create user pages crud also update pages ui build order and car ,driver first page interfase create model layer to componants

This commit is contained in:
m7amedez5511
2026-06-10 16:58:17 +03:00
parent 53c03e9867
commit e0e38dc87a
34 changed files with 2963 additions and 862 deletions

181
hooks/useOrder.ts Normal file
View File

@@ -0,0 +1,181 @@
"use client";
import { useCallback, useEffect, useReducer } from "react";
import { orderService } from "../services/order.service";
import type {
Order,
CreateOrderPayload,
UpdateOrderPayload,
UpdateOrderStatusPayload,
} from "../types/order";
// ── State ─────────────────────────────────────────────────
interface State {
orders: Order[];
total: number;
page: number;
totalPages: number;
loading: boolean;
submitting: boolean;
error: string | null;
}
type Action =
| { type: "FETCH_START" }
| { type: "FETCH_SUCCESS"; payload: { orders: Order[]; total: number; totalPages: number; page: number } }
| { type: "FETCH_ERROR"; error: string }
| { type: "SUBMIT_START" }
| { type: "SUBMIT_SUCCESS"; order: Order; isNew: boolean }
| { type: "SUBMIT_ERROR"; error: string }
| { type: "DELETE_SUCCESS"; id: string }
| { type: "CLEAR_ERROR" };
const initialState: State = {
orders: [],
total: 0,
page: 1,
totalPages: 1,
loading: false,
submitting: false,
error: null,
};
function reducer(state: State, action: Action): State {
switch (action.type) {
case "FETCH_START":
return { ...state, loading: true, error: null };
case "FETCH_SUCCESS":
return {
...state,
loading: false,
orders: action.payload.orders,
total: action.payload.total,
totalPages: action.payload.totalPages,
page: action.payload.page,
};
case "FETCH_ERROR":
return { ...state, loading: false, error: action.error };
case "SUBMIT_START":
return { ...state, submitting: true, error: null };
case "SUBMIT_SUCCESS":
return {
...state,
submitting: false,
orders: action.isNew
? [action.order, ...state.orders]
: state.orders.map((o) => (o.id === action.order.id ? action.order : o)),
};
case "SUBMIT_ERROR":
return { ...state, submitting: false, error: action.error };
case "DELETE_SUCCESS":
return { ...state, orders: state.orders.filter((o) => o.id !== action.id) };
case "CLEAR_ERROR":
return { ...state, error: null };
default:
return state;
}
}
// ── Hook ──────────────────────────────────────────────────
export function useOrders(autoFetch = true) {
const [state, dispatch] = useReducer(reducer, initialState);
const fetchOrders = useCallback(
async (page = 1, limit = 20) => {
dispatch({ type: "FETCH_START" });
try {
const res = await orderService.getAll({ page, limit });
const body = (res as unknown as { data: { data: Order[]; meta: { total: number; totalPages: number; page: number } } }).data;
dispatch({
type: "FETCH_SUCCESS",
payload: {
orders: body.data,
total: body.meta.total,
totalPages: body.meta.totalPages,
page: body.meta.page,
},
});
} catch (err: unknown) {
dispatch({
type: "FETCH_ERROR",
error: err instanceof Error ? err.message : "Failed to load orders",
});
}
},
[],
);
const createOrder = useCallback(async (payload: CreateOrderPayload) => {
dispatch({ type: "SUBMIT_START" });
try {
const res = await orderService.create(payload);
const order = (res as unknown as { data: Order }).data;
dispatch({ type: "SUBMIT_SUCCESS", order, isNew: true });
return order;
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : "Failed to create order";
dispatch({ type: "SUBMIT_ERROR", error: msg });
throw new Error(msg);
}
}, []);
const updateOrder = useCallback(
async (id: string, payload: UpdateOrderPayload) => {
dispatch({ type: "SUBMIT_START" });
try {
const res = await orderService.update(id, payload);
const order = (res as unknown as { data: Order }).data;
dispatch({ type: "SUBMIT_SUCCESS", order, isNew: false });
return order;
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : "Failed to update order";
dispatch({ type: "SUBMIT_ERROR", error: msg });
throw new Error(msg);
}
},
[],
);
const updateStatus = useCallback(
async (id: string, payload: UpdateOrderStatusPayload) => {
dispatch({ type: "SUBMIT_START" });
try {
const res = await orderService.updateStatus(id, payload);
const order = (res as unknown as { data: Order }).data;
dispatch({ type: "SUBMIT_SUCCESS", order, isNew: false });
return order;
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : "Failed to update status";
dispatch({ type: "SUBMIT_ERROR", error: msg });
throw new Error(msg);
}
},
[],
);
const deleteOrder = useCallback(async (id: string) => {
try {
await orderService.delete(id);
dispatch({ type: "DELETE_SUCCESS", id });
} catch (err: unknown) {
dispatch({
type: "FETCH_ERROR",
error: err instanceof Error ? err.message : "Failed to delete order",
});
}
}, []);
useEffect(() => {
if (autoFetch) fetchOrders();
}, [autoFetch, fetchOrders]);
return {
...state,
fetchOrders,
createOrder,
updateOrder,
updateStatus,
deleteOrder,
clearError: () => dispatch({ type: "CLEAR_ERROR" }),
};
}

166
hooks/useUser.ts Normal file
View File

@@ -0,0 +1,166 @@
"use client";
import { useCallback, useEffect, useReducer, useState } from "react";
import { getStoredToken } from "../lib/auth";
import { userService } from "../services/user.service";
import type { Branch } from "../types/branch";
import type { Role } from "../types/role";
import type {
TableAction,
TableState,
User,
UserFormData,
} from "../types/user";
// ── message taype─────────────────────────────────────────
export interface Notification {
type: "success" | "error";
message: string;
}
// ── 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, users: a.users, total: a.total, pages: a.pages };
case "LOAD_ERR": return { ...s, loading: false, error: a.error };
case "ADD": return { ...s, users: [a.user, ...s.users] };
case "UPDATE": return { ...s, users: s.users.map(u => u.id === a.user.id ? a.user : u) };
case "DELETE": return { ...s, users: s.users.filter(u => u.id !== a.id) };
case "CLEAR_ERR": return { ...s, error: null };
default: return s;
}
}
// ── first status ─────────────────────────────────────────────────────────
const initialState: TableState = {
users: [], loading: true, total: 0, pages: 1, error: null,
};
// ── main hook ──────────────────────────────────────────────────────────────
export function useUsers() {
const [state, dispatch] = useReducer(tableReducer, initialState);
const [search, setSearch] = useState("");
const [page, setPage] = useState(1);
const [roles, setRoles] = useState<Role[]>([]);
const [branches, setBranches] = useState<Branch[]>([]);
const [notification, setNotification] = useState<Notification | null>(null);
// notify with auto-dismiss after 4s
const notify = useCallback((n: Notification) => {
setNotification(n);
setTimeout(() => setNotification(null), 4000);
}, []);
// fetch users with pagination and search
const loadUsers = useCallback(async (p: number, q: string) => {
dispatch({ type: "LOAD_START" });
try {
const token = getStoredToken();
const res = await userService.getAll(p, q, token);
const payload = res.data ?? res;
dispatch({
type: "LOAD_OK",
users: payload.data ?? [],
total: payload.meta?.total ?? 0,
pages: payload.meta?.pages ?? 1,
});
} catch {
dispatch({ type: "LOAD_ERR", error: "عذراً، حدث خطأ أثناء تحميل بيانات المستخدمين. يرجى المحاولة لاحقاً." });
}
}, []);
// fetch roles and branches for form dropdowns on mount
useEffect(() => {
const token = getStoredToken();
userService.getRoles(token)
.then(res => setRoles((res.data ?? res).data ?? []))
.catch(() => {});
userService.getBranches(token)
.then(res => setBranches((res.data ?? res).data ?? []))
.catch(() => {});
}, []);
// reload users when page or search changes
useEffect(() => {
loadUsers(page, search);
}, [page, search, loadUsers]);
// create new user
const createUser = useCallback(async (data: UserFormData): Promise<boolean> => {
try {
const token = getStoredToken();
const res = await userService.create(data as UserFormData & { password: string }, token);
dispatch({ type: "ADD", user: 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 user
const updateUser = useCallback(async (id: string, data: UserFormData): Promise<boolean> => {
try {
const token = getStoredToken();
const res = await userService.update(id, data, token);
dispatch({ type: "UPDATE", user: 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]);
// deletwe user
const deleteUser = useCallback(async (id: string): Promise<boolean> => {
try {
const token = getStoredToken();
await userService.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,
// dropdown data for forms
roles,
branches,
// pagination and search state
page,
search,
setPage,
handleSearch,
clearError,
//main actions
createUser,
updateUser,
deleteUser,
// notifications for success/error messages
notification,
};
}