inogen/app/admin/pages/UsersPage.tsx
2026-10-18 18:12:59 +03:30

86 lines
7.8 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { KeyRound, Plus, Save } from "lucide-react";
import { useEffect, useMemo, useState, type FormEvent } from "react";
import { useAuth } from "../auth/AuthContext";
import { Button, Card, EmptyState, ErrorBanner, Field, Input, PageTitle, Select } from "../components/Ui";
import { api } from "../lib/api";
import type { AdminUser } from "../types";
import { ListToolbar, PaginationControls } from "../components/ListControls";
export function UsersPage() {
const { user: currentUser } = useAuth();
const [users, setUsers] = useState<AdminUser[]>([]);
const [drafts, setDrafts] = useState<Record<string, {displayName:string;role:"Admin"|"Viewer";isActive:boolean}>>({});
const [resetTarget, setResetTarget] = useState<AdminUser|null>(null);
const [error, setError] = useState("");
const [busy, setBusy] = useState("");
const [search,setSearch]=useState(""); const [roleFilter,setRoleFilter]=useState("");
const [activeFilter,setActiveFilter]=useState(""); const [page,setPage]=useState(1); const [pageSize,setPageSize]=useState(25);
const filtered=useMemo(()=>{const q=search.trim().toLocaleLowerCase("fa");return users.filter(x=>(!q||x.userName.toLocaleLowerCase().includes(q)||x.displayName.toLocaleLowerCase("fa").includes(q))&&(!roleFilter||x.role===roleFilter)&&(!activeFilter||String(x.isActive)===activeFilter));},[users,search,roleFilter,activeFilter]);
const visible=useMemo(()=>filtered.slice((page-1)*pageSize,page*pageSize),[filtered,page,pageSize]);
useEffect(()=>setPage(1),[search,roleFilter,activeFilter,pageSize]);
async function refresh() {
const result = await api<AdminUser[]>("/api/v1/administration/users");
setUsers(result);
setDrafts(Object.fromEntries(result.map(x => [x.id, { displayName:x.displayName, role:x.role, isActive:x.isActive }])));
}
useEffect(() => { void refresh().catch(reason => setError(reason.message)); }, []);
async function create(event:FormEvent<HTMLFormElement>) {
event.preventDefault(); setBusy("create"); setError("");
const form=event.currentTarget; const data=new FormData(form);
try {
await api("/api/v1/administration/users", { method:"POST", body:JSON.stringify({
userName:data.get("userName"), displayName:data.get("displayName"), password:data.get("password"), role:data.get("role")
}) });
form.reset(); await refresh();
} catch(reason) { setError(reason instanceof Error ? reason.message : "ایجاد کاربر ناموفق بود."); }
finally { setBusy(""); }
}
async function save(item:AdminUser) {
const draft=drafts[item.id]; if(!draft)return;
setBusy(item.id); setError("");
try {
await api(`/api/v1/administration/users/${item.id}`, { method:"PUT", body:JSON.stringify({...draft,version:item.version}) });
await refresh();
} catch(reason) { setError(reason instanceof Error ? reason.message : "ویرایش کاربر ناموفق بود."); }
finally { setBusy(""); }
}
async function resetPassword(event:FormEvent<HTMLFormElement>) {
event.preventDefault(); if(!resetTarget)return;
const form=event.currentTarget; const password=String(new FormData(form).get("newPassword")??"");
setBusy("reset"); setError("");
try {
await api(`/api/v1/administration/users/${resetTarget.id}/reset-password`, { method:"POST", body:JSON.stringify({newPassword:password}) });
form.reset(); setResetTarget(null); window.alert("رمز عبور با موفقیت بازنشانی شد.");
} catch(reason) { setError(reason instanceof Error ? reason.message : "بازنشانی رمز عبور ناموفق بود."); }
finally { setBusy(""); }
}
return <>
<PageTitle title="مدیریت کاربران" description="حساب‌های راهبر و مشاهده‌گر گزارش با کنترل آخرین Admin فعال"/>
{error&&<ErrorBanner message={error}/>}
<Card><div className="card-heading"><div><h3>کاربر جدید</h3><p>رمز عبور فقط هنگام ثبت ارسال می‌شود و در Audit ذخیره نمی‌شود.</p></div></div>
<form className="form-grid cols-3" onSubmit={e=>void create(e)}>
<Field label="نام کاربری"><Input name="userName" autoComplete="off" required maxLength={256}/></Field>
<Field label="نام نمایشی"><Input name="displayName" required maxLength={500}/></Field>
<Field label="نقش"><Select name="role" defaultValue="Viewer"><option value="Viewer">مشاهده‌گر گزارش</option><option value="Admin">راهبر</option></Select></Field>
<Field label="رمز اولیه" hint="حداقل ۱۲ نویسه، حرف بزرگ و کوچک، رقم و نویسه ویژه"><Input name="password" type="password" autoComplete="new-password" required minLength={12}/></Field>
<div className="form-actions"><Button disabled={busy==="create"}><Plus size={17}/>{busy==="create"?"در حال ایجاد…":"ایجاد کاربر"}</Button></div>
</form>
</Card>
<Card><div className="card-heading"><div><h3>کاربران سامانه</h3><p>{users.length} حساب تعریف‌شده</p></div></div>
<ListToolbar search={search} onSearch={setSearch} total={filtered.length} placeholder="نام کاربری یا نام نمایشی…"><Select value={roleFilter} onChange={e=>setRoleFilter(e.target.value)}><option value="">همه نقش‌ها</option><option value="Admin">راهبر</option><option value="Viewer">مشاهده‌گر گزارش</option></Select><Select value={activeFilter} onChange={e=>setActiveFilter(e.target.value)}><option value="">همه وضعیت‌ها</option><option value="true">فعال</option><option value="false">غیرفعال</option></Select></ListToolbar>
{filtered.length===0?<EmptyState title="کاربری یافت نشد" description="عبارت جست‌وجو یا فیلترها را تغییر دهید."/>:<><div className="table-wrap"><table><thead><tr><th>نام کاربری</th><th>نام نمایشی</th><th>نقش</th><th>فعال</th><th>وضعیت ورود</th><th>عملیات</th></tr></thead><tbody>{visible.map(item=>{const d=drafts[item.id];const self=item.id===currentUser?.id;return d&&<tr key={item.id}>
<td className="latin">{item.userName}</td><td><Input value={d.displayName} onChange={e=>setDrafts(x=>({...x,[item.id]:{...d,displayName:e.target.value}}))}/></td>
<td><Select value={d.role} disabled={self} onChange={e=>setDrafts(x=>({...x,[item.id]:{...d,role:e.target.value as "Admin"|"Viewer"}}))}><option value="Admin">راهبر</option><option value="Viewer">مشاهده‌گر گزارش</option></Select></td>
<td><input type="checkbox" checked={d.isActive} disabled={self} onChange={e=>setDrafts(x=>({...x,[item.id]:{...d,isActive:e.target.checked}}))}/></td>
<td>{item.isLockedOut?"قفل موقت":"عادی"}</td><td><div className="row-actions"><button className="row-action" disabled={busy===item.id} onClick={()=>void save(item)}><Save size={15}/>ذخیره</button><button className="row-action" onClick={()=>setResetTarget(item)}><KeyRound size={15}/>رمز جدید</button></div></td>
</tr>})}</tbody></table></div><PaginationControls page={page} pageSize={pageSize} total={filtered.length} loading={false} onPage={setPage} onPageSize={setPageSize}/></>}
</Card>
{resetTarget&&<Card><div className="card-heading"><div><h3>بازنشانی رمز {resetTarget.userName}</h3><p>رمز قبلی بلافاصله نامعتبر می‌شود.</p></div></div><form className="inline-form" onSubmit={e=>void resetPassword(e)}><Input name="newPassword" type="password" autoComplete="new-password" required minLength={12} placeholder="رمز عبور جدید"/><Button disabled={busy==="reset"}><KeyRound size={16}/>ثبت رمز جدید</Button><Button type="button" className="secondary" onClick={()=>setResetTarget(null)}>انصراف</Button></form></Card>}
</>;
}