create driver page and client page also create oll driver , client layer

This commit is contained in:
m7amedez5511
2026-06-14 16:25:56 +03:00
parent 68bfce4345
commit bcc4baf28a
35 changed files with 5551 additions and 816 deletions

184
hooks/useClientAddresses.ts Normal file
View File

@@ -0,0 +1,184 @@
"use client";
import { useCallback, useEffect, useReducer, useState } from "react";
import { getStoredToken } from "../lib/auth";
import { clientAddressService } from "../services/clientAddress.service";
import type {
ClientAddress,
ClientAddressFormData,
AddressTableAction,
AddressTableState,
} from "../types/client";
// ── Notification ───────────────────────────────────────────────────────────
export interface Notification {
type: "success" | "error";
message: string;
}
// ── Reducer ────────────────────────────────────────────────────────────────
function reducer(s: AddressTableState, a: AddressTableAction): AddressTableState {
switch (a.type) {
case "LOAD_START":
return { ...s, loading: true, error: null };
case "LOAD_OK":
return { ...s, loading: false, addresses: a.addresses };
case "LOAD_ERR":
return { ...s, loading: false, error: a.error };
case "ADD":
return { ...s, addresses: [...s.addresses, a.address] };
case "UPDATE":
return {
...s,
addresses: s.addresses.map((a2) =>
a2.id === a.address.id ? a.address : a2
),
};
case "DELETE":
return {
...s,
addresses: s.addresses.filter((a2) => a2.id !== a.id),
};
case "CLEAR_ERR":
return { ...s, error: null };
default:
return s;
}
}
const initialState: AddressTableState = {
addresses: [],
loading: true,
error: null,
};
// ── Main hook ──────────────────────────────────────────────────────────────
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 ──────────────────────────────────────────────────────
const loadAddresses = useCallback(async () => {
if (!clientId) return;
dispatch({ type: "LOAD_START" });
try {
const token = getStoredToken();
const res = await clientAddressService.getAll(clientId, token);
const payload = (res as any).data ?? res;
dispatch({
type: "LOAD_OK",
addresses: Array.isArray(payload) ? payload : (payload.data ?? []),
});
} catch {
dispatch({
type: "LOAD_ERR",
error: "تعذّر تحميل العناوين. يرجى المحاولة مجدداً.",
});
}
}, [clientId]);
useEffect(() => {
loadAddresses();
}, [loadAddresses]);
// ── CREATE ───────────────────────────────────────────────────────────────
const createAddress = useCallback(
async (data: ClientAddressFormData): Promise<boolean> => {
try {
const token = getStoredToken();
const res = await clientAddressService.create(clientId, data, token);
dispatch({ type: "ADD", address: res.data });
notify({ type: "success", message: "تم إضافة العنوان بنجاح." });
return true;
} catch (err) {
notify({
type: "error",
message: err instanceof Error ? err.message : "تعذّر إضافة العنوان.",
});
return false;
}
},
[clientId, notify],
);
// ── UPDATE ───────────────────────────────────────────────────────────────
const updateAddress = useCallback(
async (id: string, data: ClientAddressFormData): Promise<boolean> => {
try {
const token = getStoredToken();
const res = await clientAddressService.update(clientId, id, data, token);
dispatch({ type: "UPDATE", address: res.data });
notify({ type: "success", message: "تم تحديث العنوان." });
return true;
} catch (err) {
notify({
type: "error",
message: err instanceof Error ? err.message : "تعذّر تحديث العنوان.",
});
return false;
}
},
[clientId, notify],
);
// ── DELETE ───────────────────────────────────────────────────────────────
const deleteAddress = useCallback(
async (id: string): Promise<boolean> => {
try {
const token = getStoredToken();
await clientAddressService.delete(clientId, id, token);
dispatch({ type: "DELETE", id });
notify({ type: "success", message: "تم حذف العنوان بنجاح." });
return true;
} catch (err) {
notify({
type: "error",
message: err instanceof Error ? err.message : "تعذّر حذف العنوان.",
});
return false;
}
},
[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,
clearError: () => dispatch({ type: "CLEAR_ERR" }),
createAddress,
updateAddress,
deleteAddress,
makePrimary,
reload: loadAddresses,
};
}

View File

@@ -1,45 +0,0 @@
"use client";
import { useEffect, useState } from "react";
import { clientService } from "@/services/client.service";
import type { Order } from "../types/client";
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;
}

191
hooks/useClients.ts Normal file
View File

@@ -0,0 +1,191 @@
"use client";
import { useCallback, useEffect, useReducer, useState } from "react";
import { getStoredToken } from "../lib/auth";
import { clientService } from "../services/client.service";
import type {
Client,
ClientFormData,
ClientTableAction,
ClientTableState,
} from "../types/client";
// ── Notification (mirrors useUsers Notification) ───────────────────────────
export interface Notification {
type: "success" | "error";
message: string;
}
// ── Reducer ────────────────────────────────────────────────────────────────
function reducer(s: ClientTableState, a: ClientTableAction): ClientTableState {
switch (a.type) {
case "LOAD_START":
return { ...s, loading: true, error: null };
case "LOAD_OK":
return {
...s,
loading: false,
clients: a.clients,
total: a.total,
pages: a.pages,
};
case "LOAD_ERR":
return { ...s, loading: false, error: a.error };
case "ADD":
return { ...s, clients: [a.client, ...s.clients], total: s.total + 1 };
case "UPDATE":
return {
...s,
clients: s.clients.map((c) => (c.id === a.client.id ? a.client : c)),
};
case "DELETE":
return {
...s,
clients: s.clients.filter((c) => c.id !== a.id),
total: Math.max(0, s.total - 1),
};
case "CLEAR_ERR":
return { ...s, error: null };
default:
return s;
}
}
const initialState: ClientTableState = {
clients: [],
loading: true,
total: 0,
pages: 1,
error: null,
};
// ── Main hook ──────────────────────────────────────────────────────────────
export function useClients() {
const [state, dispatch] = useReducer(reducer, initialState);
const [search, setSearch] = useState("");
const [page, setPage] = useState(1);
const [notification, setNotification] = useState<Notification | null>(null);
const [roles, setRoles] = useState<[]>([]); // placeholder — extend if needed
const [branches, setBranches] = useState<[]>([]); // placeholder — extend if needed
/** Show a toast for 4 seconds then auto-dismiss — identical to useUsers. */
const notify = useCallback((n: Notification) => {
setNotification(n);
setTimeout(() => setNotification(null), 4000);
}, []);
// ── Fetch clients ────────────────────────────────────────────────────────
const loadClients = useCallback(async (p: number, q: string) => {
dispatch({ type: "LOAD_START" });
try {
const token = getStoredToken();
const res = await clientService.getAll(p, q, token);
// Normalise both pagination shapes the backend might return
const payload = (res as any).data ?? res;
dispatch({
type: "LOAD_OK",
clients: 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 whenever page or search changes
useEffect(() => {
loadClients(page, search);
}, [page, search, loadClients]);
// ── Search helper (resets to page 1) ────────────────────────────────────
const handleSearch = useCallback((q: string) => {
setSearch(q);
setPage(1);
}, []);
// ── CREATE ───────────────────────────────────────────────────────────────
const createClient = useCallback(
async (data: ClientFormData): Promise<boolean> => {
try {
const token = getStoredToken();
const res = await clientService.create(data, token);
dispatch({ type: "ADD", client: res.data });
notify({ type: "success", message: "تم إضافة العميل بنجاح." });
return true;
} catch (err) {
notify({
type: "error",
message: err instanceof Error ? err.message : "تعذّر إضافة العميل.",
});
return false;
}
},
[notify],
);
// ── UPDATE ───────────────────────────────────────────────────────────────
const updateClient = useCallback(
async (id: string, data: ClientFormData): Promise<boolean> => {
try {
const token = getStoredToken();
const res = await clientService.update(id, data, token);
dispatch({ type: "UPDATE", client: res.data });
notify({ type: "success", message: "تم تحديث بيانات العميل." });
return true;
} catch (err) {
notify({
type: "error",
message: err instanceof Error ? err.message : "تعذّر تحديث العميل.",
});
return false;
}
},
[notify],
);
// ── DELETE ───────────────────────────────────────────────────────────────
const deleteClient = useCallback(
async (id: string): Promise<boolean> => {
try {
const token = getStoredToken();
await clientService.delete(id, token);
dispatch({ type: "DELETE", id });
notify({ type: "success", message: "تم حذف العميل بنجاح." });
return true;
} catch (err) {
notify({
type: "error",
message: err instanceof Error ? err.message : "تعذّر حذف العميل.",
});
return false;
}
},
[notify],
);
return {
// table state
...state,
// pagination & search
page,
search,
setPage,
handleSearch,
clearError: () => dispatch({ type: "CLEAR_ERR" }),
// CRUD
createClient,
updateClient,
deleteClient,
// toast
notification,
// extras (currently unused, kept for future parity with useUsers)
roles,
branches,
reload: () => loadClients(page, search),
};
}

152
hooks/useDriver.ts Normal file
View File

@@ -0,0 +1,152 @@
"use client";
import { useCallback, useEffect, useReducer, useState } from "react";
import { getStoredToken } from "../lib/auth";
import { driverService } from "../services/driver.service";
import type { Driver } from "../types/driver";
// ── Notification type ──────────────────────────────────────────────────────
export interface DriverNotification {
type: "success" | "error";
message: string;
}
// ── Table state / reducer ──────────────────────────────────────────────────
interface TableState {
drivers: Driver[];
loading: boolean;
total: number;
pages: number;
error: string | null;
}
type TableAction =
| { type: "LOAD_START" }
| { type: "LOAD_OK"; drivers: Driver[]; total: number; pages: number }
| { type: "LOAD_ERR"; error: string }
| { type: "DELETE"; id: string }
| { type: "CLEAR_ERR" };
function reducer(s: TableState, a: TableAction): TableState {
switch (a.type) {
case "LOAD_START":
return { ...s, loading: true, error: null };
case "LOAD_OK":
return {
...s,
loading: false,
drivers: a.drivers,
total: a.total,
pages: a.pages,
};
case "LOAD_ERR":
return { ...s, loading: false, error: a.error };
case "DELETE":
return { ...s, drivers: s.drivers.filter((d) => d.id !== a.id) };
case "CLEAR_ERR":
return { ...s, error: null };
default:
return s;
}
}
const initialState: TableState = {
drivers: [],
loading: true,
total: 0,
pages: 1,
error: null,
};
// ── Main hook ──────────────────────────────────────────────────────────────
export function useDrivers() {
const [state, dispatch] = useReducer(reducer, initialState);
const [search, setSearch] = useState("");
const [page, setPage] = useState(1);
const [notification, setNotification] =
useState<DriverNotification | null>(null);
/** Show a toast for 4 seconds then auto-dismiss. */
const notify = useCallback((n: DriverNotification) => {
setNotification(n);
setTimeout(() => setNotification(null), 4000);
}, []);
// ── Fetch drivers ─────────────────────────────────────────────────────────
const loadDrivers = useCallback(async (p: number, q: string) => {
dispatch({ type: "LOAD_START" });
try {
const token = getStoredToken();
const res = await driverService.getAll(p, q, token);
// The response shape from the backend:
// { data: { data: Driver[], pagination: { total, page, pages }, meta?: ... } }
const payload = (
res as unknown as {
data: {
data: Driver[];
pagination?: { total: number; pages: number };
meta?: { total: number; pages: number };
};
}
).data ?? res;
dispatch({
type: "LOAD_OK",
drivers: 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 whenever page or search changes.
useEffect(() => {
loadDrivers(page, search);
}, [page, search, loadDrivers]);
// ── Delete ────────────────────────────────────────────────────────────────
const deleteDriver = useCallback(
async (id: string): Promise<boolean> => {
try {
const token = getStoredToken();
await driverService.delete(id, token);
dispatch({ type: "DELETE", id });
notify({ type: "success", message: "تم حذف السائق بنجاح." });
return true;
} catch (err) {
notify({
type: "error",
message:
err instanceof Error ? err.message : "تعذّر حذف السائق.",
});
return false;
}
},
[notify],
);
// ── Search helper ─────────────────────────────────────────────────────────
const handleSearch = useCallback((q: string) => {
setSearch(q);
setPage(1);
}, []);
return {
...state,
page,
search,
setPage,
handleSearch,
clearError: () => dispatch({ type: "CLEAR_ERR" }),
deleteDriver,
notification,
reload: () => loadDrivers(page, search),
};
}