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

View File

@@ -1,81 +0,0 @@
"use client";
export default function ClientHomePage() {
return (
<main className="min-h-screen bg-slate-50 text-slate-900">
<section className="flex min-h-screen">
<aside className="hidden w-18 border-r border-slate-200 bg-white lg:flex lg:flex-col lg:items-center lg:py-4">
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-blue-600 text-white">🚚</div>
<nav className="mt-6 flex flex-1 flex-col items-center gap-3 text-[9px] font-semibold text-slate-400">
{['Home','New Order','Track','History','Settings'].map((label, index) => (
<button key={label} type="button" className={`flex h-12 w-12 flex-col items-center justify-center rounded-xl ${index === 0 ? 'bg-blue-50 text-blue-600' : 'bg-transparent hover:bg-slate-100'}`}>
<span className="text-base"></span>
<span>{['الرئيسية','طلب جديد','تتبع','السجل','الإعدادات'][index]}</span>
</button>
))}
</nav>
</aside>
<section className="flex-1 p-6 lg:p-8">
<header className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
<div>
<p className="text-[12px] uppercase tracking-[0.35em] text-blue-600">الصفحة الرئيسية للعميل</p>
<h1 className="mt-2 text-[24px] font-bold text-slate-900">صباح الخير يا عميل 👋</h1>
<p className="text-[13px] text-slate-500">نظرة عامة على عمليات الإرسال والنشاط الأخير للطلبات.</p>
</div>
<button className="h-10 rounded-lg bg-blue-600 px-4 text-sm font-semibold text-white">+ طلب جديد</button>
</header>
<div className="mt-6 grid gap-4 md:grid-cols-3">
{[
['الطلبات النشطة', '12', 'text-blue-600'],
['المسلمة هذا الشهر', '86', 'text-emerald-600'],
['العناوين المحفوظة', '4', 'text-slate-900'],
].map(([label, value, tone]) => (
<article key={label} className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<p className="text-[11px] uppercase tracking-[0.35em] text-slate-400">{label}</p>
<p className={`mt-3 text-[26px] font-bold ${tone}`}>{value}</p>
</article>
))}
</div>
<div className="mt-6 grid gap-6 xl:grid-cols-[1.1fr_0.9fr]">
<article className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
<h2 className="text-[16px] font-semibold">الطلب النشط</h2>
<div className="mt-4 rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm">
<div className="flex items-center justify-between gap-3">
<div>
<p className="font-semibold text-slate-900">ORD-202606-00142</p>
<p className="text-[12px] text-slate-500">المركز الشمالي مخزن وسط المدينة</p>
</div>
<span className="rounded-full bg-amber-100 px-3 py-1 text-[11px] font-bold text-amber-800">في الطريق</span>
</div>
<div className="mt-4 h-2 rounded-full bg-slate-200">
<div className="h-2 w-2/3 rounded-full bg-blue-600" />
</div>
</div>
</article>
<article className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
<h2 className="text-[16px] font-semibold">الطلبات الأخيرة</h2>
<ul className="mt-4 divide-y divide-slate-200">
{[
['ORD-202606-00110', 'تم التوصيل', 'تم التوصيل', 'green'],
['ORD-202606-00115', 'ملغى', 'ملغى', 'red'],
].map(([ref, status, note, tone]) => (
<li key={ref} className="flex items-center justify-between gap-3 py-3 text-sm">
<div>
<p className="font-semibold text-slate-900">{ref}</p>
<p className="text-[12px] text-slate-500">{note}</p>
</div>
<span className={`rounded-full px-3 py-1 text-[11px] font-bold ${tone === 'green' ? 'bg-emerald-100 text-emerald-800' : 'bg-rose-100 text-rose-800'}`}>{status}</span>
</li>
))}
</ul>
</article>
</div>
</section>
</section>
</main>
);
}

View File

@@ -0,0 +1,538 @@
"use client";
import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Alert } from "../../../../Components/UI";
import { Toast } from "../../../../Components/Client/Toast";
import { useClientAddresses } from "../../../../hooks/useClientAddresses";
import { clientService } from "../../../../services/client.service";
import { getStoredToken } from "../../../../lib/auth";
import type {
Client,
ClientAddress,
ClientAddressFormData,
} from "../../../../types/client";
import { AddressFormModal } from "@/Components/Client/Addressformmodal";
import { DeleteConfirmModal } from "@/Components/Client/Deleteconfirmmodal";
// ── Helpers ────────────────────────────────────────────────────────────────
/** Returns a context-appropriate emoji for each common address label */
function labelIcon(label: string): string {
const map: Record<string, string> = {
"فوترة": "💳",
"شحن": "📦",
"المقر الرئيسي": "🏢",
"فرع": "🏬",
"مستودع": "🏭",
billing: "💳",
shipping: "📦",
"head office": "🏢",
branch: "🏬",
warehouse: "🏭",
};
return map[label.toLowerCase()] ?? "📍";
}
// ── Address card sub-component ─────────────────────────────────────────────
// Mirrors the AddressCard in the old page — kept co-located because it's only used here.
interface AddressCardProps {
address: ClientAddress;
onEdit: () => void;
onDelete: () => void;
onMakePrimary: () => void;
}
function AddressCard({ address, onEdit, onDelete, onMakePrimary }: AddressCardProps) {
return (
<div
style={{
position: "relative",
display: "flex",
flexDirection: "column",
gap: "0.75rem",
borderRadius: "var(--radius-xl)",
border: address.isPrimary
? "1px solid #93C5FD"
: "1px solid var(--color-border)",
padding: "1.25rem",
background: "var(--color-surface)",
boxShadow: address.isPrimary
? "0 0 0 2px #BFDBFE, var(--shadow-card)"
: "var(--shadow-card)",
}}
>
{/* Label row */}
<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
<span style={{ fontSize: 20 }} aria-hidden="true">
{labelIcon(address.label)}
</span>
<span style={{ fontSize: 13, fontWeight: 700, color: "var(--color-text-primary)" }}>
{address.label}
</span>
</div>
{address.isPrimary && (
<span
style={{
fontSize: 11,
fontWeight: 600,
color: "#1D4ED8",
background: "#EFF6FF",
border: "1px solid #BFDBFE",
borderRadius: "var(--radius-full)",
padding: "0.15rem 0.5rem",
}}
>
رئيسي
</span>
)}
</div>
{/* Address lines */}
<address
dir="rtl"
style={{
fontStyle: "normal",
fontSize: 13,
color: "var(--color-text-secondary)",
lineHeight: 1.7,
}}
>
<p style={{ margin: 0 }}>{address.street}</p>
<p style={{ margin: 0 }}>
{address.city}، {address.state} {address.postalCode}
</p>
<p style={{ margin: 0 }}>{address.country}</p>
</address>
{/* Actions */}
<div
style={{
display: "flex",
flexWrap: "wrap",
alignItems: "center",
gap: 8,
paddingTop: 8,
borderTop: "1px solid var(--color-border)",
}}
>
<ActionBtn onClick={onEdit} color="#1D4ED8" bg="#EFF6FF" border="#BFDBFE">
تعديل
</ActionBtn>
{!address.isPrimary && (
<ActionBtn
onClick={onMakePrimary}
color="#065F46"
bg="#DCFCE7"
border="#BBF7D0"
>
تعيين كرئيسي
</ActionBtn>
)}
<ActionBtn
onClick={onDelete}
color="#DC2626"
bg="#FEF2F2"
border="#FECACA"
style={{ marginRight: "auto" }}
>
حذف
</ActionBtn>
</div>
</div>
);
}
function ActionBtn({
onClick,
color,
bg,
border,
style,
children,
}: {
onClick: () => void;
color: string;
bg: string;
border: string;
style?: React.CSSProperties;
children: React.ReactNode;
}) {
return (
<button
type="button"
onClick={onClick}
style={{
height: 30,
padding: "0 0.75rem",
borderRadius: "var(--radius-md)",
border: `1px solid ${border}`,
background: bg,
fontSize: 12,
fontWeight: 600,
color,
cursor: "pointer",
fontFamily: "var(--font-sans)",
...style,
}}
>
{children}
</button>
);
}
// ── Page ───────────────────────────────────────────────────────────────────
export default function ClientAddressesPage() {
const params = useParams();
const router = useRouter();
const clientId = params?.clientId as string;
console.log('clientId:', params.clientId); // شوف إيه اللي بيجي
// ── Parent client meta ───────────────────────────────────────────────────
const [client, setClient] = useState<Client | null>(null);
const [clientLoading, setClientLoading] = useState(true);
useEffect(() => {
if (!clientId) return;
setClientLoading(true);
clientService
.getById(clientId, getStoredToken())
.then((res) => setClient(res.data))
.catch(() => router.replace("/clients"))
.finally(() => setClientLoading(false));
}, [clientId, router]);
// ── Address CRUD hook ────────────────────────────────────────────────────
const {
addresses,
loading: addrLoading,
error,
notification,
clearError,
createAddress,
updateAddress,
deleteAddress,
makePrimary,
} = useClientAddresses(clientId ?? "");
// ── Modal state (mirrors UsersPage pattern) ──────────────────────────────
// false = closed | null = create mode | ClientAddress = edit mode
const [formTarget, setFormTarget] = useState<ClientAddress | null | false>(false);
const [deleteTarget, setDeleteTarget] = useState<ClientAddress | null>(null);
const [deleting, setDeleting] = useState(false);
// ── Handlers ─────────────────────────────────────────────────────────────
const handleFormSubmit = async (
data: ClientAddressFormData,
isNew: boolean
): Promise<boolean> => {
if (isNew) return createAddress(data);
return updateAddress((formTarget as ClientAddress).id, data);
};
const handleDeleteConfirm = async () => {
if (!deleteTarget || deleting) return;
setDeleting(true);
const ok = await deleteAddress(deleteTarget.id);
setDeleting(false);
if (ok) setDeleteTarget(null);
};
// ── Guard: wait for router + client ─────────────────────────────────────
if (!clientId || clientLoading) {
return (
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
minHeight: "100vh",
}}
>
<div
style={{
width: 40,
height: 40,
borderRadius: "50%",
border: "3px solid var(--color-border)",
borderTopColor: "var(--color-brand-600)",
animation: "spin 0.7s linear infinite",
}}
/>
</div>
);
}
// ── Render ────────────────────────────────────────────────────────────────
return (
<>
{/* Global success / error toast */}
<Toast notification={notification} />
{/* Create / Edit address modal */}
{formTarget !== false && (
<AddressFormModal
editAddress={formTarget}
onClose={() => setFormTarget(false)}
onSubmit={handleFormSubmit}
/>
)}
{/* Delete confirmation — reuses the same DeleteConfirmModal shape */}
{deleteTarget && (
<DeleteConfirmModal
// Cast address as Client for the modal (same shape: id + name)
client={
{
...deleteTarget,
name: deleteTarget.label,
email: "",
phone: "",
createdAt: deleteTarget.createdAt,
updatedAt: deleteTarget.updatedAt,
} as Client
}
deleting={deleting}
onCancel={() => { if (!deleting) setDeleteTarget(null); }}
onConfirm={handleDeleteConfirm}
/>
)}
<section style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
{/* ── Page header ── */}
<header
style={{
borderRadius: "var(--radius-xl)",
border: "1px solid var(--color-border)",
background: "var(--color-surface)",
padding: "1.5rem 2rem",
boxShadow: "var(--shadow-card)",
}}
>
{/* Back link */}
<button
type="button"
onClick={() => router.push("/clients")}
style={{
display: "inline-flex",
alignItems: "center",
gap: 6,
fontSize: 12,
fontWeight: 600,
color: "var(--color-text-muted)",
background: "none",
border: "none",
cursor: "pointer",
marginBottom: 12,
fontFamily: "var(--font-sans)",
}}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M15 18l-6-6 6-6" />
</svg>
جميع العملاء
</button>
<p
style={{
fontSize: 11,
letterSpacing: "0.3em",
textTransform: "uppercase",
color: "#2563EB",
fontWeight: 600,
}}
>
إدارة العناوين
</p>
<div className="mt-3 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<div>
<h1
style={{
fontSize: "1.5rem",
fontWeight: 700,
color: "var(--color-text-primary)",
margin: 0,
}}
>
{client ? `${client.name} — العناوين` : "العناوين"}
</h1>
<p
style={{
marginTop: "0.25rem",
fontSize: 13,
color: "var(--color-text-muted)",
}}
>
إجمالي{" "}
<strong style={{ color: "var(--color-text-primary)" }}>
{addresses.length}
</strong>{" "}
عنوان
</p>
</div>
{/* Add address button */}
<button
type="button"
onClick={() => setFormTarget(null)}
style={{
height: 40,
padding: "0 1.125rem",
borderRadius: "var(--radius-lg)",
border: "none",
background: "var(--color-brand-600)",
fontSize: 13,
fontWeight: 700,
color: "#FFF",
cursor: "pointer",
display: "inline-flex",
alignItems: "center",
gap: 7,
fontFamily: "var(--font-sans)",
boxShadow: "0 1px 4px rgba(37,99,235,.35)",
whiteSpace: "nowrap",
}}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
إضافة عنوان
</button>
</div>
{/* Client info strip */}
{client && (
<div
dir="rtl"
style={{
marginTop: "1rem",
display: "flex",
flexWrap: "wrap",
gap: "1rem",
fontSize: 13,
color: "var(--color-text-secondary)",
paddingTop: "1rem",
borderTop: "1px solid var(--color-border)",
}}
>
<span style={{ fontWeight: 600, color: "var(--color-text-primary)" }}>
{client.name}
</span>
<a
href={`mailto:${client.email}`}
style={{ color: "#2563EB", textDecoration: "none" }}
>
{client.email}
</a>
<span>{client.phone}</span>
{client.taxId && (
<code
style={{
fontSize: 11,
background: "var(--color-surface-muted)",
border: "1px solid var(--color-border)",
borderRadius: "var(--radius-sm)",
padding: "0.1rem 0.4rem",
}}
>
{client.taxId}
</code>
)}
</div>
)}
</header>
{/* General load error */}
{error && <Alert type="error" message={error} onClose={clearError} />}
{/* Address grid */}
{addrLoading ? (
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: "4rem 0",
color: "var(--color-text-muted)",
fontSize: 13,
}}
>
جارٍ التحميل
</div>
) : addresses.length === 0 ? (
<div
style={{
borderRadius: "var(--radius-xl)",
border: "1px solid var(--color-border)",
background: "var(--color-surface)",
padding: "4rem 1rem",
textAlign: "center",
boxShadow: "var(--shadow-card)",
}}
>
<p style={{ fontSize: 32, margin: 0 }}>📍</p>
<p
style={{
marginTop: 12,
fontSize: 15,
fontWeight: 700,
color: "var(--color-text-primary)",
}}
>
لا توجد عناوين بعد
</p>
<p
style={{
marginTop: 4,
fontSize: 13,
color: "var(--color-text-muted)",
}}
>
أضف عنواناً واحداً على الأقل حتى يتمكن العميل من استقبال الشحنات والفواتير.
</p>
<button
type="button"
onClick={() => setFormTarget(null)}
style={{
marginTop: 16,
fontSize: 13,
fontWeight: 600,
color: "var(--color-brand-600)",
background: "none",
border: "none",
cursor: "pointer",
textDecoration: "underline",
}}
>
أضف أول عنوان
</button>
</div>
) : (
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))",
gap: "1rem",
}}
>
{addresses.map((addr) => (
<AddressCard
key={addr.id}
address={addr}
onEdit={() => setFormTarget(addr)}
onDelete={() => setDeleteTarget(addr)}
onMakePrimary={() => makePrimary(addr.id)}
/>
))}
</div>
)}
</section>
</>
);
}

238
app/clients/page.tsx Normal file
View File

@@ -0,0 +1,238 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Alert } from "../../Components/UI";
import { Toast } from "../../Components/Client/Toast";
import { useClients } from "../../hooks/useClients";
import type { Client, ClientFormData } from "../../types/client";
import { ClientFormModal } from "@/Components/Client/Clientformmodal";
import { ClientTable } from "@/Components/Client/Clienttable";
import { DeleteConfirmModal } from "@/Components/Client/Deleteconfirmmodal";
export default function ClientsPage() {
const router = useRouter();
// ── Modal state ──────────────────────────────────────────────────────────
// false = closed | null = create mode | Client = edit mode
const [formTarget, setFormTarget] = useState<Client | null | false>(false);
const [deleteTarget, setDeleteTarget] = useState<Client | null>(null);
const [deleting, setDeleting] = useState(false);
// ── Data hook ────────────────────────────────────────────────────────────
const {
clients, loading, total, pages, error,
page, search,
setPage, handleSearch, clearError,
createClient, updateClient, deleteClient,
notification,
} = useClients();
// ── Create / Update handler ──────────────────────────────────────────────
const handleFormSubmit = async (
data: ClientFormData,
isNew: boolean
): Promise<boolean> => {
if (isNew) return createClient(data);
return updateClient((formTarget as Client).id, data);
};
// ── Delete handler ───────────────────────────────────────────────────────
const handleDeleteConfirm = async () => {
if (!deleteTarget || deleting) return;
setDeleting(true);
const ok = await deleteClient(deleteTarget.id);
setDeleting(false);
if (ok) setDeleteTarget(null);
};
// ── Navigate to address management ──────────────────────────────────────
const handleManageAddresses = (client: Client) => {
router.push(`/clients/${client.id}/addresses`);
};
// ── Render ───────────────────────────────────────────────────────────────
return (
<>
{/* Global success / error toast */}
<Toast notification={notification} />
{/* Create / Edit modal */}
{formTarget !== false && (
<ClientFormModal
editClient={formTarget}
onClose={() => setFormTarget(false)}
onSubmit={handleFormSubmit}
/>
)}
{/* Delete confirmation dialog */}
{deleteTarget && (
<DeleteConfirmModal
client={deleteTarget}
deleting={deleting}
onCancel={() => { if (!deleting) setDeleteTarget(null); }}
onConfirm={handleDeleteConfirm}
/>
)}
<section style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
{/* ── Page header ── */}
<header
style={{
borderRadius: "var(--radius-xl)",
border: "1px solid var(--color-border)",
background: "var(--color-surface)",
padding: "1.5rem 2rem",
boxShadow: "var(--shadow-card)",
}}
>
<p
style={{
fontSize: 11,
letterSpacing: "0.3em",
textTransform: "uppercase",
color: "#2563EB",
fontWeight: 600,
}}
>
إدارة العملاء
</p>
<div className="mt-3 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<div>
<h1
style={{
fontSize: "1.5rem",
fontWeight: 700,
color: "var(--color-text-primary)",
margin: 0,
}}
>
العملاء
</h1>
<p
style={{
marginTop: "0.25rem",
fontSize: 13,
color: "var(--color-text-muted)",
}}
>
إجمالي{" "}
<strong style={{ color: "var(--color-text-primary)" }}>
{total}
</strong>{" "}
عميل
</p>
</div>
<div
style={{
display: "flex",
gap: "0.5rem",
flexWrap: "wrap",
alignItems: "center",
}}
>
{/* Search input */}
<div style={{ position: "relative", width: 256 }}>
<svg
style={{
position: "absolute",
right: 12,
top: "50%",
transform: "translateY(-50%)",
width: 16,
height: 16,
color: "var(--color-text-hint)",
pointerEvents: "none",
}}
fill="none"
stroke="currentColor"
strokeWidth="2"
viewBox="0 0 24 24"
>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.35-4.35" />
</svg>
<input
type="text"
placeholder="بحث بالاسم أو الهاتف أو البريد…"
value={search}
onChange={(e) => handleSearch(e.target.value)}
dir="rtl"
style={{
width: "100%",
height: 40,
paddingRight: 36,
paddingLeft: 12,
borderRadius: "var(--radius-lg)",
border: "1px solid var(--color-border)",
background: "var(--color-surface)",
fontSize: 13,
outline: "none",
fontFamily: "var(--font-sans)",
color: "var(--color-text-primary)",
}}
/>
</div>
{/* Add client button */}
<button
type="button"
onClick={() => setFormTarget(null)}
style={{
height: 40,
padding: "0 1.125rem",
borderRadius: "var(--radius-lg)",
border: "none",
background: "var(--color-brand-600)",
fontSize: 13,
fontWeight: 700,
color: "#FFF",
cursor: "pointer",
display: "inline-flex",
alignItems: "center",
gap: 7,
fontFamily: "var(--font-sans)",
boxShadow: "0 1px 4px rgba(37,99,235,.35)",
whiteSpace: "nowrap",
}}
>
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.5"
>
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
إضافة عميل
</button>
</div>
</div>
</header>
{/* General load error */}
{error && <Alert type="error" message={error} onClose={clearError} />}
{/* Clients table */}
<ClientTable
clients={clients}
loading={loading}
search={search}
page={page}
pages={pages}
onEdit={(client) => setFormTarget(client)}
onDelete={(client) => setDeleteTarget(client)}
onAddFirst={() => setFormTarget(null)}
onPageChange={setPage}
onManageAddresses={handleManageAddresses}
/>
</section>
</>
);
}

View File

@@ -1,52 +1,32 @@
"use client";
import { useEffect, useState } from "react";
import { getStoredToken } from "../../lib/auth";
import { get, post, put, del } from "../../services/api";
import { Spinner, Alert } from "../../Components/UI";
interface Driver {
id: string;
name: string;
userName?: string;
phone: string;
nationality?: string;
licenseNumber?: string;
licenseExpiry?: string;
nationalIdExpiry?: string;
status: "Active" | "Inactive" | "InTrip" | "Suspended";
isActive: boolean;
branch?: { name: string };
createdAt: string;
}
import { useState, useCallback } from "react";
import { Alert, Spinner } from "@/Components/UI";
import { DriverFormModal } from "@/Components/Driver/DriverFormModal";
import { DriverDeleteModal } from "@/Components/Driver/DriverDeleteModal";
import { driverService } from "@/services";
import { getStoredToken } from "@/lib/auth";
import { useDrivers } from "@/hooks/useDriver";
import { CreateDriverPayload, Driver, DRIVER_STATUS_MAP, UpdateDriverPayload } from "@/types/driver";
import { DriverDetailPanel } from "@/Components/Driver/DriverDetailPanel";
interface ApiResponse {
data: {
data: Driver[];
pagination: { total: number; page: number; pages: number };
meta?: { total: number; pages: number };
};
}
// ── Helpers ───────────────────────────────────────────────────────────────────
const STATUS_MAP: Record<Driver["status"], { label: string; color: string; bg: string; border: string }> = {
Active: { label: "نشط", color: "#166534", bg: "#DCFCE7", border: "#BBF7D0" },
InTrip: { label: "في رحلة", color: "#1E40AF", bg: "#EFF6FF", border: "#BFDBFE" },
Inactive: { label: "غير نشط", color: "#64748B", bg: "#F1F5F9", border: "#E2E8F0" },
Suspended: { label: "موقوف", color: "#991B1B", bg: "#FEF2F2", border: "#FECACA" },
};
function fmtDate(iso?: string) {
function fmtDate(iso?: string | null): string {
if (!iso) return "—";
return new Date(iso).toLocaleDateString("ar-SA", {
year: "numeric", month: "short", day: "numeric",
});
}
function expirySoon(iso?: string) {
function expirySoon(iso?: string | null): boolean {
if (!iso) return false;
return (new Date(iso).getTime() - Date.now()) / 86_400_000 <= 90;
}
// ── Styles ────────────────────────────────────────────────────────────────────
const cardStyle: React.CSSProperties = {
borderRadius: "var(--radius-xl)",
border: "1px solid var(--color-border)",
@@ -66,182 +46,333 @@ const thStyle: React.CSSProperties = {
borderBottom: "1px solid var(--color-border)",
};
// ── Page Component ────────────────────────────────────────────────────────────
export default function DriversPage() {
const [drivers, setDrivers] = useState<Driver[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [search, setSearch] = useState("");
const [page, setPage] = useState(1);
const [total, setTotal] = useState(0);
const [pages, setPages] = useState(1);
const {
drivers, loading, error, total, pages, page,
search, setPage, handleSearch, clearError,
deleteDriver, notification, reload,
} = useDrivers();
useEffect(() => {
const token = getStoredToken();
setLoading(true);
setError(null);
const query = `?page=${page}&limit=10${search ? `&search=${encodeURIComponent(search)}` : ""}`;
get<ApiResponse>(`driver${query}`, token)
.then((res) => {
const payload = res.data ?? res;
setDrivers(payload.data ?? []);
setTotal(payload.meta?.total ?? 0);
setPages(payload.meta?.pages ?? 1);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [page, search]);
// ── Panel / modal state ───────────────────────────────────────────────────
const [selectedDriverId, setSelectedDriverId] = useState<string | null>(null);
const [formDriver, setFormDriver] = useState<Driver | null | "new">(null);
const [deleteTarget, setDeleteTarget] = useState<Driver | null>(null);
const [deleting, setDeleting] = useState(false);
// ── Handlers ──────────────────────────────────────────────────────────────
const handleEdit = useCallback((driver: Driver) => {
setSelectedDriverId(null);
setFormDriver(driver);
}, []);
const handleDelete = useCallback((driver: Driver) => {
setSelectedDriverId(null);
setDeleteTarget(driver);
}, []);
const handleFormSubmit = useCallback(
async (
payload: CreateDriverPayload | UpdateDriverPayload,
isNew: boolean,
): Promise<boolean> => {
try {
const token = getStoredToken();
if (isNew) {
// Use multipart if there are file fields
const hasFiles =
(payload as CreateDriverPayload & { photo?: File }).photo ||
(payload as CreateDriverPayload & { nationalPhoto?: File }).nationalPhoto ||
(payload as CreateDriverPayload & { driverCardPhoto?: File }).driverCardPhoto;
if (hasFiles) {
await driverService.createWithImages(
payload as Parameters<typeof driverService.createWithImages>[0],
token,
);
} else {
await driverService.create(payload as CreateDriverPayload, token);
}
} else {
const id = (formDriver as Driver).id;
await driverService.update(id, payload as UpdateDriverPayload, token);
}
reload();
return true;
} catch {
return false;
}
},
[formDriver, reload],
);
const handleConfirmDelete = useCallback(async () => {
if (!deleteTarget) return;
setDeleting(true);
const ok = await deleteDriver(deleteTarget.id);
setDeleting(false);
if (ok) setDeleteTarget(null);
}, [deleteTarget, deleteDriver]);
// ── Render ────────────────────────────────────────────────────────────────
return (
<section style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
<>
<section style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
{/* Header */}
<header style={{
borderRadius: "var(--radius-xl)",
border: "1px solid var(--color-border)",
background: "var(--color-surface)",
padding: "1.5rem 2rem",
boxShadow: "var(--shadow-card)",
}}>
<p style={{ fontSize: 11, letterSpacing: "0.3em", textTransform: "uppercase", color: "#2563EB", fontWeight: 600 }}>
إدارة الكوادر
</p>
<div className="mt-3 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<div>
<h1 style={{ fontSize: "1.5rem", fontWeight: 700, color: "var(--color-text-primary)", margin: 0 }}>
السائقون
</h1>
<p style={{ marginTop: "0.25rem", fontSize: 13, color: "var(--color-text-muted)" }}>
إجمالي <strong style={{ color: "var(--color-text-primary)" }}>{total}</strong> سائق مسجل
</p>
</div>
<div style={{ position: "relative", width: "100%", maxWidth: 288 }}>
<svg style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", width: 16, height: 16, color: "var(--color-text-hint)", pointerEvents: "none" }}
fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
<circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
</svg>
<input type="text" placeholder="بحث بالاسم أو الهاتف..." value={search}
onChange={(e) => { setSearch(e.target.value); setPage(1); }} dir="rtl"
style={{
width: "100%", height: 40, paddingRight: 36, paddingLeft: 12,
borderRadius: "var(--radius-lg)",
border: "1px solid var(--color-border)",
background: "var(--color-surface)",
fontSize: 13, color: "var(--color-text-primary)",
outline: "none", fontFamily: "var(--font-sans)",
}}
/>
</div>
</div>
</header>
{error && <Alert type="error" message={error} onClose={() => setError(null)} />}
{/* Table */}
<div style={cardStyle}>
<div dir="rtl" style={{
display: "grid",
gridTemplateColumns: "2fr 1.2fr 1fr 1fr 1fr 1fr",
...thStyle,
{/* ── Header ── */}
<header style={{
borderRadius: "var(--radius-xl)",
border: "1px solid var(--color-border)",
background: "var(--color-surface)",
padding: "1.5rem 2rem",
boxShadow: "var(--shadow-card)",
}}>
<span>السائق</span>
<span>الفرع</span>
<span>الجنسية</span>
<span>انتهاء الرخصة</span>
<span>الحالة</span>
<span style={{ textAlign: "center" }}>انتهاء الهوية</span>
</div>
{loading ? (
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 12, padding: "4rem 0", color: "var(--color-text-muted)" }}>
<Spinner size="sm" className="text-blue-600" />
<span style={{ fontSize: 13 }}>جارٍ التحميل</span>
</div>
) : drivers.length === 0 ? (
<p style={{ textAlign: "center", padding: "4rem 0", fontSize: 13, color: "var(--color-text-muted)" }}>
لا توجد نتائج {search && `لـ "${search}"`}
<p style={{ fontSize: 11, letterSpacing: "0.3em", textTransform: "uppercase", color: "#2563EB", fontWeight: 600 }}>
إدارة الكوادر
</p>
) : (
<ul dir="rtl" style={{ listStyle: "none", margin: 0, padding: 0 }}>
{drivers.map((d, i) => {
const status = STATUS_MAP[d.status];
const licWarn = expirySoon(d.licenseExpiry);
const idWarn = expirySoon(d.nationalIdExpiry);
return (
<li key={d.id} style={{
display: "grid",
gridTemplateColumns: "2fr 1.2fr 1fr 1fr 1fr 1fr",
alignItems: "center", gap: "0.5rem",
padding: "0.875rem 1.5rem",
borderBottom: "1px solid var(--color-border)",
background: i % 2 !== 0 ? "var(--color-surface-muted)" : "transparent",
fontSize: 13,
}}>
<div>
<p style={{ fontWeight: 600, color: "var(--color-text-primary)", margin: 0 }}>{d.name}</p>
<p style={{ marginTop: 2, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--color-text-muted)" }}>{d.phone}</p>
</div>
<span style={{ color: "var(--color-text-secondary)" }}>{d.branch?.name ?? "—"}</span>
<span style={{ color: "var(--color-text-secondary)" }}>{d.nationality ?? "—"}</span>
<span style={{
fontSize: 12, fontWeight: 600,
color: licWarn ? "#D97706" : "var(--color-text-secondary)",
}}>
{licWarn && "⚠ "}{fmtDate(d.licenseExpiry)}
</span>
<span style={{
display: "inline-flex", alignItems: "center",
borderRadius: "var(--radius-full)",
border: `1px solid ${status.border}`,
background: status.bg,
padding: "0.2rem 0.625rem",
fontSize: 11, fontWeight: 600, color: status.color,
width: "fit-content",
}}>
{status.label}
</span>
<span style={{
textAlign: "center", fontSize: 12, fontWeight: 600,
color: idWarn ? "#D97706" : "var(--color-text-secondary)",
}}>
{idWarn && "⚠ "}{fmtDate(d.nationalIdExpiry)}
</span>
</li>
);
})}
</ul>
)}
<div style={{ marginTop: "0.75rem", display: "flex", flexDirection: "column", gap: "1rem" }}>
<div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: "1rem" }}>
<div>
<h1 style={{ fontSize: "1.5rem", fontWeight: 700, color: "var(--color-text-primary)", margin: 0 }}>
السائقون
</h1>
<p style={{ marginTop: "0.25rem", fontSize: 13, color: "var(--color-text-muted)" }}>
إجمالي{" "}
<strong style={{ color: "var(--color-text-primary)" }}>{total}</strong>{" "}
سائق مسجل
</p>
</div>
{pages > 1 && (
<div dir="rtl" style={{
display: "flex", alignItems: "center", justifyContent: "space-between",
borderTop: "1px solid var(--color-border)", padding: "0.875rem 1.5rem",
}}>
<span style={{ fontSize: 12, color: "var(--color-text-muted)" }}>
صفحة <strong style={{ color: "var(--color-text-primary)" }}>{page}</strong> من <strong style={{ color: "var(--color-text-primary)" }}>{pages}</strong>
</span>
<div style={{ display: "flex", gap: "0.5rem" }}>
{[
{ label: "السابق", action: () => setPage(p => Math.max(1, p - 1)), disabled: page === 1 },
{ label: "التالي", action: () => setPage(p => Math.min(pages, p + 1)), disabled: page === pages },
].map(btn => (
<button key={btn.label} onClick={btn.action} disabled={btn.disabled}
<div style={{ display: "flex", gap: "0.75rem", alignItems: "center", flexWrap: "wrap" }}>
{/* Search */}
<div style={{ position: "relative", width: 288 }}>
<svg
style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", width: 16, height: 16, color: "var(--color-text-hint)", pointerEvents: "none" }}
fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"
>
<circle cx="11" cy="11" r="8" /><path d="m21 21-4.35-4.35" />
</svg>
<input
type="text"
placeholder="بحث بالاسم أو الهاتف..."
value={search}
onChange={(e) => handleSearch(e.target.value)}
dir="rtl"
style={{
width: "100%", height: 40, paddingRight: 36, paddingLeft: 12,
borderRadius: "var(--radius-lg)",
border: "1px solid var(--color-border)",
background: "var(--color-surface)",
fontSize: 13, color: "var(--color-text-primary)",
outline: "none", fontFamily: "var(--font-sans)",
}}
/>
</div>
{/* Add button */}
<button
type="button"
onClick={() => setFormDriver("new")}
style={{
height: 40, padding: "0 1.25rem",
borderRadius: "var(--radius-lg)",
border: "1px solid var(--color-border)",
background: "var(--color-surface-muted)",
padding: "0.375rem 0.875rem",
fontSize: 12, color: "var(--color-text-secondary)",
cursor: btn.disabled ? "not-allowed" : "pointer",
opacity: btn.disabled ? 0.4 : 1,
border: "none",
background: "var(--color-brand-600)",
fontSize: 13, fontWeight: 700, color: "#FFF",
cursor: "pointer",
display: "flex", alignItems: "center", gap: 8,
fontFamily: "var(--font-sans)",
}}>
{btn.label}
flexShrink: 0,
}}
>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<path d="M12 5v14M5 12h14" />
</svg>
إضافة سائق
</button>
))}
</div>
</div>
</div>
</header>
{/* ── Notifications ── */}
{notification && (
<Alert
type={notification.type}
message={notification.message}
/>
)}
</div>
</section>
{error && (
<Alert type="error" message={error} onClose={clearError} />
)}
{/* ── Table ── */}
<div style={cardStyle}>
<div
dir="rtl"
style={{
display: "grid",
gridTemplateColumns: "2fr 1.2fr 1fr 1.1fr 1.1fr 1fr",
...thStyle,
}}
>
<span>السائق</span>
<span>الفرع</span>
<span>الجنسية</span>
<span>انتهاء الرخصة</span>
<span>انتهاء الهوية</span>
<span>الحالة</span>
</div>
{loading ? (
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 12, padding: "4rem 0", color: "var(--color-text-muted)" }}>
<Spinner size="sm" className="text-blue-600" />
<span style={{ fontSize: 13 }}>جارٍ التحميل</span>
</div>
) : drivers.length === 0 ? (
<p style={{ textAlign: "center", padding: "4rem 0", fontSize: 13, color: "var(--color-text-muted)" }}>
لا توجد نتائج {search && `لـ "${search}"`}
</p>
) : (
<ul dir="rtl" style={{ listStyle: "none", margin: 0, padding: 0 }}>
{drivers.map((d, i) => {
const statusCfg = DRIVER_STATUS_MAP[d.status] ?? DRIVER_STATUS_MAP.Inactive;
const licWarn = expirySoon(d.licenseExpiry);
const idWarn = expirySoon((d as Driver & { nationalIdExpiry?: string }).nationalIdExpiry);
return (
<li
key={d.id}
onClick={() => setSelectedDriverId(d.id)}
style={{
display: "grid",
gridTemplateColumns: "2fr 1.2fr 1fr 1.1fr 1.1fr 1fr",
alignItems: "center", gap: "0.5rem",
padding: "0.875rem 1.5rem",
borderBottom: "1px solid var(--color-border)",
background: i % 2 !== 0 ? "var(--color-surface-muted)" : "transparent",
fontSize: 13,
cursor: "pointer",
transition: "background 0.15s",
}}
onMouseEnter={(e) => (e.currentTarget.style.background = "var(--color-surface-hover, #F8FAFC)")}
onMouseLeave={(e) => (e.currentTarget.style.background = i % 2 !== 0 ? "var(--color-surface-muted)" : "transparent")}
>
{/* Name + phone */}
<div>
<p style={{ fontWeight: 600, color: "var(--color-text-primary)", margin: 0 }}>{d.name}</p>
<p style={{ marginTop: 2, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--color-text-muted)" }}>{d.phone}</p>
</div>
{/* Branch */}
<span style={{ color: "var(--color-text-secondary)" }}>{d.branch?.name ?? "—"}</span>
{/* Nationality */}
<span style={{ color: "var(--color-text-secondary)" }}>{d.nationality ?? "—"}</span>
{/* License expiry */}
<span style={{ fontSize: 12, fontWeight: licWarn ? 600 : 400, color: licWarn ? "#D97706" : "var(--color-text-secondary)" }}>
{licWarn && "⚠ "}{fmtDate(d.licenseExpiry)}
</span>
{/* National ID expiry */}
<span style={{ fontSize: 12, fontWeight: idWarn ? 600 : 400, color: idWarn ? "#D97706" : "var(--color-text-secondary)" }}>
{idWarn && "⚠ "}{fmtDate((d as Driver & { nationalIdExpiry?: string }).nationalIdExpiry)}
</span>
{/* Status badge */}
<span style={{
display: "inline-flex", alignItems: "center", gap: 5,
borderRadius: "var(--radius-full)",
border: `1px solid ${statusCfg.border}`,
background: statusCfg.bg,
padding: "0.2rem 0.625rem",
fontSize: 11, fontWeight: 600, color: statusCfg.color,
width: "fit-content",
}}>
<span style={{ width: 6, height: 6, borderRadius: "50%", background: statusCfg.dot, flexShrink: 0 }} />
{statusCfg.label}
</span>
</li>
);
})}
</ul>
)}
{/* ── Pagination ── */}
{pages > 1 && (
<div
dir="rtl"
style={{
display: "flex", alignItems: "center", justifyContent: "space-between",
borderTop: "1px solid var(--color-border)", padding: "0.875rem 1.5rem",
}}
>
<span style={{ fontSize: 12, color: "var(--color-text-muted)" }}>
صفحة{" "}
<strong style={{ color: "var(--color-text-primary)" }}>{page}</strong>{" "}
من{" "}
<strong style={{ color: "var(--color-text-primary)" }}>{pages}</strong>
</span>
<div style={{ display: "flex", gap: "0.5rem" }}>
{[
{ label: "السابق", action: () => setPage(p => Math.max(1, p - 1)), disabled: page === 1 },
{ label: "التالي", action: () => setPage(p => Math.min(pages, p + 1)), disabled: page === pages },
].map(btn => (
<button
key={btn.label}
onClick={btn.action}
disabled={btn.disabled}
style={{
borderRadius: "var(--radius-lg)",
border: "1px solid var(--color-border)",
background: "var(--color-surface-muted)",
padding: "0.375rem 0.875rem",
fontSize: 12, color: "var(--color-text-secondary)",
cursor: btn.disabled ? "not-allowed" : "pointer",
opacity: btn.disabled ? 0.4 : 1,
fontFamily: "var(--font-sans)",
}}
>
{btn.label}
</button>
))}
</div>
</div>
)}
</div>
</section>
{/* ── Detail panel ── */}
{selectedDriverId && (
<DriverDetailPanel
driverId={selectedDriverId}
onClose={() => setSelectedDriverId(null)}
onEdit={handleEdit}
onDelete={handleDelete}
/>
)}
{/* ── Form modal ── */}
{formDriver !== null && (
<DriverFormModal
editDriver={formDriver === "new" ? null : formDriver}
branches={[]}
onClose={() => setFormDriver(null)}
onSubmit={handleFormSubmit}
/>
)}
{/* ── Delete modal ── */}
{deleteTarget && (
<DriverDeleteModal
driver={deleteTarget}
deleting={deleting}
onCancel={() => setDeleteTarget(null)}
onConfirm={handleConfirmDelete}
/>
)}
</>
);
}