update client address add primary address and update client address , fixed profile page and update user layer

This commit is contained in:
m7amedez5511
2026-07-13 17:21:42 +03:00
parent 5707521b92
commit 0eebef3ba7
8 changed files with 233 additions and 50 deletions

View File

@@ -40,12 +40,14 @@ function labelIcon(label: string): string {
// ─── AddressCard ─────────────────────────────────────────────────────────── // ─── AddressCard ───────────────────────────────────────────────────────────
interface AddressCardProps { interface AddressCardProps {
address: ClientAddress; address: ClientAddress;
onEdit: () => void; onEdit: () => void;
onDelete: () => void; onDelete: () => void;
onSetPrimary: () => void;
settingPrimary: boolean; // true only while THIS card's request is in flight
} }
function AddressCard({ address, onEdit, onDelete }: AddressCardProps) { function AddressCard({ address, onEdit, onDelete, onSetPrimary, settingPrimary }: AddressCardProps) {
const { details, contactPerson } = address; const { details, contactPerson } = address;
const { const {
street, street,
@@ -195,6 +197,19 @@ function AddressCard({ address, onEdit, onDelete }: AddressCardProps) {
<ActionBtn onClick={onEdit} color="#1D4ED8" bg="#EFF6FF" border="#BFDBFE"> <ActionBtn onClick={onEdit} color="#1D4ED8" bg="#EFF6FF" border="#BFDBFE">
تعديل تعديل
</ActionBtn> </ActionBtn>
{!address.isPrimary && (
<ActionBtn
onClick={onSetPrimary}
disabled={settingPrimary}
color="#B45309"
bg="#FFFBEB"
border="#FDE68A"
>
{settingPrimary ? "جارٍ التعيين…" : "تعيين كأساسي"}
</ActionBtn>
)}
<ActionBtn <ActionBtn
onClick={onDelete} onClick={onDelete}
color="#DC2626" color="#DC2626"
@@ -346,6 +361,8 @@ export default function ClientAddressesPage() {
createAddress, createAddress,
updateAddress, updateAddress,
deleteAddress, deleteAddress,
setPrimaryAddress,
settingPrimaryId,
} = useClientAddresses(clientId ?? ""); } = useClientAddresses(clientId ?? "");
// ── Modal state ────────────────────────────────────────────────────────── // ── Modal state ──────────────────────────────────────────────────────────
@@ -374,6 +391,11 @@ export default function ClientAddressesPage() {
if (ok) setDeleteTarget(null); if (ok) setDeleteTarget(null);
}; };
// ── Set primary handler ──────────────────────────────────────────────────
const handleSetPrimary = async (address: ClientAddress) => {
await setPrimaryAddress(address.id);
};
// ── Client edit handler ────────────────────────────────────────────────── // ── Client edit handler ──────────────────────────────────────────────────
const handleClientEditSubmit = async ( const handleClientEditSubmit = async (
data: ClientFormData, data: ClientFormData,
@@ -661,6 +683,8 @@ export default function ClientAddressesPage() {
address={addr} address={addr}
onEdit={() => setAddrFormTarget(addr)} onEdit={() => setAddrFormTarget(addr)}
onDelete={() => setDeleteTarget(addr)} onDelete={() => setDeleteTarget(addr)}
onSetPrimary={() => handleSetPrimary(addr)}
settingPrimary={settingPrimaryId === addr.id}
/> />
))} ))}
</div> </div>

View File

@@ -32,19 +32,32 @@ export default function ProfilePage() {
{ label: "آخر تحديث", value: new Date(user.updatedAt).toLocaleDateString("ar-SA") }, { label: "آخر تحديث", value: new Date(user.updatedAt).toLocaleDateString("ar-SA") },
]; ];
// تجميع الصلاحيات حسب الموديول عشان تبقى منظمة وسهلة القراءة
const permissionsByModule = (user.role?.permissions ?? []).reduce<Record<string, string[]>>(
(acc, entry) => {
const mod = entry.permission.module || "أخرى";
if (!acc[mod]) acc[mod] = [];
acc[mod].push(entry.permission.name);
return acc;
},
{},
);
const modules = Object.keys(permissionsByModule);
return ( return (
<div className="mx-auto max-w-lg px-4 py-10" dir="rtl"> <div className="mx-auto max-w-2xl space-y-6 px-4 py-10" dir="rtl">
{/* بطاقة البيانات الأساسية */}
<div className="rounded-2xl bg-white p-6 shadow-md"> <div className="rounded-2xl bg-white p-6 shadow-md">
<div className="mb-6 flex flex-col items-center gap-3"> <div className="mb-6 flex flex-col items-center gap-3">
<img <div className="flex h-20 w-20 items-center justify-center rounded-full bg-blue-50 text-2xl font-semibold text-blue-600 ring-2 ring-blue-100">
src={user.photo ?? "/images/avatar-placeholder.png"} {user.name?.trim().charAt(0) ?? "?"}
alt={user.name} </div>
className="h-20 w-20 rounded-full object-cover ring-2 ring-blue-100"
onError={(e) => {
(e.target as HTMLImageElement).src = "/images/avatar-placeholder.png";
}}
/>
<h1 className="text-base font-semibold text-slate-900">{user.name}</h1> <h1 className="text-base font-semibold text-slate-900">{user.name}</h1>
{user.role?.name && (
<span className="rounded-full bg-blue-50 px-3 py-1 text-xs font-medium text-blue-700">
{user.role.name}
</span>
)}
</div> </div>
{/* عرض البيانات بشكل read-only بدون أي فورم أو زرار تعديل */} {/* عرض البيانات بشكل read-only بدون أي فورم أو زرار تعديل */}
@@ -57,6 +70,54 @@ export default function ProfilePage() {
))} ))}
</dl> </dl>
</div> </div>
{/* بطاقة الدور والصلاحيات */}
{user.role && (
<div className="rounded-2xl bg-white p-6 shadow-md">
<div className="mb-4">
<h2 className="text-sm font-semibold text-slate-900">الدور والصلاحيات</h2>
{user.role.description && (
<p className="mt-1 text-[13px] text-slate-500">{user.role.description}</p>
)}
</div>
{modules.length === 0 ? (
<p className="text-[13px] text-slate-400">لا توجد صلاحيات مسجّلة لهذا الدور.</p>
) : (
<div className="space-y-2">
{modules.map((mod) => (
<details
key={mod}
className="group rounded-lg border border-slate-100 open:bg-slate-50"
open
>
<summary className="flex cursor-pointer list-none items-center justify-between px-3 py-2.5 text-[13px] font-medium text-slate-700">
<span className="flex items-center gap-2">
{mod}
<span className="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-normal text-slate-500">
{permissionsByModule[mod].length}
</span>
</span>
<span className="text-slate-400 transition-transform group-open:rotate-180">
</span>
</summary>
<div className="flex flex-wrap gap-2 px-3 pb-3 pt-1">
{permissionsByModule[mod].map((name) => (
<span
key={name}
className="rounded-md bg-blue-50 px-2.5 py-1 text-[12px] font-medium text-blue-700"
>
{name}
</span>
))}
</div>
</details>
))}
</div>
)}
</div>
)}
</div> </div>
); );
} }

View File

@@ -19,10 +19,14 @@ import { Notification } from "../types/notif";
function normalizeAddress(raw: unknown): ClientAddress { function normalizeAddress(raw: unknown): ClientAddress {
const data = raw as { id?: string; _id?: string; [key: string]: unknown }; const data = raw as { id?: string; _id?: string; [key: string]: unknown };
// FIXED: fallback to "" so the type is always `string`, never `string | undefined`
const id = data.id ?? data._id ?? "";
return { return {
...data, ...data,
id: data.id ?? data._id, id,
}; } as ClientAddress;
} }
function normalizeAddresses(rawList: unknown[]): ClientAddress[] { function normalizeAddresses(rawList: unknown[]): ClientAddress[] {
@@ -54,6 +58,14 @@ function reducer(s: AddressTableState, a: AddressTableAction): AddressTableState
}; };
case "CLEAR_ERR": case "CLEAR_ERR":
return { ...s, error: null }; return { ...s, error: null };
case "SET_PRIMARY":
return {
...s,
addresses: s.addresses.map((addr) => ({
...addr,
isPrimary: addr.id === a.id,
})),
};
default: default:
return s; return s;
} }
@@ -69,6 +81,9 @@ const initialState: AddressTableState = {
export function useClientAddresses(clientId: string) { export function useClientAddresses(clientId: string) {
const [state, dispatch] = useReducer(reducer, initialState); const [state, dispatch] = useReducer(reducer, initialState);
const [notification, setNotification] = useState<Notification | null>(null); const [notification, setNotification] = useState<Notification | null>(null);
// Tracks which address is mid-request so its button can disable itself
// and duplicate clicks are ignored while a request is in flight.
const [settingPrimaryId, setSettingPrimaryId] = useState<string | null>(null);
const notify = useCallback((n: Notification) => { const notify = useCallback((n: Notification) => {
setNotification(n); setNotification(n);
@@ -76,25 +91,33 @@ export function useClientAddresses(clientId: string) {
}, []); }, []);
// ── Fetch ──────────────────────────────────────────────────────────────── // ── Fetch ────────────────────────────────────────────────────────────────
const loadAddresses = useCallback(async () => { const loadAddresses = useCallback(async () => {
if (!clientId) return; if (!clientId) return;
dispatch({ type: "LOAD_START" }); dispatch({ type: "LOAD_START" });
try { try {
const token = getStoredToken(); const token = getStoredToken();
const res = await clientAddressService.getAll(clientId, token); const res = await clientAddressService.getAll(clientId, token);
const payload = (res as unknown as { data?: unknown }).data ?? res; const payload = (res as unknown as { data?: unknown }).data ?? res;
const rawList = Array.isArray(payload) ? payload : ((payload as { data?: unknown }).data ?? []);
dispatch({ // FIXED: explicit Array.isArray checks instead of relying on
type: "LOAD_OK", // TS to narrow the ternary's return type on its own.
addresses: normalizeAddresses(rawList), const rawList: unknown[] = Array.isArray(payload)
}); ? payload
} catch { : Array.isArray((payload as { data?: unknown })?.data)
dispatch({ ? ((payload as { data?: unknown }).data as unknown[])
type: "LOAD_ERR", : [];
error: "تعذّر تحميل العناوين. يرجى المحاولة مجدداً.",
}); dispatch({
} type: "LOAD_OK",
}, [clientId]); addresses: normalizeAddresses(rawList),
});
} catch {
dispatch({
type: "LOAD_ERR",
error: "تعذّر تحميل العناوين. يرجى المحاولة مجدداً.",
});
}
}, [clientId]);
useEffect(() => { useEffect(() => {
loadAddresses(); loadAddresses();
@@ -160,6 +183,33 @@ export function useClientAddresses(clientId: string) {
[clientId, notify], [clientId, notify],
); );
// ── SET PRIMARY ──────────────────────────────────────────────────────────
const setPrimaryAddress = useCallback(
async (id: string): Promise<boolean> => {
if (settingPrimaryId) return false; // guard against overlapping requests
setSettingPrimaryId(id);
try {
const token = getStoredToken();
await clientAddressService.setPrimary(id, token);
// We already know the shape of the change (target -> true, everyone
// else -> false), so we update local state directly instead of
// refetching the whole list.
dispatch({ type: "SET_PRIMARY", id });
notify({ type: "success", message: "تم تعيين العنوان كعنوان أساسي." });
return true;
} catch (err) {
notify({
type: "error",
message: err instanceof Error ? err.message : "تعذّر تعيين العنوان كأساسي.",
});
return false;
} finally {
setSettingPrimaryId(null);
}
},
[notify, settingPrimaryId],
);
return { return {
...state, ...state,
notification, notification,
@@ -167,6 +217,8 @@ export function useClientAddresses(clientId: string) {
createAddress, createAddress,
updateAddress, updateAddress,
deleteAddress, deleteAddress,
setPrimaryAddress,
settingPrimaryId,
reload: loadAddresses, reload: loadAddresses,
}; };
} }

View File

@@ -16,7 +16,10 @@ export function useCurrentUser() {
try { try {
const token = getStoredToken(); const token = getStoredToken();
const res = await userService.getMe(token); const res = await userService.getMe(token);
const u = extractMeUser(res.data ?? res); // ملاحظة: مبقاش بنعمل res.data ?? res هنا قبل التمرير.
// extractMeUser هي المسؤولة الوحيدة عن تفكيك شكل الـ response،
// فبنبعتلها الـ res زي ما هو عشان نتجنب تفكيك مزدوج.
const u = extractMeUser(res);
if (!u) throw new Error("لا توجد بيانات"); if (!u) throw new Error("لا توجد بيانات");
setUser(u as UserMe); setUser(u as UserMe);
} catch { } catch {

View File

@@ -65,6 +65,13 @@ export const clientAddressService = {
delete: (clientId: string, addressId: string, token: string | null) => delete: (clientId: string, addressId: string, token: string | null) =>
del<void>(addressBase(addressId), token), del<void>(addressBase(addressId), token),
/**
* Set an address as primary for its client.
* PATCH /v1/addresses/:id/primary — no request body.
* Backend unsets isPrimary on all sibling addresses automatically.
*/
setPrimary: (addressId: string, token: string | null) =>
patch<ApiResponse<ClientAddress>>(`${addressBase(addressId)}/primary`, {}, token),
}; };

View File

@@ -1,17 +1,16 @@
import { get, post, put, del } from "./api"; import { get, post, put, del } from "./api";
import type { ApiListResponse, User, UserFormData, UserResponse } from "@/src/types/user"; import type { ApiListResponse, User, UserFormData, UserResponse, UserMe } from "@/src/types/user";
import type { Role } from "@/src/types/role"; import type { Role } from "@/src/types/role";
import type { Branch } from "@/src/types/branch"; import type { Branch } from "@/src/types/branch";
// الشكل الحقيقي لاستجابة /users/me:
// { success, message, responseAt, data: <UserMe> }
// أي "data" هنا هي بيانات اليوزر مباشرة، مفيش data.data متداخلة.
export interface MeApiResponse { export interface MeApiResponse {
success: boolean; success: boolean;
message: string; message: string;
responseAt: string; responseAt: string;
data: { data: UserMe;
data: User[] | User;
meta?: { total: number; page: number; limit: number; totalPages: number };
};
} }
@@ -60,10 +59,25 @@ export const userService = {
getMe: (token: string | null) => getMe: (token: string | null) =>
get<MeApiResponse>("users/me", token), get<MeApiResponse>("users/me", token),
}; };
export function extractMeUser(res: MeApiResponse): User | null {
const d = res.data?.data; /**
if (Array.isArray(d)) return d[0] ?? null; * بتفكك استجابة /users/me لأي شكل ييجي بيه من السيرفر:
return d ?? null; * - سواء الـ get() بيرجع الـ body مباشرة: { success, data: <user> }
* - أو بيرجع wrapper شكله axios-like: { data: { success, data: <user> } }
* فبناخد أول data موجودة (لو فيها success/message نبقى في المكان الصح)،
* وبعدين ناخد الـ data اللي جواها (بيانات اليوزر الفعلية).
* ملحوظة: مفيش تفكيك مزدوج بره الدالة دي، وأي حد بينادي عليها
* لازم يبعتلها الـ response زي ما هو من غير ما يعمل res.data قبلها.
*/
export function extractMeUser(res: MeApiResponse | { data: MeApiResponse }): UserMe | null {
const body: MeApiResponse = (res as { data: MeApiResponse })?.data?.data
? (res as { data: MeApiResponse }).data
: (res as MeApiResponse);
const d = body?.data;
if (!d) return null;
if (Array.isArray(d)) return (d[0] as UserMe) ?? null;
return d as UserMe;
} }
/** Converting the form data into a payload suitable for the API */ /** Converting the form data into a payload suitable for the API */

View File

@@ -80,7 +80,9 @@ export type AddressTableAction =
| { type: "ADD"; address: ClientAddress } | { type: "ADD"; address: ClientAddress }
| { type: "UPDATE"; address: ClientAddress } | { type: "UPDATE"; address: ClientAddress }
| { type: "DELETE"; id: string } | { type: "DELETE"; id: string }
| { type: "CLEAR_ERR" }; | { type: "CLEAR_ERR" }
// ADDED: Set primary address — flips isPrimary across the whole list in one dispatch
| { type: "SET_PRIMARY"; id: string };
// ─── Archive: Client Addresses ───────────────────────────────────────────── // ─── Archive: Client Addresses ─────────────────────────────────────────────
// Archived address resource returned by GET /addresses/archived. // Archived address resource returned by GET /addresses/archived.

View File

@@ -6,8 +6,8 @@ export interface User {
phone: string; phone: string;
isActive: boolean; isActive: boolean;
createdAt: string; createdAt: string;
role?: { id?: string; name: string }; role?: { id?: string; name: string } | null;
branch?: { id?: string; name: string }; branch?: { id?: string; name: string } | null;
} }
export interface UserResponse { export interface UserResponse {
data: User; data: User;
@@ -113,8 +113,28 @@ export interface ApiErrorResponse {
}; };
} }
export interface Permission {
name: string;
slug: string;
module: string;
}
export interface RolePermissionEntry {
permission: Permission;
}
export interface UserRoleDetail {
name: string;
description?: string;
permissions?: RolePermissionEntry[];
isActive?: boolean;
isDeleted?: boolean;
}
export interface UserMe extends User { export interface UserMe extends User {
photo: string | null; photo: string | null;
isDeleted: boolean; isDeleted: boolean;
updatedAt: string; updatedAt: string;
role?: UserRoleDetail | null;
branch?: { id?: string; name: string } | null;
} }