eCourt-note/utils/user.ts

52 lines
2.7 KiB
TypeScript
Raw Normal View History

// anonymous identity เก็บใน localStorage สร้างครั้งเดียวต่อ browser (PLAN.md §0 A4)
// ใช้เติม field userId/userName ในตาราง annotations/bookmarks — ไม่มีระบบ auth
export type LocalUser = { userId: string; userName: string };
const STORAGE_KEY = "judes-note:user";
// mock users สำหรับเลือกที่หน้าแรก (demo ไม่มีระบบ auth) — userId คงที่
// เพื่อให้กรองรายคนและสิทธิ์ "แก้ไขได้เฉพาะของตัวเอง" ทำงานสม่ำเสมอข้าม refresh
export const MOCK_USERS: LocalUser[] = [
{ userId: "mock-user-01", userName: "ผู้พิพากษา สมชาย" },
{ userId: "mock-user-02", userName: "ผู้พิพากษา สมหญิง" },
{ userId: "mock-user-03", userName: "อัยการ วิชัย" },
{ userId: "mock-user-04", userName: "เลขานุการศาล ปิยะ" },
{ userId: "mock-user-05", userName: "ทนายโจทก์ ณัฐ" },
{ userId: "mock-user-06", userName: "ทนายจำเลย อรุณี" },
{ userId: "mock-user-07", userName: "ผู้ช่วยผู้พิพากษา กันต์" },
{ userId: "mock-user-08", userName: "พนักงานสอบสวน เดชา" },
{ userId: "mock-user-09", userName: "ผู้เชี่ยวชาญ มานะ" },
{ userId: "mock-user-10", userName: "ผู้ช่วยเลขานุการ ฝ้าย" },
];
export function setLocalUser(user: LocalUser): void {
localStorage.setItem(STORAGE_KEY, JSON.stringify(user));
}
// อ่าน identity ที่เก็บไว้โดยไม่สร้างใหม่ — ใช้แสดงค่าปัจจุบันในหน้าเลือกผู้ใช้
export function getStoredLocalUser(): LocalUser | null {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
try {
const parsed = JSON.parse(raw) as LocalUser;
if (typeof parsed.userId === "string" && typeof parsed.userName === "string") {
return parsed;
}
} catch {
// ข้อมูลเก่าเสียหาย → ถือว่าไม่มีข้อมูล
}
}
return null;
}
export function getLocalUser(): LocalUser {
const stored = getStoredLocalUser();
if (stored) return stored;
const userId = crypto.randomUUID();
const userName = `ผู้ใช้ ${userId.slice(0, 4).toUpperCase()}`;
localStorage.setItem(STORAGE_KEY, JSON.stringify({ userId, userName }));
return { userId, userName };
}