update client and client adresses pages also create branch pages and role pages and update some pages to be batter
This commit is contained in:
145
src/hooks/useBranch.ts
Normal file
145
src/hooks/useBranch.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useReducer, useState } from "react";
|
||||
import { getStoredToken } from "@/src/lib/auth";
|
||||
import { branchService } from "@/src/services/branch.service";
|
||||
import type {
|
||||
Branch,
|
||||
BranchFormData,
|
||||
TableAction,
|
||||
TableState,
|
||||
} from "@/src/types/branch";
|
||||
import type { ToastNotification } from "@/src/Components/UI";
|
||||
|
||||
export type Notification = ToastNotification;
|
||||
|
||||
// ── Reducer ──────────────────────────────────────
|
||||
function tableReducer(s: TableState, a: TableAction): TableState {
|
||||
switch (a.type) {
|
||||
case "LOAD_START": return { ...s, loading: true, error: null };
|
||||
case "LOAD_OK": return { ...s, loading: false, branches: a.branches, total: a.total, pages: a.pages };
|
||||
case "LOAD_ERR": return { ...s, loading: false, error: a.error };
|
||||
case "ADD": return { ...s, branches: [a.branch, ...s.branches] };
|
||||
case "UPDATE": return { ...s, branches: s.branches.map(b => b.id === a.branch.id ? a.branch : b) };
|
||||
case "DELETE": return { ...s, branches: s.branches.filter(b => b.id !== a.id) };
|
||||
case "CLEAR_ERR": return { ...s, error: null };
|
||||
default: return s;
|
||||
}
|
||||
}
|
||||
|
||||
// ── first status ─────────────────────────────────────────────────────────
|
||||
const initialState: TableState = {
|
||||
branches: [], loading: true, total: 0, pages: 1, error: null,
|
||||
};
|
||||
|
||||
// ── main hook ──────────────────────────────────────────────────────────────
|
||||
export function useBranches() {
|
||||
const [state, dispatch] = useReducer(tableReducer, initialState);
|
||||
const [search, setSearch] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [notification, setNotification] = useState<ToastNotification | null>(null);
|
||||
|
||||
// notify with auto-dismiss after 4s
|
||||
const notify = useCallback((n: ToastNotification) => {
|
||||
setNotification(n);
|
||||
setTimeout(() => setNotification(null), 4000);
|
||||
}, []);
|
||||
|
||||
// fetch branches with pagination and search
|
||||
const loadBranches = useCallback(async (p: number, q: string) => {
|
||||
dispatch({ type: "LOAD_START" });
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const res = await branchService.getAll(p, q, token);
|
||||
const payload = res.data ?? res;
|
||||
dispatch({
|
||||
type: "LOAD_OK",
|
||||
branches: payload.data ?? [],
|
||||
total: payload.meta?.total ?? payload.pagination?.total ?? 0,
|
||||
pages: payload.meta?.pages ?? payload.pagination?.pages ?? 1,
|
||||
});
|
||||
} catch {
|
||||
dispatch({ type: "LOAD_ERR", error: "عذراً، حدث خطأ أثناء تحميل بيانات الفروع. يرجى المحاولة لاحقاً." });
|
||||
}
|
||||
}, []);
|
||||
|
||||
// reload branches when page or search changes
|
||||
useEffect(() => {
|
||||
loadBranches(page, search);
|
||||
}, [page, search, loadBranches]);
|
||||
|
||||
// create new branch
|
||||
const createBranch = useCallback(async (data: BranchFormData): Promise<boolean> => {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const res = await branchService.create(data, token);
|
||||
dispatch({ type: "ADD", branch: res.data });
|
||||
notify({ type: "success", message: "تم إضافة الفرع بنجاح." });
|
||||
return true;
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error && err.message
|
||||
? err.message
|
||||
: "تعذر الاتصال بالخادم. تحقق من اتصالك بالإنترنت.";
|
||||
notify({ type: "error", message: msg });
|
||||
return false;
|
||||
}
|
||||
}, [notify]);
|
||||
|
||||
// update existing branch
|
||||
const updateBranch = useCallback(async (id: string, data: BranchFormData): Promise<boolean> => {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const res = await branchService.update(id, data, token);
|
||||
dispatch({ type: "UPDATE", branch: res.data });
|
||||
notify({ type: "success", message: "تم تحديث الفرع بنجاح." });
|
||||
return true;
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error && err.message
|
||||
? err.message
|
||||
: "تعذر الاتصال بالخادم. تحقق من اتصالك بالإنترنت.";
|
||||
notify({ type: "error", message: msg });
|
||||
return false;
|
||||
}
|
||||
}, [notify]);
|
||||
|
||||
// delete branch
|
||||
const deleteBranch = useCallback(async (id: string): Promise<boolean> => {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
await branchService.delete(id, token);
|
||||
dispatch({ type: "DELETE", id });
|
||||
notify({ type: "success", message: "تم حذف الفرع بنجاح." });
|
||||
return true;
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error && err.message
|
||||
? err.message
|
||||
: "تعذر الاتصال بالخادم. تحقق من اتصالك بالإنترنت.";
|
||||
notify({ type: "error", message: msg });
|
||||
return false;
|
||||
}
|
||||
}, [notify]);
|
||||
|
||||
const handleSearch = useCallback((q: string) => {
|
||||
setSearch(q);
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const clearError = useCallback(() => dispatch({ type: "CLEAR_ERR" }), []);
|
||||
|
||||
return {
|
||||
//table data and status
|
||||
...state,
|
||||
// pagination and search state
|
||||
page,
|
||||
search,
|
||||
setPage,
|
||||
handleSearch,
|
||||
clearError,
|
||||
//main actions
|
||||
createBranch,
|
||||
updateBranch,
|
||||
deleteBranch,
|
||||
// notifications for success/error messages
|
||||
notification,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
"use client";
|
||||
|
||||
|
||||
import { useCallback, useEffect, useReducer, useState } from "react";
|
||||
import { getStoredToken } from "@/src/lib/auth";
|
||||
import { clientAddressService } from "@/src/services/clientAddress.service";
|
||||
@@ -8,12 +7,25 @@ import type {
|
||||
CreateAddressFormValues,
|
||||
UpdateAddressFormValues,
|
||||
} from "@/src/validations/client_address.validator";
|
||||
import { AddressTableAction, AddressTableState } from "../types/client";
|
||||
|
||||
// ── Notification ───────────────────────────────────────────────────────────
|
||||
export interface Notification {
|
||||
type: "success" | "error";
|
||||
message: string;
|
||||
import type {
|
||||
AddressTableAction,
|
||||
AddressTableState,
|
||||
ClientAddress,
|
||||
} from "../types/client_adresses";
|
||||
import { Notification } from "../types/notif";
|
||||
|
||||
|
||||
|
||||
function normalizeAddress(raw: any): ClientAddress {
|
||||
return {
|
||||
...raw,
|
||||
id: raw.id ?? raw._id,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeAddresses(rawList: any[]): ClientAddress[] {
|
||||
return rawList.map(normalizeAddress);
|
||||
}
|
||||
|
||||
// ── Reducer ────────────────────────────────────────────────────────────────
|
||||
@@ -57,13 +69,12 @@ export function useClientAddresses(clientId: string) {
|
||||
const [state, dispatch] = useReducer(reducer, initialState);
|
||||
const [notification, setNotification] = useState<Notification | null>(null);
|
||||
|
||||
/** Show a toast for 4 seconds then auto-dismiss. */
|
||||
const notify = useCallback((n: Notification) => {
|
||||
setNotification(n);
|
||||
setTimeout(() => setNotification(null), 4000);
|
||||
}, []);
|
||||
|
||||
// ── Fetch addresses ──────────────────────────────────────────────────────
|
||||
// ── Fetch ────────────────────────────────────────────────────────────────
|
||||
const loadAddresses = useCallback(async () => {
|
||||
if (!clientId) return;
|
||||
dispatch({ type: "LOAD_START" });
|
||||
@@ -71,9 +82,10 @@ export function useClientAddresses(clientId: string) {
|
||||
const token = getStoredToken();
|
||||
const res = await clientAddressService.getAll(clientId, token);
|
||||
const payload = (res as any).data ?? res;
|
||||
const rawList = Array.isArray(payload) ? payload : (payload.data ?? []);
|
||||
dispatch({
|
||||
type: "LOAD_OK",
|
||||
addresses: Array.isArray(payload) ? payload : (payload.data ?? []),
|
||||
addresses: normalizeAddresses(rawList),
|
||||
});
|
||||
} catch {
|
||||
dispatch({
|
||||
@@ -93,7 +105,7 @@ export function useClientAddresses(clientId: string) {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const res = await clientAddressService.create(clientId, data, token);
|
||||
dispatch({ type: "ADD", address: res.data });
|
||||
dispatch({ type: "ADD", address: normalizeAddress(res.data) });
|
||||
notify({ type: "success", message: "تم إضافة العنوان بنجاح." });
|
||||
return true;
|
||||
} catch (err) {
|
||||
@@ -113,7 +125,7 @@ export function useClientAddresses(clientId: string) {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const res = await clientAddressService.update(clientId, id, data, token);
|
||||
dispatch({ type: "UPDATE", address: res.data });
|
||||
dispatch({ type: "UPDATE", address: normalizeAddress(res.data) });
|
||||
notify({ type: "success", message: "تم تحديث العنوان." });
|
||||
return true;
|
||||
} catch (err) {
|
||||
@@ -147,29 +159,6 @@ export function useClientAddresses(clientId: string) {
|
||||
[clientId, notify],
|
||||
);
|
||||
|
||||
// ── SET PRIMARY ──────────────────────────────────────────────────────────
|
||||
const makePrimary = useCallback(
|
||||
async (id: string): Promise<boolean> => {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const res = await clientAddressService.setPrimary(clientId, id, token);
|
||||
// Backend demotes all others — reload to sync
|
||||
dispatch({ type: "UPDATE", address: res.data });
|
||||
// Reload to reflect the backend's cascade demotions
|
||||
await loadAddresses();
|
||||
notify({ type: "success", message: "تم تعيين العنوان الرئيسي." });
|
||||
return true;
|
||||
} catch (err) {
|
||||
notify({
|
||||
type: "error",
|
||||
message: err instanceof Error ? err.message : "تعذّر تعيين العنوان الرئيسي.",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[clientId, notify, loadAddresses],
|
||||
);
|
||||
|
||||
return {
|
||||
...state,
|
||||
notification,
|
||||
@@ -177,7 +166,6 @@ export function useClientAddresses(clientId: string) {
|
||||
createAddress,
|
||||
updateAddress,
|
||||
deleteAddress,
|
||||
makePrimary,
|
||||
reload: loadAddresses,
|
||||
};
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { clientService } from "@/src/services/client.service";
|
||||
import type { Order } from "@/src/types/order";
|
||||
|
||||
interface State {
|
||||
orders: Order[];
|
||||
error: string | null;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches all orders for a client session.
|
||||
*
|
||||
* @example
|
||||
* const { orders, loading, error } = useClientOrders(session.id);
|
||||
*/
|
||||
export function useClientOrders(clientId: string): State {
|
||||
const [state, setState] = useState<State>({
|
||||
orders: [], error: null, loading: true,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!clientId) {
|
||||
setState({ orders: [], error: null, loading: false });
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
clientService
|
||||
.getOrders(clientId)
|
||||
.then(orders => {
|
||||
if (!cancelled) setState({ orders, error: null, loading: false });
|
||||
})
|
||||
.catch((err: Error) => {
|
||||
if (!cancelled) setState({ orders: [], error: err.message, loading: false });
|
||||
});
|
||||
|
||||
return () => { cancelled = true; };
|
||||
}, [clientId]);
|
||||
|
||||
return state;
|
||||
}
|
||||
@@ -9,12 +9,9 @@ import type {
|
||||
ClientTableAction,
|
||||
ClientTableState,
|
||||
} from "@/src/types/client";
|
||||
import { Notification } from "../types/notif";
|
||||
|
||||
|
||||
// ── Notification (mirrors useUsers Notification) ───────────────────────────
|
||||
export interface Notification {
|
||||
type: "success" | "error";
|
||||
message: string;
|
||||
}
|
||||
|
||||
// ── Reducer ────────────────────────────────────────────────────────────────
|
||||
function reducer(s: ClientTableState, a: ClientTableAction): ClientTableState {
|
||||
|
||||
@@ -3,14 +3,12 @@
|
||||
import { useCallback, useEffect, useReducer, useState } from "react";
|
||||
import { getStoredToken } from "@/src/lib/auth";
|
||||
import { roleService } from "@/src/services/role.service";
|
||||
import type { Role, RoleFormData, Permission } from "@/src/services/role.service";
|
||||
import { Notification } from "../types/notif";
|
||||
import { Permission, Role, RoleFormData } from "../types/role";
|
||||
|
||||
|
||||
|
||||
// ── Notification ──────────────────────────────────────────────────────────────
|
||||
|
||||
export interface RoleNotification {
|
||||
type: "success" | "error";
|
||||
message: string;
|
||||
}
|
||||
|
||||
// ── Table state / reducer ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -76,11 +74,11 @@ export function useRoles() {
|
||||
const [search, setSearch] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [permissions, setPermissions] = useState<Permission[]>([]);
|
||||
const [notification, setNotification] = useState<RoleNotification | null>(
|
||||
const [notification, setNotification] = useState<Notification | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const notify = useCallback((n: RoleNotification) => {
|
||||
const notify = useCallback((n: Notification) => {
|
||||
setNotification(n);
|
||||
setTimeout(() => setNotification(null), 4000);
|
||||
}, []);
|
||||
@@ -144,15 +142,6 @@ export function useRoles() {
|
||||
const res = await roleService.create(data, token);
|
||||
const role = (res as unknown as { data: Role }).data;
|
||||
|
||||
// Assign permissions sequentially (backend handles individually)
|
||||
for (const pid of data.permissionIds) {
|
||||
try {
|
||||
await roleService.assignPermission(role.id, pid, token);
|
||||
} catch {
|
||||
/* non-fatal: skip individual failures */
|
||||
}
|
||||
}
|
||||
|
||||
// Re-fetch to get fresh data with permissions attached
|
||||
await loadRoles(page, search);
|
||||
notify({
|
||||
@@ -190,25 +179,11 @@ export function useRoles() {
|
||||
(p) => !data.permissionIds.includes(p),
|
||||
);
|
||||
|
||||
for (const pid of toAdd) {
|
||||
try {
|
||||
await roleService.assignPermission(id, pid, token);
|
||||
} catch {
|
||||
/* skip */
|
||||
}
|
||||
}
|
||||
for (const pid of toRemove) {
|
||||
try {
|
||||
await roleService.removePermission(id, pid, token);
|
||||
} catch {
|
||||
/* skip */
|
||||
}
|
||||
}
|
||||
|
||||
await loadRoles(page, search);
|
||||
notify({
|
||||
type: "success",
|
||||
message: "تم تحديث الدور والصلاحيات بنجاح.",
|
||||
message: "تم تحديث الدور بنجاح.",
|
||||
});
|
||||
return true;
|
||||
} catch (err) {
|
||||
@@ -240,25 +215,6 @@ export function useRoles() {
|
||||
},
|
||||
[notify],
|
||||
);
|
||||
const updateRolePermissionsBulk = useCallback(
|
||||
async (roleId: string, permissionIds: string[]): Promise<boolean> => {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const res = await roleService.setPermissions(roleId, permissionIds, token);
|
||||
const updated = (res as unknown as { data: Role }).data;
|
||||
dispatch({ type: "UPDATE", role: updated });
|
||||
notify({ type: "success", message: "تم تحديث صلاحيات الدور بنجاح." });
|
||||
return true;
|
||||
} catch (err) {
|
||||
notify({
|
||||
type: "error",
|
||||
message: err instanceof Error ? err.message : "تعذّر تحديث صلاحيات الدور.",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[notify],
|
||||
);
|
||||
|
||||
|
||||
const handleSearch = useCallback((q: string) => {
|
||||
@@ -277,7 +233,6 @@ const updateRolePermissionsBulk = useCallback(
|
||||
createRole,
|
||||
updateRole,
|
||||
deleteRole,
|
||||
updateRolePermissionsBulk,
|
||||
notification,
|
||||
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user