update saidebar layout build order crud
This commit is contained in:
@@ -1,116 +1,226 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
|
import { useState, useEffect, createContext, useContext } from "react";
|
||||||
import { getStoredUser } from "@/src/lib/auth";
|
import { getStoredUser } from "@/src/lib/auth";
|
||||||
import Logo from "@/src/utils/logo";
|
import Logo from "@/src/utils/logo";
|
||||||
|
import BrandIcon from "@/src/utils/brandIcon";
|
||||||
|
|
||||||
|
|
||||||
|
//ــــــــــــــ Drawer Context
|
||||||
|
|
||||||
|
const DrawerCtx = createContext<{
|
||||||
|
open: boolean;
|
||||||
|
setOpen: (v: boolean) => void;
|
||||||
|
}>({ open: false, setOpen: () => {} });
|
||||||
|
|
||||||
|
export function useSidebarDrawer() {
|
||||||
|
return useContext(DrawerCtx);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SidebarProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
return (
|
||||||
|
<DrawerCtx.Provider value={{ open, setOpen }}>
|
||||||
|
{children}
|
||||||
|
</DrawerCtx.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ══════════════════════════════════════════
|
||||||
|
Nav items
|
||||||
|
══════════════════════════════════════════ */
|
||||||
const navSections = [
|
const navSections = [
|
||||||
{
|
{
|
||||||
label: "الرئيسية",
|
label: "الرئيسية",
|
||||||
items: [
|
items: [
|
||||||
{ href: "/dashboard", label: "Dashboard", icon: "ti-layout-dashboard", permission: "read-dashboard" },
|
{ href: "/dashboard", label: "Dashboard", icon: "ti-layout-dashboard", permission: "read-dashboard" },
|
||||||
{ href: "/dashboard/users", label: "Users", icon: "ti-users", permission: "read-user" },
|
{ href: "/dashboard/users", label: "Users", icon: "ti-users", permission: "read-user" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "الأسطول",
|
label: "الأسطول",
|
||||||
items: [
|
items: [
|
||||||
{ href: "/dashboard/cars", label: "Cars", icon: "ti-car", permission: "read-car" },
|
{ href: "/dashboard/cars", label: "Cars", icon: "ti-car", permission: "read-car" },
|
||||||
{ href: "/dashboard/drivers", label: "Drivers", icon: "ti-steering-wheel",permission: "read-driver" },
|
{ href: "/dashboard/drivers", label: "Drivers", icon: "ti-steering-wheel", permission: "read-driver" },
|
||||||
{ href: "/dashboard/trips", label: "Trips", icon: "ti-route", permission: "read-trip" },
|
{ href: "/dashboard/trips", label: "Trips", icon: "ti-route", permission: "read-trip" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "العمليات",
|
label: "العمليات",
|
||||||
items: [
|
items: [
|
||||||
{ href: "/dashboard/orders", label: "Orders", icon: "ti-package", permission: "read-order" },
|
{ href: "/dashboard/orders", label: "Orders", icon: "ti-package", permission: "read-order" },
|
||||||
{ href: "/dashboard/clients", label: "Clients", icon: "ti-users-group", permission: "read-client" },
|
{ href: "/dashboard/clients", label: "Clients", icon: "ti-users-group", permission: "read-client" },
|
||||||
{ href: "/dashboard/branches", label: "Branches", icon: "ti-building", permission: "read-branch" },
|
{ href: "/dashboard/branches", label: "Branches", icon: "ti-building", permission: "read-branch" },
|
||||||
{ href: "/dashboard/roles", label: "Roles", icon: "ti-shield", permission: "read-role" },
|
{ href: "/dashboard/roles", label: "Roles", icon: "ti-shield", permission: "read-role" },
|
||||||
{ href: "/dashboard/role_permission", label: "Roles & Permission", icon: "ti-shield", permission: "manage-role-permissions" },
|
{ href: "/dashboard/role_permission", label: "Roles & Permission", icon: "ti-shield", permission: "manage-role-permissions" },
|
||||||
{ href: "/dashboard/audit", label: "Audit", icon: "ti-clipboard-list", permission: "read-audit" },
|
{ href: "/dashboard/audit", label: "Audit", icon: "ti-clipboard-list", permission: "read-audit" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/* ══════════════════════════════════════════
|
||||||
|
Brand Icon
|
||||||
|
══════════════════════════════════════════ */
|
||||||
|
|
||||||
|
|
||||||
|
export function BrandIconButton({ onClick }: { onClick: () => void }) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClick}
|
||||||
|
aria-label="فتح القائمة"
|
||||||
|
style={{
|
||||||
|
background: "transparent",
|
||||||
|
border: "1px solid var(--color-border)",
|
||||||
|
borderRadius: 8,
|
||||||
|
width: 36, height: 36,
|
||||||
|
padding: 2,
|
||||||
|
display: "flex", alignItems: "center", justifyContent: "center",
|
||||||
|
cursor: "pointer",
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<BrandIcon size={28} bg="#2563EB" />
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const GRAD = "linear-gradient(175deg, #1E3A8A 0%, #1D4ED8 60%, #1565C0 100%)";
|
||||||
|
|
||||||
|
/* ══════════════════════════════════════════
|
||||||
|
Sidebar
|
||||||
|
⚠️ NO display property in any inline style here
|
||||||
|
globals.css controls ALL display with !important
|
||||||
|
══════════════════════════════════════════ */
|
||||||
export function Sidebar() {
|
export function Sidebar() {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const user = getStoredUser();
|
const user = getStoredUser();
|
||||||
const permissions = user?.permissions ?? navSections.flatMap(s => s.items.map(i => i.permission));
|
const permissions = user?.permissions ?? navSections.flatMap(s => s.items.map(i => i.permission));
|
||||||
|
const { open, setOpen } = useSidebarDrawer();
|
||||||
|
|
||||||
|
useEffect(() => { setOpen(false); }, [pathname, setOpen]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
document.body.style.overflow = open ? "hidden" : "";
|
||||||
|
return () => { document.body.style.overflow = ""; };
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/*
|
{/* ══ 1. Full sidebar — lg+ ══*/}
|
||||||
Full sidebar — visible lg+.
|
|
||||||
No `left`/`right` is set anywhere: placement comes purely from
|
|
||||||
document order + `dir="rtl"` on <html>. A flex row in RTL lays
|
|
||||||
its first child against the inline-start edge, which is
|
|
||||||
physically the RIGHT of the screen. Because <Sidebar /> is
|
|
||||||
still the first child in DashboardLayout, it now renders on
|
|
||||||
the right automatically — no positional CSS to flip.
|
|
||||||
*/}
|
|
||||||
<aside
|
<aside
|
||||||
|
id="sb-full"
|
||||||
suppressHydrationWarning
|
suppressHydrationWarning
|
||||||
className="hidden lg:flex lg:flex-col"
|
|
||||||
style={{
|
style={{
|
||||||
|
background: GRAD,
|
||||||
|
flexDirection: "column", /* NO display property */
|
||||||
width: "var(--sidebar-width)",
|
width: "var(--sidebar-width)",
|
||||||
flexShrink: 0,
|
flexShrink: 0,
|
||||||
background: "linear-gradient(175deg, #1E3A8A 0%, #1D4ED8 60%, #1565C0 100%)",
|
|
||||||
minHeight: "100vh",
|
minHeight: "100vh",
|
||||||
padding: "20px 12px",
|
padding: "20px 12px",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<SidebarContent
|
<SidebarContent pathname={pathname} permissions={permissions} user={user} compact={false} />
|
||||||
pathname={pathname}
|
|
||||||
permissions={permissions}
|
|
||||||
user={user}
|
|
||||||
compact={false}
|
|
||||||
/>
|
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
{/*
|
{/* ══ 2. Compact rail */}
|
||||||
Compact icon rail — md and below (replaces the old behavior of
|
|
||||||
hiding the sidebar entirely under `lg`). Fixed to the
|
|
||||||
inline-end... no: fixed to the RIGHT edge explicitly, because a
|
|
||||||
`position: fixed` element takes no part in flex flow and so
|
|
||||||
gets no automatic RTL placement from document order. This is
|
|
||||||
exactly the kind of element logical properties exist for:
|
|
||||||
`inset-inline-end: 0` means "right in RTL, left in LTR"
|
|
||||||
without a manual swap if direction ever toggles.
|
|
||||||
*/}
|
|
||||||
<aside
|
<aside
|
||||||
|
id="sb-compact"
|
||||||
suppressHydrationWarning
|
suppressHydrationWarning
|
||||||
className="hidden md:flex lg:hidden md:flex-col md:items-center"
|
aria-label="التنقل المصغر"
|
||||||
style={{
|
style={{
|
||||||
|
background: GRAD,
|
||||||
|
flexDirection: "column", /* NO display property */
|
||||||
|
alignItems: "center",
|
||||||
position: "fixed",
|
position: "fixed",
|
||||||
insetBlockStart: 0,
|
top: 0,
|
||||||
insetBlockEnd: 0,
|
bottom: 0,
|
||||||
insetInlineEnd: 0,
|
right: 0,
|
||||||
|
left: "auto",
|
||||||
width: "var(--sidebar-width-compact)",
|
width: "var(--sidebar-width-compact)",
|
||||||
background: "linear-gradient(175deg, #1E3A8A 0%, #1D4ED8 60%, #1565C0 100%)",
|
|
||||||
padding: "16px 0",
|
padding: "16px 0",
|
||||||
zIndex: 30,
|
zIndex: 30,
|
||||||
overflowY: "auto",
|
overflowY: "auto",
|
||||||
}}
|
}}
|
||||||
aria-label="التنقل المصغر"
|
|
||||||
>
|
>
|
||||||
<SidebarContent
|
<SidebarContent pathname={pathname} permissions={permissions} user={user} compact={true} />
|
||||||
pathname={pathname}
|
</aside>
|
||||||
permissions={permissions}
|
|
||||||
user={user}
|
{/* mobile drower*/}
|
||||||
compact={true}
|
|
||||||
|
{/* open drower*/}
|
||||||
|
{open && (
|
||||||
|
<div
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
aria-hidden="true"
|
||||||
|
style={{
|
||||||
|
position: "fixed",
|
||||||
|
top: 0, left: 0, right: 0, bottom: 0,
|
||||||
|
background: "rgba(0,0,0,0.5)",
|
||||||
|
zIndex: 40,
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Drawer panel */}
|
||||||
|
<aside
|
||||||
|
id="sb-drawer"
|
||||||
|
suppressHydrationWarning
|
||||||
|
aria-label="قائمة التنقل"
|
||||||
|
style={{
|
||||||
|
background: GRAD,
|
||||||
|
flexDirection: "column", /* NO display property */
|
||||||
|
position: "fixed",
|
||||||
|
top: 0,
|
||||||
|
bottom: 0,
|
||||||
|
right: 0,
|
||||||
|
left: "auto",
|
||||||
|
width: "var(--sidebar-width)",
|
||||||
|
padding: "20px 12px",
|
||||||
|
zIndex: 50,
|
||||||
|
overflowY: "auto",
|
||||||
|
/* transform بيخفي/يظهر الـ drawer على sm */
|
||||||
|
transform: open ? "translateX(0)" : "translateX(100%)",
|
||||||
|
transition: "transform 280ms cubic-bezier(0.4,0,0.2,1)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* زرار الإغلاق */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
aria-label="إغلاق القائمة"
|
||||||
|
style={{
|
||||||
|
position: "absolute",
|
||||||
|
top: 14,
|
||||||
|
left: 12,
|
||||||
|
background: "rgba(255,255,255,0.12)",
|
||||||
|
border: "none",
|
||||||
|
borderRadius: 8,
|
||||||
|
width: 30, height: 30,
|
||||||
|
display: "flex", alignItems: "center", justifyContent: "center",
|
||||||
|
cursor: "pointer",
|
||||||
|
color: "#fff",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none"
|
||||||
|
stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
|
||||||
|
<path d="M18 6 6 18M6 6l12 12"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<SidebarContent pathname={pathname} permissions={permissions} user={user} compact={false} />
|
||||||
</aside>
|
</aside>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ══════════════════════════════════════════
|
||||||
|
SidebarContent
|
||||||
|
══════════════════════════════════════════ */
|
||||||
function SidebarContent({
|
function SidebarContent({
|
||||||
pathname,
|
pathname, permissions, user, compact,
|
||||||
permissions,
|
|
||||||
user,
|
|
||||||
compact,
|
|
||||||
}: {
|
}: {
|
||||||
pathname: string;
|
pathname: string;
|
||||||
permissions: string[];
|
permissions: string[];
|
||||||
@@ -119,40 +229,28 @@ function SidebarContent({
|
|||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/* Logo */}
|
|
||||||
<div style={{ marginBottom: 28, display: "flex", justifyContent: compact ? "center" : "flex-start" }}>
|
<div style={{ marginBottom: 28, display: "flex", justifyContent: compact ? "center" : "flex-start" }}>
|
||||||
<Logo white />
|
{compact ? <BrandIcon size={36} /> : <Logo white />}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Nav sections */}
|
<nav style={{ flex: 1, display: "flex", flexDirection: "column", width: "100%" }}
|
||||||
<nav
|
aria-label="Main navigation">
|
||||||
style={{ flex: 1, display: "flex", flexDirection: "column", gap: 0, width: "100%" }}
|
|
||||||
aria-label="Main navigation"
|
|
||||||
>
|
|
||||||
{navSections.map((section) => (
|
{navSections.map((section) => (
|
||||||
<div key={section.label} style={{ marginBottom: 8 }}>
|
<div key={section.label} style={{ marginBottom: 8 }}>
|
||||||
{!compact && (
|
{!compact && (
|
||||||
<p style={{
|
<p style={{
|
||||||
fontSize: 9,
|
fontSize: 9, letterSpacing: "0.14em", textTransform: "uppercase",
|
||||||
letterSpacing: "0.14em",
|
color: "rgba(255,255,255,0.45)", padding: "8px 8px 4px",
|
||||||
textTransform: "uppercase",
|
fontWeight: 600, textAlign: "start", margin: 0,
|
||||||
color: "rgba(255,255,255,0.45)",
|
|
||||||
padding: "8px 8px 4px",
|
|
||||||
fontWeight: 600,
|
|
||||||
textAlign: "start",
|
|
||||||
}}>
|
}}>
|
||||||
{section.label}
|
{section.label}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{section.items.map((item) => {
|
{section.items.map((item) => {
|
||||||
const allowed = item.permission === "read-dashboard"
|
const allowed = item.permission === "read-dashboard" || permissions.includes(item.permission);
|
||||||
|| permissions.includes(item.permission);
|
|
||||||
if (!allowed) return null;
|
if (!allowed) return null;
|
||||||
|
|
||||||
const active = pathname === item.href
|
const active = pathname === item.href
|
||||||
|| (item.href !== "/dashboard" && pathname.startsWith(item.href));
|
|| (item.href !== "/dashboard" && pathname.startsWith(item.href));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
key={item.href}
|
key={item.href}
|
||||||
@@ -176,11 +274,8 @@ function SidebarContent({
|
|||||||
textAlign: "start",
|
textAlign: "start",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<i
|
<i className={`ti ${item.icon}`} aria-hidden="true"
|
||||||
className={`ti ${item.icon}`}
|
style={{ fontSize: compact ? 18 : 16, flexShrink: 0 }} />
|
||||||
aria-hidden="true"
|
|
||||||
style={{ fontSize: compact ? 18 : 16, flexShrink: 0 }}
|
|
||||||
/>
|
|
||||||
{!compact && item.label}
|
{!compact && item.label}
|
||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
@@ -189,34 +284,23 @@ function SidebarContent({
|
|||||||
))}
|
))}
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
{/* User badge — collapses to an avatar dot in compact mode */}
|
|
||||||
{compact ? (
|
{compact ? (
|
||||||
<div
|
<div
|
||||||
suppressHydrationWarning
|
suppressHydrationWarning
|
||||||
title={user?.name ?? user?.userName ?? "—"}
|
title={user?.name ?? user?.userName ?? "—"}
|
||||||
style={{
|
style={{
|
||||||
width: 36,
|
width: 36, height: 36, borderRadius: "var(--radius-full)",
|
||||||
height: 36,
|
|
||||||
borderRadius: "var(--radius-full)",
|
|
||||||
background: "rgba(255,255,255,0.18)",
|
background: "rgba(255,255,255,0.18)",
|
||||||
display: "flex",
|
display: "flex", alignItems: "center", justifyContent: "center",
|
||||||
alignItems: "center",
|
fontSize: 13, fontWeight: 600, color: "#fff", marginTop: 8,
|
||||||
justifyContent: "center",
|
|
||||||
fontSize: 13,
|
|
||||||
fontWeight: 600,
|
|
||||||
color: "#fff",
|
|
||||||
marginTop: 8,
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{(user?.name ?? user?.userName ?? "—").slice(0, 1)}
|
{(user?.name ?? user?.userName ?? "—").slice(0, 1)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div style={{
|
<div style={{
|
||||||
background: "rgba(255,255,255,0.12)",
|
background: "rgba(255,255,255,0.12)", borderRadius: 10,
|
||||||
borderRadius: 10,
|
padding: "10px 12px", marginTop: 8, width: "100%",
|
||||||
padding: "10px 12px",
|
|
||||||
marginTop: 8,
|
|
||||||
width: "100%",
|
|
||||||
}}>
|
}}>
|
||||||
<p suppressHydrationWarning style={{ fontSize: 13, fontWeight: 500, color: "#fff", margin: 0, textAlign: "start" }}>
|
<p suppressHydrationWarning style={{ fontSize: 13, fontWeight: 500, color: "#fff", margin: 0, textAlign: "start" }}>
|
||||||
{user?.name ?? user?.userName ?? "—"}
|
{user?.name ?? user?.userName ?? "—"}
|
||||||
|
|||||||
@@ -2,9 +2,11 @@
|
|||||||
|
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { clearAuth, getStoredUser } from "@/src/lib/auth";
|
import { clearAuth, getStoredUser } from "@/src/lib/auth";
|
||||||
|
import { useSidebarDrawer, BrandIconButton } from "./Sidebar";
|
||||||
|
|
||||||
export function Topbar() {
|
export function Topbar() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const { setOpen } = useSidebarDrawer();
|
||||||
|
|
||||||
async function handleLogout() {
|
async function handleLogout() {
|
||||||
await clearAuth();
|
await clearAuth();
|
||||||
@@ -24,33 +26,27 @@ export function Topbar() {
|
|||||||
display: "flex",
|
display: "flex",
|
||||||
alignItems: "center",
|
alignItems: "center",
|
||||||
justifyContent: "space-between",
|
justifyContent: "space-between",
|
||||||
/*
|
|
||||||
`justify-content: space-between` and `display: flex` are
|
|
||||||
direction-agnostic — they already flip with `dir` for free.
|
|
||||||
The title block (first child) lands at the inline-start edge
|
|
||||||
(right, in RTL) and the actions cluster (second child) lands
|
|
||||||
at inline-end (left). That matches the brief's "primary
|
|
||||||
actions easily accessible" requirement: in Arabic dashboards
|
|
||||||
the page title reads first at the right, and the role badge
|
|
||||||
+ logout sit together at the natural reading end — unchanged
|
|
||||||
from before, just now correctly positioned by `dir` instead
|
|
||||||
of by accident.
|
|
||||||
*/
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
{/* عنوان الصفحة */}
|
||||||
<div>
|
<div>
|
||||||
<p style={{ fontSize: 14, fontWeight: 600, color: "var(--color-text-primary)", margin: 0, textAlign: "start" }}>
|
<p style={{ fontSize: 14, fontWeight: 600, color: "var(--color-text-primary)", margin: 0, textAlign: "start" }}>
|
||||||
لوحة التحكم
|
لوحة التحكم
|
||||||
</p>
|
</p>
|
||||||
<p style={{ fontSize: 11, color: "var(--color-text-muted)", margin: 0, textAlign: "start" }}>
|
<p style={{ fontSize: 11, color: "var(--color-text-muted)", margin: 0, textAlign: "start" }}>
|
||||||
{/* English product label intentionally stays LTR-embedded so
|
|
||||||
"Operations dashboard" doesn't get its word order or
|
|
||||||
punctuation reversed by the surrounding RTL run. */}
|
|
||||||
<span className="ltr-embed">Operations dashboard</span>
|
<span className="ltr-embed">Operations dashboard</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div style={{ display: "flex", alignItems: "center", gap: 12 }}>
|
{/* أكشنز */}
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 10 }}>
|
||||||
|
|
||||||
|
{/* زرار المنيو — sm فقط، globals.css بتتحكم في الـ display */}
|
||||||
|
<div id="topbar-menu-btn">
|
||||||
|
<BrandIconButton onClick={() => setOpen(true)} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* الدور */}
|
||||||
<div
|
<div
|
||||||
suppressHydrationWarning
|
suppressHydrationWarning
|
||||||
style={{
|
style={{
|
||||||
@@ -65,14 +61,13 @@ export function Topbar() {
|
|||||||
{user?.role ?? "—"}
|
{user?.role ?? "—"}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* خروج */}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={handleLogout}
|
onClick={handleLogout}
|
||||||
style={{
|
style={{
|
||||||
fontSize: 12,
|
fontSize: 12, fontWeight: 500,
|
||||||
fontWeight: 500,
|
color: "#DC2626", background: "#FEF2F2",
|
||||||
color: "#DC2626",
|
|
||||||
background: "#FEF2F2",
|
|
||||||
border: "1px solid #FECACA",
|
border: "1px solid #FECACA",
|
||||||
borderRadius: "var(--radius-full)",
|
borderRadius: "var(--radius-full)",
|
||||||
padding: "5px 14px",
|
padding: "5px 14px",
|
||||||
|
|||||||
@@ -1,36 +1,64 @@
|
|||||||
import { Sidebar } from "../components/layout/Sidebar";
|
"use client";
|
||||||
import { Topbar } from "../components/layout/Topbar";
|
|
||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
import { usePathname } from "next/navigation";
|
||||||
|
import { Sidebar, SidebarProvider } from "../components/layout/Sidebar";
|
||||||
|
import { Topbar } from "../components/layout/Topbar";
|
||||||
|
|
||||||
|
function DashShell({ children }: { children: React.ReactNode }) {
|
||||||
|
const contentRef = useRef<HTMLDivElement>(null);
|
||||||
|
const pathname = usePathname();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const el = contentRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
|
||||||
|
function applyPadding() {
|
||||||
|
if (!el) return;
|
||||||
|
const w = window.innerWidth;
|
||||||
|
if (w >= 768 && w < 1024) {
|
||||||
|
|
||||||
|
el.style.paddingInlineEnd = "72px";
|
||||||
|
} else {
|
||||||
|
el.style.paddingInlineEnd = "0px";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
applyPadding();
|
||||||
|
window.addEventListener("resize", applyPadding);
|
||||||
|
return () => window.removeEventListener("resize", applyPadding);
|
||||||
|
}, [pathname]);
|
||||||
|
|
||||||
export default function DashboardLayout({
|
|
||||||
children,
|
|
||||||
}: {
|
|
||||||
children: React.ReactNode;
|
|
||||||
}) {
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="flex min-h-screen"
|
style={{
|
||||||
style={{ background: "var(--color-surface-muted)" }}
|
display: "flex",
|
||||||
|
minHeight: "100vh",
|
||||||
|
background: "var(--color-surface-muted)",
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{/*
|
|
||||||
Sidebar is still the first flex child. With dir="rtl" on <html>
|
|
||||||
(set in app/layout.tsx) this is enough to place the full
|
|
||||||
sidebar on the right with no positional CSS — see Sidebar.tsx.
|
|
||||||
*/}
|
|
||||||
<Sidebar />
|
<Sidebar />
|
||||||
|
|
||||||
{/*
|
|
||||||
The compact icon rail (md and below) is `position: fixed`, so it
|
|
||||||
doesn't take up flex space. This wrapper reserves room for it
|
|
||||||
with `paddingInlineEnd`, which means "right padding in RTL,
|
|
||||||
left padding in LTR" — it never needs to be touched again if
|
|
||||||
direction changes.
|
|
||||||
*/}
|
|
||||||
<div
|
<div
|
||||||
className="flex min-w-0 flex-1 flex-col md:[padding-inline-end:var(--sidebar-width-compact)] lg:[padding-inline-end:0]"
|
ref={contentRef}
|
||||||
|
id="dash-content"
|
||||||
|
style={{
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<Topbar />
|
<Topbar />
|
||||||
<main className="flex-1 p-6">{children}</main>
|
<main style={{ flex: 1, padding: "1.7rem" }}>{children}</main>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<SidebarProvider>
|
||||||
|
<DashShell>{children}</DashShell>
|
||||||
|
</SidebarProvider>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
@@ -1,47 +1,32 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { getStoredToken } from "@/src/lib/auth";
|
|
||||||
import { get } from "@/src/services/api";
|
|
||||||
import { Spinner, Alert } from "@/src/Components/UI";
|
|
||||||
|
|
||||||
interface Order {
|
|
||||||
id: string;
|
import { useState, useCallback } from "react";
|
||||||
shipmentNumber: string;
|
import { Alert, Spinner, Toast } from "@/src/Components/UI";
|
||||||
recipientName: string;
|
import { OrderFormModal } from "@/src/Components/Order/Orderformmodal";
|
||||||
recipientPhone: string;
|
import { OrderDeleteModal } from "@/src/Components/Order/Orderdeletemodal";
|
||||||
currentStatus: "Created" | "Assigned" | "InTransit" | "Delivered" | "Returned" | "Cancelled";
|
import { OrderDetailPanel, ORDER_STATUS_MAP } from "@/src/Components/Order/OrderDetailBanel";
|
||||||
totalPrice?: number;
|
import { useOrders } from "@/src/hooks/useOrder";
|
||||||
paymentMethod?: string;
|
import type { CreateOrderPayload, Order, UpdateOrderPayload } from "@/src/types/order";
|
||||||
paymentStatus?: "Pending" | "Paid" | "Failed" | "Refunded";
|
|
||||||
client?: { name: string };
|
// ── Helpers — copied verbatim from app/dashboard/drivers/page.tsx ───────
|
||||||
trip?: { tripNumber: string };
|
|
||||||
createdAt: string;
|
function fmtDate(iso?: string | null): string {
|
||||||
|
if (!iso) return "—";
|
||||||
|
return new Date(iso).toLocaleDateString("ar-SA", {
|
||||||
|
year: "numeric", month: "short", day: "numeric",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ApiResponse {
|
function fmtAmount(n?: number | null): string {
|
||||||
data: {
|
if (n == null) return "—";
|
||||||
data: Order[];
|
return `${n.toFixed(2)} ر.س`;
|
||||||
pagination: { total: number; page: number; pages: number };
|
|
||||||
meta?: { total: number; pages: number };
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const STATUS_MAP: Record<Order["currentStatus"], { label: string; color: string; bg: string; border: string }> = {
|
// ── Styles — identical tokens/values to the Drivers page, per the
|
||||||
Created: { label: "تم الإنشاء", color: "#1E40AF", bg: "#EFF6FF", border: "#BFDBFE" },
|
// "no new styles" constraint; only column widths differ to fit Order's
|
||||||
Assigned: { label: "مُعيَّن", color: "#5B21B6", bg: "#F5F3FF", border: "#DDD6FE" },
|
// field set (shipment / recipient / client / amount / status / actions).
|
||||||
InTransit: { label: "قيد التوصيل", color: "#854D0E", bg: "#FFFBEB", border: "#FDE68A" },
|
|
||||||
Delivered: { label: "تم التسليم", color: "#166534", bg: "#DCFCE7", border: "#BBF7D0" },
|
|
||||||
Returned: { label: "مُرتجع", color: "#991B1B", bg: "#FEF2F2", border: "#FECACA" },
|
|
||||||
Cancelled: { label: "ملغي", color: "#64748B", bg: "#F1F5F9", border: "#E2E8F0" },
|
|
||||||
};
|
|
||||||
|
|
||||||
const PAY_MAP: Record<string, { label: string; color: string }> = {
|
|
||||||
Pending: { label: "معلَّق", color: "#D97706" },
|
|
||||||
Paid: { label: "مدفوع", color: "#16A34A" },
|
|
||||||
Failed: { label: "فشل", color: "#DC2626" },
|
|
||||||
Refunded: { label: "مُسترجع", color: "#64748B" },
|
|
||||||
};
|
|
||||||
|
|
||||||
const cardStyle: React.CSSProperties = {
|
const cardStyle: React.CSSProperties = {
|
||||||
borderRadius: "var(--radius-xl)",
|
borderRadius: "var(--radius-xl)",
|
||||||
@@ -62,220 +47,417 @@ const thStyle: React.CSSProperties = {
|
|||||||
borderBottom: "1px solid var(--color-border)",
|
borderBottom: "1px solid var(--color-border)",
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function OrdersPage() {
|
// Shared across header + rows — keep these in sync or columns will misalign.
|
||||||
const [orders, setOrders] = useState<Order[]>([]);
|
const ROW_GRID_COLUMNS = "1.6fr 1.6fr 1.2fr 1.1fr 1fr 0.8fr";
|
||||||
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 [statusFilter, setStatusFilter] = useState<string>("");
|
|
||||||
|
|
||||||
useEffect(() => {
|
const iconBtnBase: React.CSSProperties = {
|
||||||
const token = getStoredToken();
|
width: 30,
|
||||||
setLoading(true);
|
height: 30,
|
||||||
setError(null);
|
display: "flex",
|
||||||
const params = new URLSearchParams({ page: String(page), limit: "10" });
|
alignItems: "center",
|
||||||
if (search) params.set("search", search);
|
justifyContent: "center",
|
||||||
if (statusFilter) params.set("currentStatus", statusFilter);
|
borderRadius: "var(--radius-md)",
|
||||||
get<ApiResponse>(`orders?${params}`, token)
|
cursor: "pointer",
|
||||||
.then((res) => {
|
flexShrink: 0,
|
||||||
const payload = res.data ?? res;
|
};
|
||||||
setOrders(payload.data ?? []);
|
|
||||||
setTotal(payload.meta?.total ?? 0);
|
|
||||||
setPages(payload.meta?.pages ?? 1);
|
|
||||||
})
|
|
||||||
.catch((err: Error) => setError(err.message))
|
|
||||||
.finally(() => setLoading(false));
|
|
||||||
}, [page, search, statusFilter]);
|
|
||||||
|
|
||||||
|
// ── Page Component ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export default function OrderComponent() {
|
||||||
|
const {
|
||||||
|
orders, loading, error, total, pages, page,
|
||||||
|
search, statusFilter, setPage, handleSearch, handleStatusFilter, clearError,
|
||||||
|
createOrder, updateOrder, updateStatus, deleteOrder,
|
||||||
|
notification, reload,
|
||||||
|
} = useOrders();
|
||||||
|
|
||||||
|
// ── Panel / modal state — same three-state shape as DriversPage
|
||||||
|
// (selected id for the detail panel, "new" | Order | null for the
|
||||||
|
// form modal, Order | null for the delete modal). ───────────────────
|
||||||
|
const [selectedOrderId, setSelectedOrderId] = useState<string | null>(null);
|
||||||
|
const [formOrder, setFormOrder] = useState<Order | null | "new">(null);
|
||||||
|
const [deleteTarget, setDeleteTarget] = useState<Order | null>(null);
|
||||||
|
const [deleting, setDeleting] = useState(false);
|
||||||
|
// Bumped after a successful edit/status-change to force the detail panel
|
||||||
|
// to re-fetch — same trick as DriversPage's panelRefreshKey.
|
||||||
|
const [panelRefreshKey, setPanelRefreshKey] = useState(0);
|
||||||
|
|
||||||
|
// ── Handlers ─────────────────────────────────────────────────────────
|
||||||
|
const handleEdit = useCallback((order: Order) => {
|
||||||
|
setSelectedOrderId(null);
|
||||||
|
setFormOrder(order);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDelete = useCallback((order: Order) => {
|
||||||
|
setSelectedOrderId(null);
|
||||||
|
setDeleteTarget(order);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// ── Notifications: create/update success or failure surfaces as a
|
||||||
|
// toast via useOrders()' notify() — see useOrders.ts createOrder /
|
||||||
|
// updateOrder. Field-level / request errors additionally render
|
||||||
|
// inside the form modal itself via its own <Alert>. ────────────────
|
||||||
|
const handleFormSubmit = useCallback(
|
||||||
|
async (
|
||||||
|
payload: CreateOrderPayload | UpdateOrderPayload,
|
||||||
|
isNew: boolean,
|
||||||
|
): Promise<boolean> => {
|
||||||
|
let ok: boolean;
|
||||||
|
|
||||||
|
if (isNew) {
|
||||||
|
ok = await createOrder(payload as CreateOrderPayload);
|
||||||
|
} else {
|
||||||
|
const id = (formOrder as Order).id;
|
||||||
|
ok = await updateOrder(id, payload as UpdateOrderPayload);
|
||||||
|
// Re-fetch detail panel so updated fields are visible immediately
|
||||||
|
if (ok && selectedOrderId) setPanelRefreshKey((k) => k + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok;
|
||||||
|
},
|
||||||
|
[formOrder, createOrder, updateOrder, selectedOrderId],
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Notification: status change made from the detail panel bubbles up
|
||||||
|
// here and fires the same success toast the table-level actions use,
|
||||||
|
// keeping feedback consistent regardless of where the action started. ──
|
||||||
|
const handleStatusChanged = useCallback(() => {
|
||||||
|
setPanelRefreshKey((k) => k + 1);
|
||||||
|
reload();
|
||||||
|
}, [reload]);
|
||||||
|
|
||||||
|
const handleConfirmDelete = useCallback(async () => {
|
||||||
|
if (!deleteTarget) return;
|
||||||
|
setDeleting(true);
|
||||||
|
const ok = await deleteOrder(deleteTarget.id);
|
||||||
|
setDeleting(false);
|
||||||
|
if (ok) setDeleteTarget(null);
|
||||||
|
}, [deleteTarget, deleteOrder]);
|
||||||
|
|
||||||
|
// ── Render ───────────────────────────────────────────────────────────
|
||||||
return (
|
return (
|
||||||
<section style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
|
<>
|
||||||
|
<section style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
|
||||||
|
|
||||||
{/* Header */}
|
{/* ── Header ── */}
|
||||||
<header style={{
|
<header style={{
|
||||||
borderRadius: "var(--radius-xl)",
|
borderRadius: "var(--radius-xl)",
|
||||||
border: "1px solid var(--color-border)",
|
border: "1px solid var(--color-border)",
|
||||||
background: "var(--color-surface)",
|
background: "var(--color-surface)",
|
||||||
padding: "1.5rem 2rem",
|
padding: "1.5rem 2rem",
|
||||||
boxShadow: "var(--shadow-card)",
|
boxShadow: "var(--shadow-card)",
|
||||||
}}>
|
}}>
|
||||||
<p style={{ fontSize: 11, letterSpacing: "0.3em", textTransform: "uppercase", color: "#2563EB", fontWeight: 600 }}>
|
<p style={{ fontSize: 11, letterSpacing: "0.3em", textTransform: "uppercase", color: "#2563EB", fontWeight: 600 }}>
|
||||||
إدارة الشحنات
|
إدارة الشحنات
|
||||||
</p>
|
</p>
|
||||||
<div className="mt-3 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
|
<div style={{ marginTop: "0.75rem", display: "flex", flexDirection: "column", gap: "1rem" }}>
|
||||||
<div>
|
<div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: "1rem" }}>
|
||||||
<h1 style={{ fontSize: "1.5rem", fontWeight: 700, color: "var(--color-text-primary)", margin: 0 }}>
|
<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)" }}>
|
</h1>
|
||||||
إجمالي <strong style={{ color: "var(--color-text-primary)" }}>{total}</strong> طلب
|
<p style={{ marginTop: "0.25rem", fontSize: 13, color: "var(--color-text-muted)" }}>
|
||||||
</p>
|
إجمالي{" "}
|
||||||
|
<strong style={{ color: "var(--color-text-primary)" }}>{total}</strong>{" "}
|
||||||
|
طلب مسجل
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ display: "flex", gap: "0.75rem", alignItems: "center", flexWrap: "wrap" }}>
|
||||||
|
{/* Status filter — ported from app/dashboard/orders/page.tsx */}
|
||||||
|
<select
|
||||||
|
value={statusFilter}
|
||||||
|
onChange={(e) => handleStatusFilter(e.target.value)}
|
||||||
|
dir="rtl"
|
||||||
|
style={{
|
||||||
|
height: 40, borderRadius: "var(--radius-lg)",
|
||||||
|
border: "1px solid var(--color-border)",
|
||||||
|
background: "var(--color-surface)",
|
||||||
|
fontSize: 13, color: "var(--color-text-secondary)",
|
||||||
|
padding: "0 0.75rem", outline: "none",
|
||||||
|
fontFamily: "var(--font-sans)", cursor: "pointer",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">كل الحالات</option>
|
||||||
|
{Object.entries(ORDER_STATUS_MAP).map(([k, v]) => (
|
||||||
|
<option key={k} value={k}>{v.label}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
{/* 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={() => setFormOrder("new")}
|
||||||
|
style={{
|
||||||
|
height: 40, padding: "0 1.25rem",
|
||||||
|
borderRadius: "var(--radius-lg)",
|
||||||
|
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)",
|
||||||
|
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>
|
</div>
|
||||||
<div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
|
</header>
|
||||||
{/* Status filter */}
|
|
||||||
<select
|
{/* ── Notifications: page-level error banner (e.g. failed list load)
|
||||||
value={statusFilter}
|
dismissible via clearError() from the hook. Action-result
|
||||||
onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }}
|
toasts (create/update/delete/status success or failure) render
|
||||||
|
separately below via <Toast>, matching DriversPage's split
|
||||||
|
between a persistent <Alert> for fetch errors and a transient
|
||||||
|
<Toast> for action feedback. ── */}
|
||||||
|
{error && (
|
||||||
|
<Alert type="error" message={error} onClose={clearError} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ── Table ── */}
|
||||||
|
<div style={cardStyle}>
|
||||||
|
<div
|
||||||
|
dir="rtl"
|
||||||
|
style={{
|
||||||
|
display: "grid",
|
||||||
|
gridTemplateColumns: ROW_GRID_COLUMNS,
|
||||||
|
...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>
|
||||||
|
) : orders.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 }}>
|
||||||
|
{orders.map((o, i) => {
|
||||||
|
const statusCfg = ORDER_STATUS_MAP[o.currentStatus] ?? ORDER_STATUS_MAP.Created;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
key={o.id}
|
||||||
|
onClick={() => setSelectedOrderId(o.id)}
|
||||||
|
style={{
|
||||||
|
display: "grid",
|
||||||
|
gridTemplateColumns: ROW_GRID_COLUMNS,
|
||||||
|
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")}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<p style={{ fontWeight: 600, fontFamily: "var(--font-mono)", color: "#2563EB", margin: 0 }}>{o.shipmentNumber}</p>
|
||||||
|
<p style={{ marginTop: 2, fontSize: 11, color: "var(--color-text-muted)" }}>{fmtDate(o.createdAt)}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p style={{ fontWeight: 600, color: "var(--color-text-primary)", margin: 0 }}>{o.recipientName}</p>
|
||||||
|
<p style={{ marginTop: 2, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--color-text-muted)" }}>{o.recipientPhone}</p>
|
||||||
|
</div>
|
||||||
|
<span style={{ color: "var(--color-text-secondary)" }}>{o.client?.name ?? "—"}</span>
|
||||||
|
<span style={{ fontWeight: 600, color: "var(--color-text-primary)", fontFamily: "var(--font-mono)" }}>
|
||||||
|
{fmtAmount(o.totalPrice)}
|
||||||
|
</span>
|
||||||
|
<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>
|
||||||
|
|
||||||
|
{/* ── Inline row actions: edit / delete ──
|
||||||
|
stopPropagation is required on both buttons so the
|
||||||
|
click doesn't bubble up to the <li> onClick and
|
||||||
|
open the detail panel as well. */}
|
||||||
|
<div style={{ display: "flex", gap: "0.4rem" }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="تعديل الطلب"
|
||||||
|
title="تعديل"
|
||||||
|
onClick={(e) => { e.stopPropagation(); handleEdit(o); }}
|
||||||
|
style={{
|
||||||
|
...iconBtnBase,
|
||||||
|
border: "1px solid var(--color-brand-200)",
|
||||||
|
background: "var(--color-brand-50, #EFF6FF)",
|
||||||
|
color: "var(--color-brand-600)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
|
||||||
|
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
|
||||||
|
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="حذف الطلب"
|
||||||
|
title="حذف"
|
||||||
|
onClick={(e) => { e.stopPropagation(); handleDelete(o); }}
|
||||||
|
style={{
|
||||||
|
...iconBtnBase,
|
||||||
|
border: "1px solid #FECACA",
|
||||||
|
background: "#FEF2F2",
|
||||||
|
color: "#DC2626",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<polyline points="3 6 5 6 21 6" />
|
||||||
|
<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
|
||||||
|
<path d="M10 11v6M14 11v6" />
|
||||||
|
<path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ── Pagination ── */}
|
||||||
|
{pages > 1 && (
|
||||||
|
<div
|
||||||
dir="rtl"
|
dir="rtl"
|
||||||
style={{
|
style={{
|
||||||
height: 40, borderRadius: "var(--radius-lg)",
|
display: "flex", alignItems: "center", justifyContent: "space-between",
|
||||||
border: "1px solid var(--color-border)",
|
borderTop: "1px solid var(--color-border)", padding: "0.875rem 1.5rem",
|
||||||
background: "var(--color-surface)",
|
|
||||||
fontSize: 13, color: "var(--color-text-secondary)",
|
|
||||||
padding: "0 0.75rem", outline: "none",
|
|
||||||
fontFamily: "var(--font-sans)",
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<option value="">كل الحالات</option>
|
<span style={{ fontSize: 12, color: "var(--color-text-muted)" }}>
|
||||||
{Object.entries(STATUS_MAP).map(([k, v]) => (
|
صفحة{" "}
|
||||||
<option key={k} value={k}>{v.label}</option>
|
<strong style={{ color: "var(--color-text-primary)" }}>{page}</strong>{" "}
|
||||||
))}
|
من{" "}
|
||||||
</select>
|
<strong style={{ color: "var(--color-text-primary)" }}>{pages}</strong>
|
||||||
{/* Search */}
|
</span>
|
||||||
<div style={{ position: "relative", width: 256 }}>
|
<div style={{ display: "flex", gap: "0.5rem" }}>
|
||||||
<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">
|
{ label: "السابق", action: () => setPage(p => Math.max(1, p - 1)), disabled: page === 1 },
|
||||||
<circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
|
{ label: "التالي", action: () => setPage(p => Math.min(pages, p + 1)), disabled: page === pages },
|
||||||
</svg>
|
].map(btn => (
|
||||||
<input type="text" placeholder="رقم الشحنة أو المستلم..." value={search}
|
<button
|
||||||
onChange={(e) => { setSearch(e.target.value); setPage(1); }} dir="rtl"
|
key={btn.label}
|
||||||
style={{
|
onClick={btn.action}
|
||||||
width: "100%", height: 40, paddingRight: 36, paddingLeft: 12,
|
disabled={btn.disabled}
|
||||||
borderRadius: "var(--radius-lg)",
|
style={{
|
||||||
border: "1px solid var(--color-border)",
|
borderRadius: "var(--radius-lg)",
|
||||||
background: "var(--color-surface)",
|
border: "1px solid var(--color-border)",
|
||||||
fontSize: 13, color: "var(--color-text-primary)",
|
background: "var(--color-surface-muted)",
|
||||||
outline: "none", fontFamily: "var(--font-sans)",
|
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>
|
||||||
</div>
|
)}
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</section>
|
||||||
|
|
||||||
{error && <Alert type="error" message={error} onClose={() => setError(null)} />}
|
{/* ── Detail panel — key forces re-fetch after a successful edit or
|
||||||
|
status change. Status updates triggered inside the panel call
|
||||||
|
updateStatus() from useOrders() (via handleStatusChanged), which
|
||||||
|
fires the same toast as a table-level action. ── */}
|
||||||
|
{selectedOrderId && (
|
||||||
|
<OrderDetailPanel
|
||||||
|
key={`${selectedOrderId}-${panelRefreshKey}`}
|
||||||
|
orderId={selectedOrderId}
|
||||||
|
onClose={() => setSelectedOrderId(null)}
|
||||||
|
onEdit={handleEdit}
|
||||||
|
onDelete={handleDelete}
|
||||||
|
onStatusChanged={handleStatusChanged}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Table */}
|
{/* ── Form modal ── */}
|
||||||
<div style={cardStyle}>
|
{formOrder !== null && (
|
||||||
<div dir="rtl" style={{
|
<OrderFormModal
|
||||||
display: "grid",
|
editOrder={formOrder === "new" ? null : formOrder}
|
||||||
gridTemplateColumns: "1.8fr 1.5fr 1.2fr 1fr 1fr 1fr",
|
onClose={() => setFormOrder(null)}
|
||||||
...thStyle,
|
onSubmit={handleFormSubmit}
|
||||||
}}>
|
/>
|
||||||
<span>رقم الشحنة</span>
|
)}
|
||||||
<span>المستلم</span>
|
|
||||||
<span>العميل</span>
|
|
||||||
<span>المبلغ</span>
|
|
||||||
<span>الحالة</span>
|
|
||||||
<span style={{ textAlign: "center" }}>التاريخ</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{loading ? (
|
{/* ── Delete modal ── */}
|
||||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 12, padding: "4rem 0", color: "var(--color-text-muted)" }}>
|
{deleteTarget && (
|
||||||
<Spinner size="sm" className="text-blue-600" />
|
<OrderDeleteModal
|
||||||
<span style={{ fontSize: 13 }}>جارٍ التحميل…</span>
|
order={deleteTarget}
|
||||||
</div>
|
deleting={deleting}
|
||||||
) : orders.length === 0 ? (
|
onCancel={() => setDeleteTarget(null)}
|
||||||
<p style={{ textAlign: "center", padding: "4rem 0", fontSize: 13, color: "var(--color-text-muted)" }}>
|
onConfirm={handleConfirmDelete}
|
||||||
لا توجد نتائج
|
/>
|
||||||
</p>
|
)}
|
||||||
) : (
|
|
||||||
<ul dir="rtl" style={{ listStyle: "none", margin: 0, padding: 0 }}>
|
|
||||||
{orders.map((o, i) => {
|
|
||||||
const status = STATUS_MAP[o.currentStatus];
|
|
||||||
const pay = o.paymentStatus ? PAY_MAP[o.paymentStatus] : null;
|
|
||||||
return (
|
|
||||||
<li key={o.id} style={{
|
|
||||||
display: "grid",
|
|
||||||
gridTemplateColumns: "1.8fr 1.5fr 1.2fr 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={{ fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 700, color: "#2563EB", margin: 0 }}>
|
|
||||||
{o.shipmentNumber}
|
|
||||||
</p>
|
|
||||||
{o.trip && (
|
|
||||||
<p style={{ marginTop: 2, fontSize: 11, color: "var(--color-text-muted)" }}>
|
|
||||||
رحلة: {o.trip.tripNumber}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p style={{ color: "var(--color-text-primary)", margin: 0 }}>{o.recipientName}</p>
|
|
||||||
<p style={{ marginTop: 2, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--color-text-muted)" }}>
|
|
||||||
{o.recipientPhone}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<span style={{ color: "var(--color-text-secondary)" }}>{o.client?.name ?? "—"}</span>
|
|
||||||
<div>
|
|
||||||
<p style={{ fontWeight: 600, color: "var(--color-text-primary)", margin: 0 }}>
|
|
||||||
{o.totalPrice != null ? `${o.totalPrice.toFixed(2)} ر.س` : "—"}
|
|
||||||
</p>
|
|
||||||
{pay && (
|
|
||||||
<p style={{ marginTop: 2, fontSize: 11, fontWeight: 600, color: pay.color }}>
|
|
||||||
{pay.label}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<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: 11, color: "var(--color-text-muted)" }}>
|
|
||||||
{new Date(o.createdAt).toLocaleDateString("ar-SA", {
|
|
||||||
year: "numeric", month: "short", day: "numeric",
|
|
||||||
})}
|
|
||||||
</span>
|
|
||||||
</li>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</ul>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{pages > 1 && (
|
{/* ── Toast: transient success/error feedback for create, update,
|
||||||
<div dir="rtl" style={{
|
delete, and status-change actions — sourced from useOrders()'
|
||||||
display: "flex", alignItems: "center", justifyContent: "space-between",
|
`notification` state (see useOrders.ts notify()). This is the
|
||||||
borderTop: "1px solid var(--color-border)", padding: "0.875rem 1.5rem",
|
same toast used by the Driver pages via DriverDeleteModal's
|
||||||
}}>
|
parent and useDriver.ts, kept consistent here. ── */}
|
||||||
<span style={{ fontSize: 12, color: "var(--color-text-muted)" }}>
|
<Toast notification={notification} />
|
||||||
صفحة <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>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Named export alongside the default, mirroring src/Components/Driver/index.ts's
|
||||||
|
// pattern of re-exporting each piece for use elsewhere (e.g. a future
|
||||||
|
// app/dashboard/orders/page.tsx importing { OrderComponent }).
|
||||||
|
export { OrderComponent };
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
@import "../src/styles/tokens.css";
|
@import "../src/styles/tokens.css";
|
||||||
@import "tailwindcss";
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
|
||||||
/* ── Base resets ────────────────────────────────────── */
|
/* ── Base resets ────────────────────────────────────── */
|
||||||
*,
|
*,
|
||||||
*::before,
|
*::before,
|
||||||
@@ -12,11 +11,6 @@
|
|||||||
html {
|
html {
|
||||||
scroll-behavior: smooth;
|
scroll-behavior: smooth;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
/* `dir` is now set on <html> in app/layout.tsx (lang="ar" dir="rtl").
|
|
||||||
Tailwind v4 ships native `rtl:` / `ltr:` variants that key off this
|
|
||||||
attribute, so utility classes like `rtl:flex-row-reverse` work
|
|
||||||
without a plugin. Route groups no longer need to set `dir`
|
|
||||||
individually — see report Section 1. */
|
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
@@ -29,8 +23,63 @@ body {
|
|||||||
-moz-osx-font-smoothing: grayscale;
|
-moz-osx-font-smoothing: grayscale;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ════════════════════════════════════════════════════
|
||||||
|
SIDEBAR VISIBILITY
|
||||||
|
⚠️ مفيش display في أي inline style على الـ sidebar elements
|
||||||
|
⚠️ !important عشان يغلب أي حاجة تانية
|
||||||
|
════════════════════════════════════════════════════ */
|
||||||
|
|
||||||
|
/* default: كل العناصر مخفية */
|
||||||
|
#sb-full,
|
||||||
|
#sb-compact,
|
||||||
|
#sb-drawer,
|
||||||
|
#topbar-menu-btn {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* lg+ (≥1024px): full sidebar */
|
||||||
|
@media (min-width: 1024px) {
|
||||||
|
#sb-full { display: flex !important; }
|
||||||
|
#sb-compact { display: none !important; }
|
||||||
|
#sb-drawer { display: none !important; }
|
||||||
|
#topbar-menu-btn { display: none !important; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* md (768px–1023px): compact rail */
|
||||||
|
@media (min-width: 768px) and (max-width: 1023px) {
|
||||||
|
#sb-full { display: none !important; }
|
||||||
|
#sb-compact { display: flex !important; }
|
||||||
|
#sb-drawer { display: none !important; }
|
||||||
|
#topbar-menu-btn { display: none !important; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* sm (<768px): drawer + topbar button */
|
||||||
|
@media (max-width: 767px) {
|
||||||
|
#sb-full { display: none !important; }
|
||||||
|
#sb-compact { display: none !important; }
|
||||||
|
#sb-drawer { display: flex !important; }
|
||||||
|
#topbar-menu-btn { display: flex !important; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ════════════════════════════════════════════════════
|
||||||
|
DASH CONTENT PADDING
|
||||||
|
class selector بيغلب على inline style في CSS
|
||||||
|
بيحجز مكان الـ compact rail الـ fixed على md
|
||||||
|
════════════════════════════════════════════════════ */
|
||||||
|
|
||||||
|
/* sm + lg: مفيش padding إضافي */
|
||||||
|
.dash-content-wrapper {
|
||||||
|
padding-inline-end: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* md فقط: حجز 72px لمكان الـ compact rail */
|
||||||
|
@media (min-width: 768px) and (max-width: 1023px) {
|
||||||
|
.dash-content-wrapper {
|
||||||
|
padding-inline-end: var(--sidebar-width-compact);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* ── Tailwind theme bridge ──────────────────────────── */
|
/* ── Tailwind theme bridge ──────────────────────────── */
|
||||||
/* Expose CSS variables as Tailwind color utilities. */
|
|
||||||
@theme inline {
|
@theme inline {
|
||||||
--color-primary-*: initial;
|
--color-primary-*: initial;
|
||||||
--color-sand-*: initial;
|
--color-sand-*: initial;
|
||||||
@@ -88,18 +137,20 @@ body {
|
|||||||
--font-mono: var(--font-mono);
|
--font-mono: var(--font-mono);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Focus ring utility ─────────────────────────────── */
|
/* ── Focus ring ─────────────────────────────────────── */
|
||||||
/* Unchanged: box-shadow rings are direction-neutral. */
|
|
||||||
.focus-ring {
|
.focus-ring {
|
||||||
outline: none;
|
outline: none;
|
||||||
box-shadow: 0 0 0 2px var(--color-brand-600);
|
box-shadow: 0 0 0 2px var(--color-brand-600);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── RTL icon mirroring ─────────────────────────────────
|
/* ── RTL icon mirroring ─────────────────────────────── */
|
||||||
Directional glyphs (chevrons, arrows, "back") need to visually
|
|
||||||
point the opposite way in RTL even though the underlying icon
|
|
||||||
font glyph doesn't change. Apply .icon-flip-rtl to any <i>/<svg>
|
|
||||||
whose meaning is "forward"/"back" rather than purely decorative. */
|
|
||||||
[dir="rtl"] .icon-flip-rtl {
|
[dir="rtl"] .icon-flip-rtl {
|
||||||
transform: scaleX(-1);
|
transform: scaleX(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── LTR embed for codes/paths ──────────────────────── */
|
||||||
|
.ltr-embed {
|
||||||
|
direction: ltr;
|
||||||
|
unicode-bidi: isolate;
|
||||||
|
display: inline-block;
|
||||||
}
|
}
|
||||||
104
src/Components/Order/OrderDeleteModal.tsx
Normal file
104
src/Components/Order/OrderDeleteModal.tsx
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { Spinner } from "../UI";
|
||||||
|
import type { Order } from "@/src/types/order";
|
||||||
|
|
||||||
|
interface OrderDeleteModalProps {
|
||||||
|
order: Order;
|
||||||
|
deleting: boolean;
|
||||||
|
onCancel: () => void;
|
||||||
|
onConfirm: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors DriverDeleteModal.tsx 1:1 — same alertdialog role, same
|
||||||
|
* backdrop/click-outside-to-close behavior, same Escape-to-close effect,
|
||||||
|
* same button layout. Only the copy and the identifying fields differ.
|
||||||
|
*/
|
||||||
|
export function OrderDeleteModal({ order, deleting, onCancel, onConfirm }: OrderDeleteModalProps) {
|
||||||
|
useEffect(() => {
|
||||||
|
const h = (e: KeyboardEvent) => { if (e.key === "Escape") onCancel(); };
|
||||||
|
window.addEventListener("keydown", h);
|
||||||
|
return () => window.removeEventListener("keydown", h);
|
||||||
|
}, [onCancel]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="alertdialog" aria-modal="true" aria-labelledby="order-del-title"
|
||||||
|
onClick={e => { if (e.target === e.currentTarget) onCancel(); }}
|
||||||
|
style={{
|
||||||
|
position: "fixed", inset: 0, zIndex: 60,
|
||||||
|
background: "rgba(15,23,42,0.55)", backdropFilter: "blur(4px)",
|
||||||
|
display: "flex", alignItems: "center", justifyContent: "center", padding: "1rem",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
onClick={e => e.stopPropagation()}
|
||||||
|
style={{
|
||||||
|
width: "100%", maxWidth: 420,
|
||||||
|
background: "var(--color-surface)",
|
||||||
|
borderRadius: "var(--radius-xl)",
|
||||||
|
border: "1px solid #FECACA",
|
||||||
|
boxShadow: "0 20px 48px rgba(0,0,0,.18)",
|
||||||
|
padding: "2rem",
|
||||||
|
display: "flex", flexDirection: "column", gap: "1rem",
|
||||||
|
textAlign: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Icon */}
|
||||||
|
<div style={{
|
||||||
|
width: 52, height: 52, margin: "0 auto", borderRadius: "50%",
|
||||||
|
background: "#FEF2F2", border: "1px solid #FECACA",
|
||||||
|
display: "flex", alignItems: "center", justifyContent: "center",
|
||||||
|
}}>
|
||||||
|
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#DC2626" strokeWidth="2">
|
||||||
|
<polyline points="3 6 5 6 21 6" />
|
||||||
|
<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
|
||||||
|
<path d="M10 11v6M14 11v6" />
|
||||||
|
<path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h2 id="order-del-title" style={{ fontSize: 17, fontWeight: 700, color: "var(--color-text-primary)", margin: 0 }}>
|
||||||
|
حذف الطلب
|
||||||
|
</h2>
|
||||||
|
<p style={{ marginTop: 8, fontSize: 13, color: "var(--color-text-muted)", lineHeight: 1.6 }}>
|
||||||
|
هل أنت متأكد من حذف الطلب{" "}
|
||||||
|
<strong style={{ color: "var(--color-text-primary)" }}>{order.shipmentNumber}</strong>
|
||||||
|
{" "}الخاص بـ{" "}
|
||||||
|
<span style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>
|
||||||
|
{order.recipientName}
|
||||||
|
</span>
|
||||||
|
؟ لا يمكن التراجع عن هذا الإجراء.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ display: "flex", gap: "0.5rem" }}>
|
||||||
|
<button type="button" onClick={onCancel} disabled={deleting}
|
||||||
|
style={{
|
||||||
|
flex: 1, height: 40, borderRadius: "var(--radius-md)",
|
||||||
|
border: "1px solid var(--color-border)", background: "var(--color-surface)",
|
||||||
|
fontSize: 13, fontWeight: 600, color: "var(--color-text-secondary)",
|
||||||
|
cursor: deleting ? "not-allowed" : "pointer", fontFamily: "var(--font-sans)",
|
||||||
|
}}>
|
||||||
|
إلغاء
|
||||||
|
</button>
|
||||||
|
<button type="button" onClick={onConfirm} disabled={deleting}
|
||||||
|
style={{
|
||||||
|
flex: 1, height: 40, borderRadius: "var(--radius-md)",
|
||||||
|
border: "none", background: "#DC2626",
|
||||||
|
fontSize: 13, fontWeight: 700, color: "#FFF",
|
||||||
|
cursor: deleting ? "not-allowed" : "pointer",
|
||||||
|
display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
|
||||||
|
fontFamily: "var(--font-sans)", opacity: deleting ? 0.7 : 1,
|
||||||
|
}}>
|
||||||
|
{deleting && <Spinner size="sm" className="text-white" />}
|
||||||
|
{deleting ? "جارٍ الحذف…" : "تأكيد الحذف"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
590
src/Components/Order/OrderDetailBanel.tsx
Normal file
590
src/Components/Order/OrderDetailBanel.tsx
Normal file
@@ -0,0 +1,590 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { Spinner, Alert } from "../UI";
|
||||||
|
import { orderService } from "@/src/services/order.service";
|
||||||
|
import type { Order, OrderStatus, UpdateOrderStatusPayload } from "@/src/types/order";
|
||||||
|
|
||||||
|
// ── Status config ────────────────────────────────────────────────────────
|
||||||
|
// Same shape as DRIVER_STATUS_MAP in src/types/driver.ts, kept local here
|
||||||
|
// since order.ts doesn't currently export a colour map of its own.
|
||||||
|
const ORDER_STATUS_MAP: Record<
|
||||||
|
OrderStatus,
|
||||||
|
{ label: string; color: string; bg: string; border: string; dot: string }
|
||||||
|
> = {
|
||||||
|
Created: { label: "تم الإنشاء", color: "#1E40AF", bg: "#EFF6FF", border: "#BFDBFE", dot: "#3B82F6" },
|
||||||
|
Assigned: { label: "مُعيَّن", color: "#5B21B6", bg: "#F5F3FF", border: "#DDD6FE", dot: "#8B5CF6" },
|
||||||
|
InTransit: { label: "قيد التوصيل", color: "#854D0E", bg: "#FFFBEB", border: "#FDE68A", dot: "#D97706" },
|
||||||
|
Delivered: { label: "تم التسليم", color: "#166534", bg: "#DCFCE7", border: "#BBF7D0", dot: "#16A34A" },
|
||||||
|
Returned: { label: "مُرتجع", color: "#991B1B", bg: "#FEF2F2", border: "#FECACA", dot: "#DC2626" },
|
||||||
|
Cancelled: { label: "ملغي", color: "#64748B", bg: "#F1F5F9", border: "#E2E8F0", dot: "#94A3B8" },
|
||||||
|
};
|
||||||
|
|
||||||
|
const PAY_STATUS_MAP: Record<string, { label: string; color: string }> = {
|
||||||
|
Pending: { label: "معلَّق", color: "#D97706" },
|
||||||
|
Paid: { label: "مدفوع", color: "#16A34A" },
|
||||||
|
Failed: { label: "فشل", color: "#DC2626" },
|
||||||
|
Refunded: { label: "مُسترجع", color: "#64748B" },
|
||||||
|
};
|
||||||
|
|
||||||
|
const PAY_METHOD_LABEL: Record<string, string> = {
|
||||||
|
Cash: "نقداً",
|
||||||
|
Card: "بطاقة",
|
||||||
|
Prepaid: "مدفوع مسبقاً",
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Helpers — identical to DriverDetailPanel.tsx's fmtDate ──────────────
|
||||||
|
function fmtDate(iso?: string | null): string {
|
||||||
|
if (!iso) return "—";
|
||||||
|
return new Date(iso).toLocaleDateString("ar-SA", {
|
||||||
|
year: "numeric",
|
||||||
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtAmount(n?: number | string | null): string {
|
||||||
|
if (n == null || n === "") return "—";
|
||||||
|
const num = Number(n);
|
||||||
|
if (isNaN(num)) return "—";
|
||||||
|
return `${num.toFixed(2)} ر.س`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Sub-components — copied verbatim from DriverDetailPanel.tsx ─────────
|
||||||
|
// (DetailRow / SectionHeading carry no Driver-specific logic, so they are
|
||||||
|
// reproduced here rather than imported, matching how the Driver files keep
|
||||||
|
// their detail-panel building blocks local to the panel that uses them.)
|
||||||
|
|
||||||
|
function DetailRow({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
mono = false,
|
||||||
|
warn = false,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
mono?: boolean;
|
||||||
|
warn?: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
alignItems: "baseline",
|
||||||
|
padding: "0.55rem 0",
|
||||||
|
borderBottom: "1px solid var(--color-border)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span style={{ fontSize: 12, color: "var(--color-text-muted)", fontWeight: 600 }}>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
fontSize: 13,
|
||||||
|
fontFamily: mono ? "var(--font-mono)" : "var(--font-sans)",
|
||||||
|
color: warn ? "#D97706" : "var(--color-text-primary)",
|
||||||
|
fontWeight: warn ? 600 : 400,
|
||||||
|
maxWidth: "60%",
|
||||||
|
textAlign: "left",
|
||||||
|
wordBreak: "break-word",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{warn && value !== "—" ? "⚠ " : ""}
|
||||||
|
{value}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SectionHeading({ title }: { title: string }) {
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
style={{
|
||||||
|
fontSize: 11,
|
||||||
|
letterSpacing: "0.25em",
|
||||||
|
textTransform: "uppercase",
|
||||||
|
color: "var(--color-text-hint)",
|
||||||
|
fontWeight: 700,
|
||||||
|
margin: "1.25rem 0 0.5rem",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Props ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
interface OrderDetailPanelProps {
|
||||||
|
orderId: string;
|
||||||
|
onClose: () => void;
|
||||||
|
onEdit: (order: Order) => void;
|
||||||
|
onDelete: (order: Order) => void;
|
||||||
|
/** Bubble a status change up so the list row updates without a full reload */
|
||||||
|
onStatusChanged?: (order: Order) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Component ─────────────────────────────────────────────────────────────
|
||||||
|
// Structurally identical to DriverDetailPanel.tsx: fixed backdrop + slide-in
|
||||||
|
// <aside>, header with avatar-equivalent badge, scrollable body of
|
||||||
|
// SectionHeading/DetailRow blocks, sticky footer actions.
|
||||||
|
|
||||||
|
export function OrderDetailPanel({
|
||||||
|
orderId,
|
||||||
|
onClose,
|
||||||
|
onEdit,
|
||||||
|
onDelete,
|
||||||
|
onStatusChanged,
|
||||||
|
}: OrderDetailPanelProps) {
|
||||||
|
const [order, setOrder] = useState<Order | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Inline status-update control state
|
||||||
|
const [statusDraft, setStatusDraft] = useState<OrderStatus | "">("");
|
||||||
|
const [statusReason, setStatusReason] = useState("");
|
||||||
|
const [updatingStatus, setUpdatingStatus] = useState(false);
|
||||||
|
const [statusError, setStatusError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const loadOrder = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await orderService.getById(orderId);
|
||||||
|
const data = (res as unknown as { data: Order }).data ?? (res as unknown as Order);
|
||||||
|
setOrder(data);
|
||||||
|
setStatusDraft(data.currentStatus);
|
||||||
|
} catch (err: unknown) {
|
||||||
|
setError(err instanceof Error ? err.message : "تعذّر تحميل بيانات الطلب.");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [orderId]);
|
||||||
|
|
||||||
|
useEffect(() => { loadOrder(); }, [loadOrder]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const h = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||||
|
window.addEventListener("keydown", h);
|
||||||
|
return () => window.removeEventListener("keydown", h);
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
// ── Status update — alert shown inline in the panel, success bubbled up ──
|
||||||
|
const handleStatusUpdate = useCallback(async () => {
|
||||||
|
if (!order || !statusDraft || statusDraft === order.currentStatus) return;
|
||||||
|
setUpdatingStatus(true);
|
||||||
|
setStatusError(null);
|
||||||
|
try {
|
||||||
|
const payload: UpdateOrderStatusPayload = { status: statusDraft };
|
||||||
|
if (statusReason) payload.reason = statusReason;
|
||||||
|
const res = await orderService.updateStatus(order.id, payload);
|
||||||
|
const updated = (res as unknown as { data: Order }).data ?? (res as unknown as Order);
|
||||||
|
setOrder(updated);
|
||||||
|
setStatusReason("");
|
||||||
|
onStatusChanged?.(updated);
|
||||||
|
} catch (err: unknown) {
|
||||||
|
setStatusError(err instanceof Error ? err.message : "تعذّر تحديث حالة الطلب.");
|
||||||
|
} finally {
|
||||||
|
setUpdatingStatus(false);
|
||||||
|
}
|
||||||
|
}, [order, statusDraft, statusReason, onStatusChanged]);
|
||||||
|
|
||||||
|
const statusConfig = order ? ORDER_STATUS_MAP[order.currentStatus] : null;
|
||||||
|
const payStatus = order?.paymentStatus ? PAY_STATUS_MAP[order.paymentStatus] : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Backdrop */}
|
||||||
|
<div
|
||||||
|
onClick={onClose}
|
||||||
|
style={{
|
||||||
|
position: "fixed",
|
||||||
|
inset: 0,
|
||||||
|
zIndex: 40,
|
||||||
|
background: "rgba(15,23,42,0.45)",
|
||||||
|
backdropFilter: "blur(2px)",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Slide-in panel */}
|
||||||
|
<aside
|
||||||
|
aria-label="تفاصيل الطلب"
|
||||||
|
style={{
|
||||||
|
position: "fixed",
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
bottom: 0,
|
||||||
|
zIndex: 50,
|
||||||
|
width: "min(520px, 100vw)",
|
||||||
|
background: "var(--color-surface)",
|
||||||
|
borderRight: "1px solid var(--color-border)",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
boxShadow: "8px 0 40px rgba(0,0,0,.18)",
|
||||||
|
overflowY: "hidden",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* ── Header ── */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: "1.25rem 1.5rem",
|
||||||
|
borderBottom: "1px solid var(--color-border)",
|
||||||
|
background: "var(--color-surface-muted)",
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 12 }}>
|
||||||
|
{/* Shipment "avatar" badge — order has no photo, so a glyph stands in for it,
|
||||||
|
matching the circular-badge slot Driver uses for its avatar image. */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
width: 56,
|
||||||
|
height: 56,
|
||||||
|
borderRadius: "50%",
|
||||||
|
flexShrink: 0,
|
||||||
|
border: "2px solid var(--color-brand-200)",
|
||||||
|
background: "var(--color-surface-muted)",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--color-brand-600)" strokeWidth="2">
|
||||||
|
<rect x="2" y="7" width="20" height="14" rx="2"/>
|
||||||
|
<path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2"/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p style={{ fontSize: 11, letterSpacing: "0.3em", textTransform: "uppercase", color: "#2563EB", fontWeight: 600, margin: 0 }}>
|
||||||
|
ملف الطلب
|
||||||
|
</p>
|
||||||
|
{order && (
|
||||||
|
<h2 style={{ fontSize: 17, fontWeight: 700, color: "var(--color-text-primary)", margin: "3px 0 0", fontFamily: "var(--font-mono)" }}>
|
||||||
|
{order.shipmentNumber}
|
||||||
|
</h2>
|
||||||
|
)}
|
||||||
|
{order?.trip?.tripNumber && (
|
||||||
|
<p style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--color-text-muted)", margin: "2px 0 0" }}>
|
||||||
|
رحلة: {order.trip.tripNumber}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
aria-label="إغلاق"
|
||||||
|
style={{
|
||||||
|
width: 34,
|
||||||
|
height: 34,
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
border: "1px solid var(--color-border)",
|
||||||
|
background: "var(--color-surface)",
|
||||||
|
cursor: "pointer",
|
||||||
|
fontSize: 18,
|
||||||
|
color: "var(--color-text-muted)",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ── Scrollable content ── */}
|
||||||
|
<div style={{ flex: 1, overflowY: "auto", padding: "1.25rem 1.5rem" }}>
|
||||||
|
{loading && (
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 12, padding: "2rem 0" }}>
|
||||||
|
<Spinner size="sm" className="text-blue-600" />
|
||||||
|
<span style={{ fontSize: 13, color: "var(--color-text-muted)" }}>جارٍ التحميل…</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div style={{
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
background: "#FEF2F2",
|
||||||
|
border: "1px solid #FECACA",
|
||||||
|
padding: "0.75rem 1rem",
|
||||||
|
fontSize: 13,
|
||||||
|
color: "#DC2626",
|
||||||
|
}}>
|
||||||
|
⚠ {error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{order && !loading && (
|
||||||
|
<>
|
||||||
|
{/* Status badges */}
|
||||||
|
<div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: "1rem" }}>
|
||||||
|
{statusConfig && (
|
||||||
|
<span style={{
|
||||||
|
borderRadius: "var(--radius-full)",
|
||||||
|
border: `1px solid ${statusConfig.border}`,
|
||||||
|
background: statusConfig.bg,
|
||||||
|
padding: "0.3rem 0.875rem",
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: 700,
|
||||||
|
color: statusConfig.color,
|
||||||
|
display: "inline-flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 6,
|
||||||
|
}}>
|
||||||
|
<span style={{ width: 7, height: 7, borderRadius: "50%", background: statusConfig.dot }} />
|
||||||
|
{statusConfig.label}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{payStatus && (
|
||||||
|
<span style={{
|
||||||
|
borderRadius: "var(--radius-full)",
|
||||||
|
border: "1px solid var(--color-border)",
|
||||||
|
background: "var(--color-surface-muted)",
|
||||||
|
padding: "0.3rem 0.875rem",
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: 700,
|
||||||
|
color: payStatus.color,
|
||||||
|
}}>
|
||||||
|
{payStatus.label}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<SectionHeading title="بيانات المستلم" />
|
||||||
|
<DetailRow label="اسم المستلم" value={order.recipientName} />
|
||||||
|
<DetailRow label="رقم الجوال" value={order.recipientPhone} mono />
|
||||||
|
<DetailRow label="العميل" value={order.client?.name ?? "—"} />
|
||||||
|
|
||||||
|
<SectionHeading title="بيانات الشحنة" />
|
||||||
|
<DetailRow label="رقم الشحنة" value={order.shipmentNumber} mono />
|
||||||
|
<DetailRow label="نوع الشحنة" value={order.type ?? "—"} />
|
||||||
|
<DetailRow label="الكمية" value={String(order.quantity ?? "—")} />
|
||||||
|
<DetailRow label="الوزن" value={order.weight != null ? `${order.weight} كجم` : "—"} />
|
||||||
|
<DetailRow label="الرحلة" value={order.trip?.tripNumber ?? "—"} mono />
|
||||||
|
|
||||||
|
<SectionHeading title="بيانات الدفع" />
|
||||||
|
<DetailRow label="طريقة الدفع" value={order.paymentMethod ? PAY_METHOD_LABEL[order.paymentMethod] ?? order.paymentMethod : "—"} />
|
||||||
|
<DetailRow label="حالة الدفع" value={payStatus?.label ?? "—"} />
|
||||||
|
<DetailRow label="الإجمالي الفرعي" value={fmtAmount(order.subTotal)} mono />
|
||||||
|
<DetailRow label="ضريبة القيمة المضافة" value={fmtAmount(order.vatAmount)} mono />
|
||||||
|
<DetailRow label="الإجمالي" value={fmtAmount(order.totalPrice)} mono />
|
||||||
|
|
||||||
|
{/* ── Delivery Address ── */}
|
||||||
|
{order.deliveryAddress?.details && Object.values(order.deliveryAddress.details).some(Boolean) && (
|
||||||
|
<>
|
||||||
|
<SectionHeading title="عنوان التسليم" />
|
||||||
|
{order.deliveryAddress.details.city && <DetailRow label="المدينة" value={order.deliveryAddress.details.city} />}
|
||||||
|
{order.deliveryAddress.details.district && <DetailRow label="الحي" value={order.deliveryAddress.details.district} />}
|
||||||
|
{order.deliveryAddress.details.street && <DetailRow label="الشارع" value={order.deliveryAddress.details.street} />}
|
||||||
|
{order.deliveryAddress.details.buildingNo && <DetailRow label="رقم المبنى" value={order.deliveryAddress.details.buildingNo} mono />}
|
||||||
|
{order.deliveryAddress.details.unitNo && <DetailRow label="رقم الوحدة" value={order.deliveryAddress.details.unitNo} mono />}
|
||||||
|
{order.deliveryAddress.details.zipCode && <DetailRow label="الرمز البريدي" value={order.deliveryAddress.details.zipCode} mono />}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{!order.deliveryAddress?.details && order.deliveryAddressId && (
|
||||||
|
<>
|
||||||
|
<SectionHeading title="عنوان التسليم" />
|
||||||
|
<DetailRow label="معرّف العنوان" value={order.deliveryAddressId} mono />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ── Pickup Address ── */}
|
||||||
|
{order.pickupAddress?.details && Object.values(order.pickupAddress.details).some(Boolean) && (
|
||||||
|
<>
|
||||||
|
<SectionHeading title="عنوان الاستلام" />
|
||||||
|
{order.pickupAddress.details.city && <DetailRow label="المدينة" value={order.pickupAddress.details.city} />}
|
||||||
|
{order.pickupAddress.details.district && <DetailRow label="الحي" value={order.pickupAddress.details.district} />}
|
||||||
|
{order.pickupAddress.details.street && <DetailRow label="الشارع" value={order.pickupAddress.details.street} />}
|
||||||
|
{order.pickupAddress.details.buildingNo && <DetailRow label="رقم المبنى" value={order.pickupAddress.details.buildingNo} mono />}
|
||||||
|
{order.pickupAddress.details.unitNo && <DetailRow label="رقم الوحدة" value={order.pickupAddress.details.unitNo} mono />}
|
||||||
|
{order.pickupAddress.details.zipCode && <DetailRow label="الرمز البريدي" value={order.pickupAddress.details.zipCode} mono />}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{!order.pickupAddress?.details && order.pickupAddressId && (
|
||||||
|
<>
|
||||||
|
<SectionHeading title="عنوان الاستلام" />
|
||||||
|
<DetailRow label="معرّف العنوان" value={order.pickupAddressId} mono />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<SectionHeading title="معلومات النظام" /> <DetailRow label="تاريخ الإنشاء" value={fmtDate(order.createdAt)} />
|
||||||
|
<DetailRow label="آخر تحديث" value={fmtDate(order.updatedAt)} />
|
||||||
|
|
||||||
|
{/* ── Inline status update ──
|
||||||
|
Same alert/feedback pattern as the rest of the panel: a
|
||||||
|
local Alert renders any failure, success simply updates
|
||||||
|
the badge above (no extra toast — the parent page's
|
||||||
|
global toast already fires via onStatusChanged). */}
|
||||||
|
<SectionHeading title="تحديث الحالة" />
|
||||||
|
{statusError && (
|
||||||
|
<Alert type="error" message={statusError} onClose={() => setStatusError(null)} />
|
||||||
|
)}
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 8 }}>
|
||||||
|
<select
|
||||||
|
value={statusDraft}
|
||||||
|
onChange={(e) => setStatusDraft(e.target.value as OrderStatus)}
|
||||||
|
dir="rtl"
|
||||||
|
style={{
|
||||||
|
height: 40, padding: "0 0.75rem",
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
border: "1px solid var(--color-border)",
|
||||||
|
background: "var(--color-surface)",
|
||||||
|
fontSize: 13, color: "var(--color-text-primary)",
|
||||||
|
fontFamily: "var(--font-sans)", cursor: "pointer",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{Object.entries(ORDER_STATUS_MAP).map(([k, v]) => (
|
||||||
|
<option key={k} value={k}>{v.label}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={statusReason}
|
||||||
|
onChange={(e) => setStatusReason(e.target.value)}
|
||||||
|
placeholder="سبب التغيير (اختياري)"
|
||||||
|
dir="rtl"
|
||||||
|
style={{
|
||||||
|
height: 40, padding: "0 0.75rem",
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
border: "1px solid var(--color-border)",
|
||||||
|
background: "var(--color-surface)",
|
||||||
|
fontSize: 13, color: "var(--color-text-primary)",
|
||||||
|
fontFamily: "var(--font-sans)",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleStatusUpdate}
|
||||||
|
disabled={updatingStatus || !statusDraft || statusDraft === order.currentStatus}
|
||||||
|
style={{
|
||||||
|
height: 40,
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
border: "none",
|
||||||
|
background: updatingStatus ? "var(--color-brand-400)" : "var(--color-brand-600)",
|
||||||
|
fontSize: 13, fontWeight: 700, color: "#FFF",
|
||||||
|
cursor: (updatingStatus || !statusDraft || statusDraft === order.currentStatus) ? "not-allowed" : "pointer",
|
||||||
|
opacity: (!statusDraft || statusDraft === order.currentStatus) ? 0.6 : 1,
|
||||||
|
display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
|
||||||
|
fontFamily: "var(--font-sans)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{updatingStatus && <Spinner size="sm" className="text-white" />}
|
||||||
|
{updatingStatus ? "جارٍ التحديث…" : "تحديث الحالة"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{order.statusHistory && order.statusHistory.length > 0 && (
|
||||||
|
<>
|
||||||
|
<SectionHeading title="سجل الحالات" />
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||||
|
{order.statusHistory.slice(0, 5).map((h) => {
|
||||||
|
const s = ORDER_STATUS_MAP[h.status] ?? ORDER_STATUS_MAP.Created;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={h.id}
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
alignItems: "center",
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
border: `1px solid ${s.border}`,
|
||||||
|
background: s.bg,
|
||||||
|
padding: "0.5rem 0.875rem",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<span style={{ fontSize: 12, fontWeight: 600, color: s.color }}>{s.label}</span>
|
||||||
|
{h.reason && (
|
||||||
|
<span style={{ fontSize: 11, color: "var(--color-text-muted)", marginRight: 8 }}>
|
||||||
|
— {h.reason}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<span style={{ fontSize: 11, color: "var(--color-text-muted)" }}>
|
||||||
|
{fmtDate(h.createdAt)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ── Footer actions ── */}
|
||||||
|
{order && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: "1rem 1.5rem",
|
||||||
|
borderTop: "1px solid var(--color-border)",
|
||||||
|
background: "var(--color-surface-muted)",
|
||||||
|
display: "flex",
|
||||||
|
gap: "0.75rem",
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onDelete(order)}
|
||||||
|
style={{
|
||||||
|
height: 40, padding: "0 1rem",
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
border: "1px solid #FECACA",
|
||||||
|
background: "#FEF2F2",
|
||||||
|
fontSize: 13, fontWeight: 700, color: "#DC2626",
|
||||||
|
cursor: "pointer", fontFamily: "var(--font-sans)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
حذف
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onEdit(order)}
|
||||||
|
style={{
|
||||||
|
height: 40, padding: "0 1rem",
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
border: "1px solid var(--color-brand-200)",
|
||||||
|
background: "var(--color-brand-50, #EFF6FF)",
|
||||||
|
fontSize: 13, fontWeight: 700, color: "var(--color-brand-600)",
|
||||||
|
cursor: "pointer", fontFamily: "var(--font-sans)",
|
||||||
|
display: "flex", alignItems: "center", gap: 6,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
|
||||||
|
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
|
||||||
|
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
|
||||||
|
</svg>
|
||||||
|
تعديل
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
style={{
|
||||||
|
flex: 1, height: 40,
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
border: "1px solid var(--color-border)",
|
||||||
|
background: "var(--color-surface)",
|
||||||
|
fontSize: 13, fontWeight: 600, color: "var(--color-text-secondary)",
|
||||||
|
cursor: "pointer", fontFamily: "var(--font-sans)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
إغلاق
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</aside>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { ORDER_STATUS_MAP, PAY_STATUS_MAP, PAY_METHOD_LABEL };
|
||||||
929
src/Components/Order/OrderFormModal.tsx
Normal file
929
src/Components/Order/OrderFormModal.tsx
Normal file
@@ -0,0 +1,929 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState, useCallback } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { Alert, Spinner } from "../UI";
|
||||||
|
import { getStoredToken } from "@/src/lib/auth";
|
||||||
|
import { clientService } from "@/src/services/client.service";
|
||||||
|
import { tripService } from "@/src/services/trip.service";
|
||||||
|
import { createOrderSchema, updateOrderSchema } from "@/src/validations/order.validation";
|
||||||
|
import type { ValidationError } from "yup";
|
||||||
|
import type {
|
||||||
|
Order,
|
||||||
|
CreateOrderPayload,
|
||||||
|
UpdateOrderPayload,
|
||||||
|
PaymentMethod,
|
||||||
|
PaymentStatus,
|
||||||
|
} from "@/src/types/order";
|
||||||
|
import type { Client } from "@/src/types/client";
|
||||||
|
import type { Trip } from "@/src/types/trip";
|
||||||
|
import type { OrderSchemaErrors } from "@/src/validations/order.validation";
|
||||||
|
|
||||||
|
// ── Shared input / label styles — verbatim from DriverFormModal.tsx ──────────
|
||||||
|
|
||||||
|
const inputBase: React.CSSProperties = {
|
||||||
|
width: "100%",
|
||||||
|
height: 40,
|
||||||
|
padding: "0 0.75rem",
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
border: "1px solid var(--color-border)",
|
||||||
|
background: "var(--color-surface)",
|
||||||
|
fontSize: 13,
|
||||||
|
color: "var(--color-text-primary)",
|
||||||
|
outline: "none",
|
||||||
|
fontFamily: "var(--font-sans)",
|
||||||
|
};
|
||||||
|
|
||||||
|
const labelStyle: React.CSSProperties = {
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
gap: 6,
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: 600,
|
||||||
|
color: "var(--color-text-secondary)",
|
||||||
|
};
|
||||||
|
|
||||||
|
const errorTextStyle: React.CSSProperties = {
|
||||||
|
fontSize: 11,
|
||||||
|
color: "var(--color-danger)",
|
||||||
|
fontWeight: 500,
|
||||||
|
};
|
||||||
|
|
||||||
|
const sectionHeadingStyle: React.CSSProperties = {
|
||||||
|
fontSize: 11,
|
||||||
|
letterSpacing: "0.25em",
|
||||||
|
textTransform: "uppercase",
|
||||||
|
color: "var(--color-text-hint)",
|
||||||
|
fontWeight: 700,
|
||||||
|
margin: "0.5rem 0 0",
|
||||||
|
};
|
||||||
|
|
||||||
|
const optionalLabelStyle: React.CSSProperties = {
|
||||||
|
fontSize: 10,
|
||||||
|
fontWeight: 500,
|
||||||
|
color: "var(--color-text-hint)",
|
||||||
|
marginRight: 4,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Small "Create new" link rendered below each relation dropdown. */
|
||||||
|
const createLinkStyle: React.CSSProperties = {
|
||||||
|
fontSize: 11,
|
||||||
|
color: "var(--color-brand-600)",
|
||||||
|
textDecoration: "none",
|
||||||
|
fontWeight: 500,
|
||||||
|
marginTop: 2,
|
||||||
|
display: "inline-flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 3,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Props ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
interface OrderFormModalProps {
|
||||||
|
editOrder: Order | null;
|
||||||
|
onClose: () => void;
|
||||||
|
onSubmit: (
|
||||||
|
payload: CreateOrderPayload | UpdateOrderPayload,
|
||||||
|
isNew: boolean,
|
||||||
|
) => Promise<boolean>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Component ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function OrderFormModal({ editOrder, onClose, onSubmit }: OrderFormModalProps) {
|
||||||
|
const isNew = editOrder === null;
|
||||||
|
|
||||||
|
// ── Relation data — clients & trips loaded once on mount ─────────────────
|
||||||
|
const [clients, setClients] = useState<Client[]>([]);
|
||||||
|
const [trips, setTrips] = useState<Trip[]>([]);
|
||||||
|
const [relLoading, setRelLoading] = useState(true);
|
||||||
|
|
||||||
|
// ── Form state ────────────────────────────────────────────────────────────
|
||||||
|
const [shipmentNumber, setShipmentNumber] = useState(editOrder?.shipmentNumber ?? "");
|
||||||
|
const [recipientName, setRecipientName] = useState(editOrder?.recipientName ?? "");
|
||||||
|
const [recipientPhone, setRecipientPhone] = useState(editOrder?.recipientPhone ?? "");
|
||||||
|
const [clientId, setClientId] = useState(editOrder?.clientId ?? "");
|
||||||
|
const [tripId, setTripId] = useState(editOrder?.tripId ?? "");
|
||||||
|
const [type, setType] = useState(editOrder?.type ?? "");
|
||||||
|
const [quantity, setQuantity] = useState(String(editOrder?.quantity ?? 1));
|
||||||
|
const [weight, setWeight] = useState(
|
||||||
|
editOrder?.weight != null ? String(editOrder.weight) : "",
|
||||||
|
);
|
||||||
|
const [subTotal, setSubTotal] = useState(
|
||||||
|
editOrder?.subTotal != null ? String(editOrder.subTotal) : "",
|
||||||
|
);
|
||||||
|
const [vatRate, setVatRate] = useState(
|
||||||
|
editOrder?.vatRate != null ? String(editOrder.vatRate) : "",
|
||||||
|
);
|
||||||
|
const [paymentMethod, setPaymentMethod] = useState<PaymentMethod | "">(
|
||||||
|
editOrder?.paymentMethod ?? "",
|
||||||
|
);
|
||||||
|
const [paymentStatus, setPaymentStatus] = useState<PaymentStatus | "">(
|
||||||
|
editOrder?.paymentStatus ?? "",
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Address state ─────────────────────────────────────────────────────────
|
||||||
|
// Delivery address (عنوان التسليم) — always creates new MongoDB doc
|
||||||
|
const [delCity, setDelCity] = useState(editOrder?.deliveryAddress?.details?.city ?? "");
|
||||||
|
const [delDistrict, setDelDistrict] = useState(editOrder?.deliveryAddress?.details?.district ?? "");
|
||||||
|
const [delStreet, setDelStreet] = useState(editOrder?.deliveryAddress?.details?.street ?? "");
|
||||||
|
const [delBuildingNo, setDelBuildingNo] = useState(editOrder?.deliveryAddress?.details?.buildingNo ?? "");
|
||||||
|
const [delUnitNo, setDelUnitNo] = useState(editOrder?.deliveryAddress?.details?.unitNo ?? "");
|
||||||
|
const [delZipCode, setDelZipCode] = useState(editOrder?.deliveryAddress?.details?.zipCode ?? "");
|
||||||
|
// GeoJSON coordinates [longitude, latitude] — required by backend
|
||||||
|
const [delLng, setDelLng] = useState(
|
||||||
|
editOrder?.deliveryAddress?.location?.coordinates?.[0] != null
|
||||||
|
? String(editOrder.deliveryAddress!.location!.coordinates![0])
|
||||||
|
: "",
|
||||||
|
);
|
||||||
|
const [delLat, setDelLat] = useState(
|
||||||
|
editOrder?.deliveryAddress?.location?.coordinates?.[1] != null
|
||||||
|
? String(editOrder.deliveryAddress!.location!.coordinates![1])
|
||||||
|
: "",
|
||||||
|
);
|
||||||
|
|
||||||
|
// Pickup address (عنوان الاستلام) — إما ID موجود أو object جديد
|
||||||
|
const [pickupMode, setPickupMode] = useState<"id" | "new">(
|
||||||
|
editOrder?.pickupAddressId ? "id" : "new",
|
||||||
|
);
|
||||||
|
const [pickupAddressId, setPickupAddressId] = useState(editOrder?.pickupAddressId ?? "");
|
||||||
|
const [pkpCity, setPkpCity] = useState(editOrder?.pickupAddress?.details?.city ?? "");
|
||||||
|
const [pkpDistrict, setPkpDistrict] = useState(editOrder?.pickupAddress?.details?.district ?? "");
|
||||||
|
const [pkpStreet, setPkpStreet] = useState(editOrder?.pickupAddress?.details?.street ?? "");
|
||||||
|
const [pkpBuildingNo, setPkpBuildingNo] = useState(editOrder?.pickupAddress?.details?.buildingNo ?? "");
|
||||||
|
const [pkpUnitNo, setPkpUnitNo] = useState(editOrder?.pickupAddress?.details?.unitNo ?? "");
|
||||||
|
const [pkpZipCode, setPkpZipCode] = useState(editOrder?.pickupAddress?.details?.zipCode ?? "");
|
||||||
|
// GeoJSON coordinates [longitude, latitude] — optional for pickup
|
||||||
|
const [pkpLng, setPkpLng] = useState(
|
||||||
|
editOrder?.pickupAddress?.location?.coordinates?.[0] != null
|
||||||
|
? String(editOrder.pickupAddress!.location!.coordinates![0])
|
||||||
|
: "",
|
||||||
|
);
|
||||||
|
const [pkpLat, setPkpLat] = useState(
|
||||||
|
editOrder?.pickupAddress?.location?.coordinates?.[1] != null
|
||||||
|
? String(editOrder.pickupAddress!.location!.coordinates![1])
|
||||||
|
: "",
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
const [errors, setErrors] = useState<OrderSchemaErrors>({});
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [apiError, setApiError] = useState("");
|
||||||
|
const firstRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
// ── Load clients + trips in parallel on mount ─────────────────────────────
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const token = getStoredToken();
|
||||||
|
|
||||||
|
// Fetch first 100 clients (enough for a practical dropdown)
|
||||||
|
const clientRes = await clientService.getAll(1, "", token);
|
||||||
|
const clientPayload = (clientRes as any).data ?? clientRes;
|
||||||
|
const clientList: Client[] = clientPayload.data ?? [];
|
||||||
|
|
||||||
|
// Fetch first 100 trips (active ones the order can be assigned to)
|
||||||
|
const tripRes = await tripService.getAll({ page: 1, limit: 100 }, token);
|
||||||
|
const tripPayload = (tripRes as any).data ?? tripRes;
|
||||||
|
const tripList: Trip[] = tripPayload.data ?? [];
|
||||||
|
|
||||||
|
if (!cancelled) {
|
||||||
|
setClients(clientList);
|
||||||
|
setTrips(tripList);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// Logged so failures are visible during development instead of
|
||||||
|
// failing completely silently when clientService/tripService error out
|
||||||
|
// (e.g. expired token, CORS, 500). Dropdowns stay empty either way,
|
||||||
|
// and the user can still navigate to the create pages via the helper
|
||||||
|
// links — but now they also see a message explaining why.
|
||||||
|
console.error("OrderFormModal: failed to load clients/trips", err);
|
||||||
|
if (!cancelled) {
|
||||||
|
setApiError("تعذّر تحميل قوائم العملاء والرحلات. تحقق من اتصالك وحاول إعادة فتح النافذة.");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (!cancelled) setRelLoading(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// ── Keyboard / focus setup ────────────────────────────────────────────────
|
||||||
|
useEffect(() => { firstRef.current?.focus(); }, []);
|
||||||
|
useEffect(() => {
|
||||||
|
const h = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||||
|
window.addEventListener("keydown", h);
|
||||||
|
return () => window.removeEventListener("keydown", h);
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
// ── Dynamic input error style ─────────────────────────────────────────────
|
||||||
|
const inputStyle = (field: keyof OrderSchemaErrors): React.CSSProperties => ({
|
||||||
|
...inputBase,
|
||||||
|
border: errors[field]
|
||||||
|
? "1px solid var(--color-danger)"
|
||||||
|
: inputBase.border,
|
||||||
|
...(errors[field] ? { background: "#FEF2F2" } : {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const clearFieldError = useCallback(
|
||||||
|
(field: keyof OrderSchemaErrors) => setErrors((p) => ({ ...p, [field]: undefined })),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Yup validation ────────────────────────────────────────────────────────
|
||||||
|
const runValidation = useCallback(async (): Promise<boolean> => {
|
||||||
|
const schema = isNew ? createOrderSchema : updateOrderSchema;
|
||||||
|
try {
|
||||||
|
await schema.validate(
|
||||||
|
{
|
||||||
|
tripId,
|
||||||
|
clientId,
|
||||||
|
shipmentNumber,
|
||||||
|
recipientName,
|
||||||
|
recipientPhone,
|
||||||
|
quantity: quantity ? Number(quantity) : undefined,
|
||||||
|
weight: weight ? Number(weight) : undefined,
|
||||||
|
subTotal: subTotal ? Number(subTotal) : undefined,
|
||||||
|
vatRate: vatRate ? Number(vatRate) : undefined,
|
||||||
|
paymentMethod: paymentMethod || undefined,
|
||||||
|
paymentStatus: paymentStatus || undefined,
|
||||||
|
type: type || undefined,
|
||||||
|
},
|
||||||
|
{ abortEarly: false },
|
||||||
|
);
|
||||||
|
setErrors({});
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
const bag: OrderSchemaErrors = {};
|
||||||
|
(err as ValidationError).inner.forEach((e) => {
|
||||||
|
if (e.path) (bag as Record<string, string>)[e.path] = e.message;
|
||||||
|
});
|
||||||
|
setErrors(bag);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}, [isNew, tripId, clientId, shipmentNumber, recipientName, recipientPhone,
|
||||||
|
quantity, weight, subTotal, vatRate, paymentMethod, paymentStatus, type]);
|
||||||
|
|
||||||
|
// ── Submit ────────────────────────────────────────────────────────────────
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const valid = await runValidation();
|
||||||
|
if (!valid) return;
|
||||||
|
|
||||||
|
// Build clean payload.
|
||||||
|
// NOTE: deliveryAddressId / pickupAddressId are intentionally omitted
|
||||||
|
// from create payloads — the backend creates address records from
|
||||||
|
// deliveryAddressData / pickupAddressData instead.
|
||||||
|
const payload: Record<string, unknown> = {
|
||||||
|
shipmentNumber,
|
||||||
|
recipientName,
|
||||||
|
recipientPhone,
|
||||||
|
clientId,
|
||||||
|
quantity: Number(quantity) || 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
// tripId: only include when a value is selected
|
||||||
|
if (tripId) payload.tripId = tripId;
|
||||||
|
|
||||||
|
// Optional fields — include only when filled
|
||||||
|
if (type) payload.type = type;
|
||||||
|
if (weight) payload.weight = Number(weight);
|
||||||
|
if (subTotal) payload.subTotal = Number(subTotal);
|
||||||
|
if (vatRate) payload.vatRate = Number(vatRate);
|
||||||
|
if (paymentMethod) payload.paymentMethod = paymentMethod;
|
||||||
|
if (paymentStatus) payload.paymentStatus = paymentStatus;
|
||||||
|
|
||||||
|
// ── Build delivery address object (only if at least one field filled) ──
|
||||||
|
const delDetails = {
|
||||||
|
...(delCity && { city: delCity }),
|
||||||
|
...(delDistrict && { district: delDistrict }),
|
||||||
|
...(delStreet && { street: delStreet }),
|
||||||
|
...(delBuildingNo && { buildingNo: delBuildingNo }),
|
||||||
|
...(delUnitNo && { unitNo: delUnitNo }),
|
||||||
|
...(delZipCode && { zipCode: delZipCode }),
|
||||||
|
};
|
||||||
|
// coordinates are always included when provided (required by backend GeoJSON schema)
|
||||||
|
const delCoordinates =
|
||||||
|
delLng.trim() && delLat.trim()
|
||||||
|
? [Number(delLng), Number(delLat)]
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
if (Object.keys(delDetails).length > 0 || delCoordinates) {
|
||||||
|
payload.deliveryAddress = {
|
||||||
|
...(Object.keys(delDetails).length > 0 && { details: delDetails }),
|
||||||
|
...(delCoordinates && { location: { coordinates: delCoordinates } }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Build pickup address: ID or new object ──
|
||||||
|
if (pickupMode === "id" && pickupAddressId.trim()) {
|
||||||
|
payload.pickupAddressId = pickupAddressId.trim();
|
||||||
|
} else {
|
||||||
|
const pkpDetails = {
|
||||||
|
...(pkpCity && { city: pkpCity }),
|
||||||
|
...(pkpDistrict && { district: pkpDistrict }),
|
||||||
|
...(pkpStreet && { street: pkpStreet }),
|
||||||
|
...(pkpBuildingNo && { buildingNo: pkpBuildingNo }),
|
||||||
|
...(pkpUnitNo && { unitNo: pkpUnitNo }),
|
||||||
|
...(pkpZipCode && { zipCode: pkpZipCode }),
|
||||||
|
};
|
||||||
|
const pkpCoordinates =
|
||||||
|
pkpLng.trim() && pkpLat.trim()
|
||||||
|
? [Number(pkpLng), Number(pkpLat)]
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
if (Object.keys(pkpDetails).length > 0 || pkpCoordinates) {
|
||||||
|
payload.pickupAddress = {
|
||||||
|
...(Object.keys(pkpDetails).length > 0 && { details: pkpDetails }),
|
||||||
|
...(pkpCoordinates && { location: { coordinates: pkpCoordinates } }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
setSaving(true);
|
||||||
|
setApiError("");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const ok = await onSubmit(payload as unknown as CreateOrderPayload, isNew);
|
||||||
|
if (ok) {
|
||||||
|
onClose();
|
||||||
|
} else {
|
||||||
|
setApiError("حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const message =
|
||||||
|
err instanceof Error ? err.message : "حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.";
|
||||||
|
setApiError(message);
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Render ────────────────────────────────────────────────────────────────
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby="order-modal-title"
|
||||||
|
onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
|
||||||
|
style={{
|
||||||
|
position: "fixed", inset: 0, zIndex: 50,
|
||||||
|
background: "rgba(15,23,42,0.55)", backdropFilter: "blur(4px)",
|
||||||
|
display: "flex", alignItems: "center", justifyContent: "center",
|
||||||
|
padding: "1rem", overflowY: "auto",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
style={{
|
||||||
|
width: "100%", maxWidth: 640,
|
||||||
|
background: "var(--color-surface)",
|
||||||
|
borderRadius: "var(--radius-2xl)",
|
||||||
|
border: "1px solid var(--color-border)",
|
||||||
|
boxShadow: "0 24px 64px rgba(0,0,0,.18)",
|
||||||
|
overflow: "hidden", margin: "auto",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* ── Header ── */}
|
||||||
|
<div style={{
|
||||||
|
display: "flex", alignItems: "center", justifyContent: "space-between",
|
||||||
|
padding: "1.25rem 1.5rem",
|
||||||
|
borderBottom: "1px solid var(--color-border)",
|
||||||
|
background: "var(--color-surface-muted)",
|
||||||
|
}}>
|
||||||
|
<div>
|
||||||
|
<p style={{
|
||||||
|
fontSize: 11, letterSpacing: "0.3em", textTransform: "uppercase",
|
||||||
|
color: "#2563EB", fontWeight: 600, margin: 0,
|
||||||
|
}}>
|
||||||
|
{isNew ? "إنشاء طلب" : "تعديل طلب"}
|
||||||
|
</p>
|
||||||
|
<h2
|
||||||
|
id="order-modal-title"
|
||||||
|
style={{
|
||||||
|
fontSize: 17, fontWeight: 700,
|
||||||
|
color: "var(--color-text-primary)",
|
||||||
|
margin: "4px 0 0", fontFamily: "var(--font-mono)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isNew ? "طلب جديد" : editOrder?.shipmentNumber}
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button" onClick={onClose} aria-label="إغلاق"
|
||||||
|
style={{
|
||||||
|
width: 34, height: 34, borderRadius: "var(--radius-md)",
|
||||||
|
border: "1px solid var(--color-border)", background: "var(--color-surface)",
|
||||||
|
cursor: "pointer", fontSize: 18, color: "var(--color-text-muted)",
|
||||||
|
display: "flex", alignItems: "center", justifyContent: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ── Form ── */}
|
||||||
|
<form
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
noValidate
|
||||||
|
style={{
|
||||||
|
padding: "1.5rem",
|
||||||
|
display: "flex", flexDirection: "column", gap: "1rem",
|
||||||
|
maxHeight: "75vh", overflowY: "auto",
|
||||||
|
}}
|
||||||
|
dir="rtl"
|
||||||
|
>
|
||||||
|
{apiError && (
|
||||||
|
<Alert type="error" message={apiError} onClose={() => setApiError("")} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ── Section: Shipment & Recipient ── */}
|
||||||
|
<p style={sectionHeadingStyle}>بيانات الشحنة والمستلم</p>
|
||||||
|
|
||||||
|
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
|
||||||
|
|
||||||
|
{/* Shipment number — required */}
|
||||||
|
<label style={labelStyle}>
|
||||||
|
رقم الشحنة *
|
||||||
|
<input
|
||||||
|
ref={firstRef}
|
||||||
|
style={inputStyle("shipmentNumber")}
|
||||||
|
value={shipmentNumber}
|
||||||
|
onChange={(e) => {
|
||||||
|
setShipmentNumber(e.target.value);
|
||||||
|
clearFieldError("shipmentNumber");
|
||||||
|
}}
|
||||||
|
placeholder="SHP-0001"
|
||||||
|
dir="ltr"
|
||||||
|
autoComplete="off"
|
||||||
|
/>
|
||||||
|
{errors.shipmentNumber && (
|
||||||
|
<span style={errorTextStyle}>{errors.shipmentNumber}</span>
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{/* ── Client dropdown — required ── */}
|
||||||
|
<label style={labelStyle}>
|
||||||
|
العميل *
|
||||||
|
<select
|
||||||
|
style={{
|
||||||
|
...inputStyle("clientId"),
|
||||||
|
cursor: relLoading ? "wait" : "pointer",
|
||||||
|
// Shift placeholder text right for RTL
|
||||||
|
paddingRight: "0.75rem",
|
||||||
|
}}
|
||||||
|
value={clientId}
|
||||||
|
disabled={relLoading}
|
||||||
|
onChange={(e) => {
|
||||||
|
setClientId(e.target.value);
|
||||||
|
clearFieldError("clientId");
|
||||||
|
}}
|
||||||
|
dir="rtl"
|
||||||
|
>
|
||||||
|
<option value="">
|
||||||
|
{relLoading ? "جارٍ التحميل…" : "اختر العميل"}
|
||||||
|
</option>
|
||||||
|
{clients.map((c) => (
|
||||||
|
<option key={c.id} value={c.id}>
|
||||||
|
{c.name}
|
||||||
|
{c.phone ? ` — ${c.phone}` : ""}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{errors.clientId && (
|
||||||
|
<span style={errorTextStyle}>{errors.clientId}</span>
|
||||||
|
)}
|
||||||
|
{/* Helper link */}
|
||||||
|
<Link href="/dashboard/clients" style={createLinkStyle} tabIndex={-1}>
|
||||||
|
<svg width="11" height="11" 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>
|
||||||
|
إنشاء عميل جديد
|
||||||
|
</Link>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{/* Recipient name — required */}
|
||||||
|
<label style={labelStyle}>
|
||||||
|
اسم المستلم *
|
||||||
|
<input
|
||||||
|
style={inputStyle("recipientName")}
|
||||||
|
value={recipientName}
|
||||||
|
onChange={(e) => {
|
||||||
|
setRecipientName(e.target.value);
|
||||||
|
clearFieldError("recipientName");
|
||||||
|
}}
|
||||||
|
placeholder="أحمد محمد"
|
||||||
|
dir="rtl"
|
||||||
|
/>
|
||||||
|
{errors.recipientName && (
|
||||||
|
<span style={errorTextStyle}>{errors.recipientName}</span>
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{/* Recipient phone — required */}
|
||||||
|
<label style={labelStyle}>
|
||||||
|
رقم جوال المستلم *
|
||||||
|
<input
|
||||||
|
style={inputStyle("recipientPhone")}
|
||||||
|
value={recipientPhone}
|
||||||
|
onChange={(e) => {
|
||||||
|
setRecipientPhone(e.target.value);
|
||||||
|
clearFieldError("recipientPhone");
|
||||||
|
}}
|
||||||
|
placeholder="05XXXXXXXX"
|
||||||
|
dir="ltr"
|
||||||
|
/>
|
||||||
|
{errors.recipientPhone && (
|
||||||
|
<span style={errorTextStyle}>{errors.recipientPhone}</span>
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{/* ── Trip dropdown — required on create, optional on edit ── */}
|
||||||
|
<label style={{ ...labelStyle, gridColumn: "1 / -1" }}>
|
||||||
|
{isNew ? "الرحلة *" : "الرحلة"}
|
||||||
|
{!isNew && <span style={optionalLabelStyle}>(اختياري)</span>}
|
||||||
|
<select
|
||||||
|
style={{
|
||||||
|
...inputStyle("tripId"),
|
||||||
|
cursor: relLoading ? "wait" : "pointer",
|
||||||
|
}}
|
||||||
|
value={tripId ?? ""}
|
||||||
|
disabled={relLoading}
|
||||||
|
onChange={(e) => {
|
||||||
|
setTripId(e.target.value);
|
||||||
|
clearFieldError("tripId");
|
||||||
|
}}
|
||||||
|
dir="rtl"
|
||||||
|
>
|
||||||
|
<option value="">
|
||||||
|
{relLoading ? "جارٍ التحميل…" : "اختر الرحلة"}
|
||||||
|
</option>
|
||||||
|
{trips.map((t) => (
|
||||||
|
<option key={t.id} value={t.id}>
|
||||||
|
{t.tripNumber}
|
||||||
|
{t.title ? ` — ${t.title}` : ""}
|
||||||
|
{t.driver?.name ? ` (${t.driver.name})` : ""}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{errors.tripId && (
|
||||||
|
<span style={errorTextStyle}>{errors.tripId}</span>
|
||||||
|
)}
|
||||||
|
{/* Helper link */}
|
||||||
|
<Link href="/dashboard/trips" style={createLinkStyle} tabIndex={-1}>
|
||||||
|
<svg width="11" height="11" 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>
|
||||||
|
إنشاء رحلة جديدة
|
||||||
|
</Link>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ── Section: Shipment details ── */}
|
||||||
|
<p style={sectionHeadingStyle}>تفاصيل الشحنة</p>
|
||||||
|
|
||||||
|
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "0.75rem" }}>
|
||||||
|
{/* Type — optional */}
|
||||||
|
<label style={labelStyle}>
|
||||||
|
نوع الشحنة
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input
|
||||||
|
style={inputBase}
|
||||||
|
value={type}
|
||||||
|
onChange={(e) => setType(e.target.value)}
|
||||||
|
placeholder="عادي / مبرد"
|
||||||
|
dir="rtl"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{/* Quantity — required, defaults to 1 */}
|
||||||
|
<label style={labelStyle}>
|
||||||
|
الكمية *
|
||||||
|
<input
|
||||||
|
style={inputStyle("quantity")}
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
value={quantity}
|
||||||
|
onChange={(e) => {
|
||||||
|
setQuantity(e.target.value);
|
||||||
|
clearFieldError("quantity");
|
||||||
|
}}
|
||||||
|
dir="ltr"
|
||||||
|
/>
|
||||||
|
{errors.quantity && (
|
||||||
|
<span style={errorTextStyle}>{errors.quantity}</span>
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{/* Weight — optional */}
|
||||||
|
<label style={labelStyle}>
|
||||||
|
الوزن (كجم)
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input
|
||||||
|
style={inputBase}
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
step="0.01"
|
||||||
|
value={weight}
|
||||||
|
onChange={(e) => setWeight(e.target.value)}
|
||||||
|
dir="ltr"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ── Section: Payment ── */}
|
||||||
|
<p style={sectionHeadingStyle}>بيانات الدفع</p>
|
||||||
|
|
||||||
|
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "0.75rem" }}>
|
||||||
|
{/* Subtotal — optional */}
|
||||||
|
<label style={labelStyle}>
|
||||||
|
الإجمالي الفرعي
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input
|
||||||
|
style={inputStyle("subTotal")}
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
step="0.01"
|
||||||
|
value={subTotal}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSubTotal(e.target.value);
|
||||||
|
clearFieldError("subTotal");
|
||||||
|
}}
|
||||||
|
dir="ltr"
|
||||||
|
/>
|
||||||
|
{errors.subTotal && (
|
||||||
|
<span style={errorTextStyle}>{errors.subTotal}</span>
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{/* VAT rate — optional */}
|
||||||
|
<label style={labelStyle}>
|
||||||
|
نسبة الضريبة (%)
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input
|
||||||
|
style={inputStyle("vatRate")}
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
step="0.01"
|
||||||
|
value={vatRate}
|
||||||
|
onChange={(e) => {
|
||||||
|
setVatRate(e.target.value);
|
||||||
|
clearFieldError("vatRate");
|
||||||
|
}}
|
||||||
|
dir="ltr"
|
||||||
|
/>
|
||||||
|
{errors.vatRate && (
|
||||||
|
<span style={errorTextStyle}>{errors.vatRate}</span>
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{/* Payment method — optional */}
|
||||||
|
<label style={labelStyle}>
|
||||||
|
طريقة الدفع
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<select
|
||||||
|
style={{ ...inputBase, cursor: "pointer" }}
|
||||||
|
value={paymentMethod}
|
||||||
|
onChange={(e) => setPaymentMethod(e.target.value as PaymentMethod | "")}
|
||||||
|
dir="rtl"
|
||||||
|
>
|
||||||
|
<option value="">اختر الطريقة</option>
|
||||||
|
<option value="Cash">نقداً</option>
|
||||||
|
<option value="Card">بطاقة</option>
|
||||||
|
<option value="Prepaid">مدفوع مسبقاً</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{/* Payment status — edit-only, mirrors Driver's status-on-edit pattern */}
|
||||||
|
{!isNew && (
|
||||||
|
<label style={labelStyle}>
|
||||||
|
حالة الدفع
|
||||||
|
<select
|
||||||
|
style={{ ...inputBase, cursor: "pointer" }}
|
||||||
|
value={paymentStatus}
|
||||||
|
onChange={(e) =>
|
||||||
|
setPaymentStatus(e.target.value as PaymentStatus | "")
|
||||||
|
}
|
||||||
|
dir="rtl"
|
||||||
|
>
|
||||||
|
<option value="">—</option>
|
||||||
|
<option value="Pending">معلَّق</option>
|
||||||
|
<option value="Paid">مدفوع</option>
|
||||||
|
<option value="Failed">فشل</option>
|
||||||
|
<option value="Refunded">مُسترجع</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ── Section: Delivery Address ── */}
|
||||||
|
<p style={sectionHeadingStyle}>عنوان التسليم</p>
|
||||||
|
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "0.75rem" }}>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
المدينة
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input style={inputBase} value={delCity} onChange={(e) => setDelCity(e.target.value)} placeholder="الرياض" dir="rtl" />
|
||||||
|
</label>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
الحي
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input style={inputBase} value={delDistrict} onChange={(e) => setDelDistrict(e.target.value)} placeholder="العليا" dir="rtl" />
|
||||||
|
</label>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
الشارع
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input style={inputBase} value={delStreet} onChange={(e) => setDelStreet(e.target.value)} placeholder="شارع الأمير محمد" dir="rtl" />
|
||||||
|
</label>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
رقم المبنى
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input style={inputBase} value={delBuildingNo} onChange={(e) => setDelBuildingNo(e.target.value)} placeholder="1234" dir="ltr" />
|
||||||
|
</label>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
رقم الوحدة
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input style={inputBase} value={delUnitNo} onChange={(e) => setDelUnitNo(e.target.value)} placeholder="56" dir="ltr" />
|
||||||
|
</label>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
الرمز البريدي
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input style={inputBase} value={delZipCode} onChange={(e) => setDelZipCode(e.target.value)} placeholder="12345" dir="ltr" />
|
||||||
|
</label>
|
||||||
|
{/* GeoJSON coordinates — required by backend */}
|
||||||
|
<label style={labelStyle}>
|
||||||
|
خط الطول (Longitude) *
|
||||||
|
<input
|
||||||
|
style={inputBase}
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
value={delLng}
|
||||||
|
onChange={(e) => setDelLng(e.target.value)}
|
||||||
|
placeholder="46.6753"
|
||||||
|
dir="ltr"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
خط العرض (Latitude) *
|
||||||
|
<input
|
||||||
|
style={inputBase}
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
value={delLat}
|
||||||
|
onChange={(e) => setDelLat(e.target.value)}
|
||||||
|
placeholder="24.7136"
|
||||||
|
dir="ltr"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ── Section: Pickup Address ── */}
|
||||||
|
<p style={sectionHeadingStyle}>عنوان الاستلام</p>
|
||||||
|
|
||||||
|
{/* Toggle: existing ID or new address */}
|
||||||
|
<div style={{ display: "flex", gap: "0.5rem", marginBottom: "0.25rem" }}>
|
||||||
|
{(["id", "new"] as const).map((m) => (
|
||||||
|
<button
|
||||||
|
key={m}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setPickupMode(m)}
|
||||||
|
style={{
|
||||||
|
height: 32, padding: "0 0.875rem",
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
border: `1px solid ${pickupMode === m ? "var(--color-brand-600)" : "var(--color-border)"}`,
|
||||||
|
background: pickupMode === m ? "var(--color-brand-50, #EFF6FF)" : "var(--color-surface)",
|
||||||
|
fontSize: 12, fontWeight: 600,
|
||||||
|
color: pickupMode === m ? "var(--color-brand-600)" : "var(--color-text-secondary)",
|
||||||
|
cursor: "pointer", fontFamily: "var(--font-sans)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{m === "id" ? "عنوان موجود (ID)" : "عنوان جديد"}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{pickupMode === "id" ? (
|
||||||
|
<label style={labelStyle}>
|
||||||
|
معرّف العنوان (MongoDB ID)
|
||||||
|
<input
|
||||||
|
style={inputBase}
|
||||||
|
value={pickupAddressId}
|
||||||
|
onChange={(e) => setPickupAddressId(e.target.value)}
|
||||||
|
placeholder="67a1b2c3d4e5f6a7b8c9d0e1"
|
||||||
|
dir="ltr"
|
||||||
|
autoComplete="off"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
) : (
|
||||||
|
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "0.75rem" }}>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
المدينة
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input style={inputBase} value={pkpCity} onChange={(e) => setPkpCity(e.target.value)} placeholder="جدة" dir="rtl" />
|
||||||
|
</label>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
الحي
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input style={inputBase} value={pkpDistrict} onChange={(e) => setPkpDistrict(e.target.value)} placeholder="الروضة" dir="rtl" />
|
||||||
|
</label>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
الشارع
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input style={inputBase} value={pkpStreet} onChange={(e) => setPkpStreet(e.target.value)} placeholder="شارع التحلية" dir="rtl" />
|
||||||
|
</label>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
رقم المبنى
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input style={inputBase} value={pkpBuildingNo} onChange={(e) => setPkpBuildingNo(e.target.value)} placeholder="4321" dir="ltr" />
|
||||||
|
</label>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
رقم الوحدة
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input style={inputBase} value={pkpUnitNo} onChange={(e) => setPkpUnitNo(e.target.value)} placeholder="12" dir="ltr" />
|
||||||
|
</label>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
الرمز البريدي
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input style={inputBase} value={pkpZipCode} onChange={(e) => setPkpZipCode(e.target.value)} placeholder="23456" dir="ltr" />
|
||||||
|
</label>
|
||||||
|
{/* GeoJSON coordinates — optional for pickup */}
|
||||||
|
<label style={labelStyle}>
|
||||||
|
خط الطول (Longitude)
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input
|
||||||
|
style={inputBase}
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
value={pkpLng}
|
||||||
|
onChange={(e) => setPkpLng(e.target.value)}
|
||||||
|
placeholder="46.6753"
|
||||||
|
dir="ltr"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label style={labelStyle}>
|
||||||
|
خط العرض (Latitude)
|
||||||
|
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||||
|
<input
|
||||||
|
style={inputBase}
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
value={pkpLat}
|
||||||
|
onChange={(e) => setPkpLat(e.target.value)}
|
||||||
|
placeholder="24.7136"
|
||||||
|
dir="ltr"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ── Actions ── */}
|
||||||
|
<div style={{
|
||||||
|
display: "flex", gap: "0.5rem",
|
||||||
|
justifyContent: "flex-end", paddingTop: "0.5rem",
|
||||||
|
}}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
disabled={saving}
|
||||||
|
style={{
|
||||||
|
height: 40, padding: "0 1.25rem",
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
border: "1px solid var(--color-border)",
|
||||||
|
background: "var(--color-surface)",
|
||||||
|
fontSize: 13, fontWeight: 600, color: "var(--color-text-secondary)",
|
||||||
|
cursor: saving ? "not-allowed" : "pointer",
|
||||||
|
fontFamily: "var(--font-sans)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
إلغاء
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={saving}
|
||||||
|
style={{
|
||||||
|
height: 40, padding: "0 1.5rem",
|
||||||
|
borderRadius: "var(--radius-md)",
|
||||||
|
border: "none",
|
||||||
|
background: saving ? "var(--color-brand-400)" : "var(--color-brand-600)",
|
||||||
|
fontSize: 13, fontWeight: 700, color: "#FFF",
|
||||||
|
cursor: saving ? "not-allowed" : "pointer",
|
||||||
|
display: "flex", alignItems: "center", gap: 8,
|
||||||
|
fontFamily: "var(--font-sans)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{saving && <Spinner size="sm" className="text-white" />}
|
||||||
|
{saving ? "جارٍ الحفظ…" : isNew ? "إنشاء الطلب" : "حفظ التغييرات"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
"use client";
|
|
||||||
import React, { type FC } from "react";
|
|
||||||
import { useClientOrders } from "@/src/hooks/useClientOrders";
|
|
||||||
import { fmtDate, fmtAmount } from "@/src/lib/formatters";
|
|
||||||
import { statusColor, statusLabel } from "@/src/lib/order-status";
|
|
||||||
import { clearSession, type ClientSession } from "@/src/lib/session";
|
|
||||||
import type { OrderStatus } from "@/src/types/order";
|
|
||||||
import { Spinner } from "../UI";
|
|
||||||
|
|
||||||
// ─── Order status tracker ─────────────────────
|
|
||||||
const STATUS_STEPS: OrderStatus[] = ["CREATED", "IN_TRANSIT", "DELIVERED"];
|
|
||||||
const STEP_LABELS = ["تم الإنشاء", "قيد التوصيل", "تم التسليم"];
|
|
||||||
|
|
||||||
const StepIcon: FC<{ step: number }> = ({ step }) => {
|
|
||||||
if (step === 0) return (
|
|
||||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
|
||||||
<rect x="9" y="3" width="6" height="4" rx="1"/>
|
|
||||||
<path d="M4 7h16v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1z"/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
if (step === 1) return (
|
|
||||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
|
||||||
<rect x="2" y="7" width="20" height="14" rx="2"/>
|
|
||||||
<path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2"/>
|
|
||||||
<line x1="12" y1="12" x2="12" y2="16"/><line x1="10" y1="14" x2="14" y2="14"/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
return (
|
|
||||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
|
||||||
<polyline points="20 6 9 17 4 12"/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const OrderTracker: FC<{ status: OrderStatus }> = ({ status }) => {
|
|
||||||
const idx = STATUS_STEPS.indexOf(status === "CANCELLED" ? "CREATED" : status);
|
|
||||||
return (
|
|
||||||
<div className="flex items-center gap-0 py-2" dir="rtl" role="list" aria-label="تقدم الطلب">
|
|
||||||
{STATUS_STEPS.map((s, i) => (
|
|
||||||
<React.Fragment key={s}>
|
|
||||||
<div className="flex flex-col items-center gap-1" role="listitem">
|
|
||||||
<div className={`w-9 h-9 rounded-full flex items-center justify-center transition-all ${
|
|
||||||
status === "CANCELLED"
|
|
||||||
? "bg-[#FEE2E2] text-red-500 border-2 border-red-200"
|
|
||||||
: i <= idx ? "bg-[#1A73E8] text-white" : "bg-white border-2 border-[#E5E7EB] text-[#D1D5DB]"
|
|
||||||
}`} aria-current={i === idx ? "step" : undefined}>
|
|
||||||
<StepIcon step={i} />
|
|
||||||
</div>
|
|
||||||
<span className={`text-[10px] font-semibold whitespace-nowrap ${
|
|
||||||
status === "CANCELLED" ? "text-red-400" : i <= idx ? "text-[#1A73E8]" : "text-[#9CA3AF]"
|
|
||||||
}`}>
|
|
||||||
{STEP_LABELS[i]}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
{i < STATUS_STEPS.length - 1 && (
|
|
||||||
<div aria-hidden="true" className={`flex-1 h-0.5 mb-4 mx-1 ${
|
|
||||||
status === "CANCELLED" ? "bg-red-200" : i < idx ? "bg-[#1A73E8]" : "bg-[#E5E7EB]"
|
|
||||||
}`} />
|
|
||||||
)}
|
|
||||||
</React.Fragment>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
// ─── DashboardStep ───────────────────────────
|
|
||||||
interface DashboardStepProps {
|
|
||||||
session: ClientSession;
|
|
||||||
}
|
|
||||||
|
|
||||||
const DashboardStep: FC<DashboardStepProps> = ({ session }) => {
|
|
||||||
const { orders, loading, error } = useClientOrders(session.id);
|
|
||||||
|
|
||||||
const activeOrder = orders.find(o => o.status === "CREATED" || o.status === "IN_TRANSIT");
|
|
||||||
const pastOrders = orders.filter(o => o !== activeOrder);
|
|
||||||
|
|
||||||
const summary = {
|
|
||||||
total: orders.length,
|
|
||||||
delivered: orders.filter(o => o.status === "DELIVERED").length,
|
|
||||||
pending: orders.filter(o => o.status === "CREATED" || o.status === "IN_TRANSIT").length,
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div dir="rtl">
|
|
||||||
{/* Header */}
|
|
||||||
<div className="mb-6 flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h2 className="text-[22px] font-bold text-[#111827] tracking-tight">لوحة الطلبات</h2>
|
|
||||||
<p className="text-[13px] text-[#6B7280] mt-0.5">
|
|
||||||
مرحبًا بعودتك، <strong className="text-[#111827]">{session.name}</strong>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-1.5 bg-[#D1FAE5] border border-[#A7F3D0] rounded-full px-3 py-1.5" role="status" aria-label="الحساب نشط">
|
|
||||||
<span aria-hidden="true" className="w-2 h-2 rounded-full bg-[#10B981] motion-safe:animate-pulse" />
|
|
||||||
<span className="text-[11px] font-bold text-[#065F46]">نشط</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Loading */}
|
|
||||||
{loading && (
|
|
||||||
<div className="flex flex-col items-center justify-center py-14 gap-3" role="status">
|
|
||||||
<Spinner />
|
|
||||||
<p className="text-[13px] text-[#6B7280]">جارٍ تحميل الطلبات…</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Error */}
|
|
||||||
{error && (
|
|
||||||
<div className="flex flex-col items-center gap-3 py-10" role="alert">
|
|
||||||
<p className="text-[13px] text-red-500">{error}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!loading && !error && (
|
|
||||||
<>
|
|
||||||
{/* Stats */}
|
|
||||||
<div className="grid grid-cols-3 gap-3 mb-6">
|
|
||||||
{[
|
|
||||||
{ label: "إجمالي الطلبات", value: summary.total, color: "text-[#111827]" },
|
|
||||||
{ label: "مُسلَّمة", value: summary.delivered, color: "text-[#34A853]" },
|
|
||||||
{ label: "قيد التنفيذ", value: summary.pending, color: "text-[#1A73E8]" },
|
|
||||||
].map(s => (
|
|
||||||
<div key={s.label} className="bg-white border border-[#E5E7EB] rounded-xl p-3.5">
|
|
||||||
<p className="text-[10px] font-bold text-[#9CA3AF] mb-1">{s.label}</p>
|
|
||||||
<p className={`text-[26px] font-bold ${s.color}`}>{s.value}</p>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Active order tracker */}
|
|
||||||
{activeOrder ? (
|
|
||||||
<div className="bg-gradient-to-bl from-[#0D47A1] to-[#1A73E8] rounded-xl p-4 mb-6">
|
|
||||||
<div className="flex items-center justify-between mb-3">
|
|
||||||
<div>
|
|
||||||
<p className="text-[11px] font-bold text-white/60 tracking-wide">الطلب الحالي</p>
|
|
||||||
<p className="text-[14px] font-bold text-white font-mono">{activeOrder.id}</p>
|
|
||||||
</div>
|
|
||||||
<span className={`text-[11px] font-bold border px-2.5 py-1 rounded-full ${
|
|
||||||
activeOrder.status === "CREATED"
|
|
||||||
? "bg-white/15 border-white/30 text-white"
|
|
||||||
: "bg-[#D1FAE5] border-[#A7F3D0] text-[#065F46]"
|
|
||||||
}`}>
|
|
||||||
{statusLabel(activeOrder.status)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<OrderTracker status={activeOrder.status} />
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="border border-dashed border-[#E5E7EB] rounded-xl p-5 mb-6 text-center">
|
|
||||||
<p className="text-[13px] text-[#9CA3AF]">لا يوجد طلب نشط حاليًا.</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Past orders table */}
|
|
||||||
{pastOrders.length > 0 && (
|
|
||||||
<div className="bg-white border border-[#E5E7EB] rounded-xl overflow-hidden">
|
|
||||||
<div className="px-4 py-3 border-b border-[#E5E7EB] flex items-center justify-between">
|
|
||||||
<p className="text-[13px] font-bold text-[#111827]">سجل الطلبات</p>
|
|
||||||
<span className="text-[11px] text-[#9CA3AF] font-medium">{pastOrders.length} طلبات</span>
|
|
||||||
</div>
|
|
||||||
<div className="overflow-x-auto">
|
|
||||||
<table className="w-full" dir="rtl">
|
|
||||||
<thead>
|
|
||||||
<tr className="bg-[#F9FAFB]">
|
|
||||||
{["رقم الطلب", "التاريخ", "الوصف", "الحالة", "المبلغ"].map(h => (
|
|
||||||
<th key={h} scope="col" className="px-4 py-2.5 text-right text-[10px] font-bold text-[#9CA3AF] uppercase tracking-wide">
|
|
||||||
{h}
|
|
||||||
</th>
|
|
||||||
))}
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{pastOrders.map((order, i) => (
|
|
||||||
<tr key={order.id} className={`border-t border-[#F3F4F6] hover:bg-[#FAFAFA] transition-colors ${i % 2 === 0 ? "" : "bg-[#FAFAFA]/30"}`}>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<span className="font-mono text-[12px] font-semibold text-[#1A73E8]">{order.id}</span>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-[12px] text-[#6B7280] whitespace-nowrap">{fmtDate(order.createdAt)}</td>
|
|
||||||
<td className="px-4 py-3 text-[12px] text-[#374151]">{order.description}</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<span className={`inline-flex items-center gap-1.5 text-[11px] font-bold border px-2.5 py-0.5 rounded-full whitespace-nowrap ${statusColor(order.status)}`}>
|
|
||||||
<span aria-hidden="true" className="w-1.5 h-1.5 rounded-full bg-current" />
|
|
||||||
{statusLabel(order.status)}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-[12px] font-semibold text-[#111827] font-mono whitespace-nowrap">
|
|
||||||
{fmtAmount(order.totalAmount)}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => { clearSession(); window.location.reload(); }}
|
|
||||||
className="mt-4 text-[11px] text-[#9CA3AF] hover:text-red-400 underline transition-colors"
|
|
||||||
>
|
|
||||||
مسح الجلسة وإعادة البدء
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default DashboardStep;
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useEffect, useReducer } from "react";
|
import { useCallback, useEffect, useReducer, useState } from "react";
|
||||||
import { orderService } from "@/src/services/order.service";
|
import { orderService } from "@/src/services/order.service";
|
||||||
import type {
|
import type {
|
||||||
Order,
|
Order,
|
||||||
@@ -8,174 +8,194 @@ import type {
|
|||||||
UpdateOrderPayload,
|
UpdateOrderPayload,
|
||||||
UpdateOrderStatusPayload,
|
UpdateOrderStatusPayload,
|
||||||
} from "@/src/types/order";
|
} from "@/src/types/order";
|
||||||
|
import type { ToastNotification } from "@/src/Components/UI";
|
||||||
|
|
||||||
// ── State ─────────────────────────────────────────────────
|
export type OrderNotification = ToastNotification;
|
||||||
interface State {
|
|
||||||
|
// ── Table state / reducer ──────────────────────────────────────────────────
|
||||||
|
// Mirrors useDriver.ts's TableState/TableAction shape so the two resource
|
||||||
|
// hooks stay readable side by side.
|
||||||
|
interface TableState {
|
||||||
orders: Order[];
|
orders: Order[];
|
||||||
total: number;
|
|
||||||
page: number;
|
|
||||||
totalPages: number;
|
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
submitting: boolean;
|
total: number;
|
||||||
|
pages: number;
|
||||||
error: string | null;
|
error: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
type Action =
|
type TableAction =
|
||||||
| { type: "FETCH_START" }
|
| { type: "LOAD_START" }
|
||||||
| { type: "FETCH_SUCCESS"; payload: { orders: Order[]; total: number; totalPages: number; page: number } }
|
| { type: "LOAD_OK"; orders: Order[]; total: number; pages: number }
|
||||||
| { type: "FETCH_ERROR"; error: string }
|
| { type: "LOAD_ERR"; error: string }
|
||||||
| { type: "SUBMIT_START" }
|
| { type: "DELETE"; id: string }
|
||||||
| { type: "SUBMIT_SUCCESS"; order: Order; isNew: boolean }
|
| { type: "UPDATE"; order: Order }
|
||||||
| { type: "SUBMIT_ERROR"; error: string }
|
| { type: "CLEAR_ERR" };
|
||||||
| { type: "DELETE_SUCCESS"; id: string }
|
|
||||||
| { type: "CLEAR_ERROR" };
|
|
||||||
|
|
||||||
const initialState: State = {
|
function reducer(s: TableState, a: TableAction): TableState {
|
||||||
orders: [],
|
switch (a.type) {
|
||||||
total: 0,
|
case "LOAD_START":
|
||||||
page: 1,
|
return { ...s, loading: true, error: null };
|
||||||
totalPages: 1,
|
case "LOAD_OK":
|
||||||
loading: false,
|
return { ...s, loading: false, orders: a.orders, total: a.total, pages: a.pages };
|
||||||
submitting: false,
|
case "LOAD_ERR":
|
||||||
error: null,
|
return { ...s, loading: false, error: a.error };
|
||||||
};
|
case "DELETE":
|
||||||
|
return { ...s, orders: s.orders.filter((o) => o.id !== a.id) };
|
||||||
function reducer(state: State, action: Action): State {
|
// Instantly reflect the updated order in the list without a full reload
|
||||||
switch (action.type) {
|
case "UPDATE":
|
||||||
case "FETCH_START":
|
return { ...s, orders: s.orders.map((o) => (o.id === a.order.id ? a.order : o)) };
|
||||||
return { ...state, loading: true, error: null };
|
case "CLEAR_ERR":
|
||||||
case "FETCH_SUCCESS":
|
return { ...s, error: null };
|
||||||
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:
|
default:
|
||||||
return state;
|
return s;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Hook ──────────────────────────────────────────────────
|
const initialState: TableState = {
|
||||||
export function useOrders(autoFetch = true) {
|
orders: [],
|
||||||
|
loading: true,
|
||||||
|
total: 0,
|
||||||
|
pages: 1,
|
||||||
|
error: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Main hook ──────────────────────────────────────────────────────────────
|
||||||
|
export function useOrders() {
|
||||||
const [state, dispatch] = useReducer(reducer, initialState);
|
const [state, dispatch] = useReducer(reducer, initialState);
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [statusFilter, setStatusFilter] = useState("");
|
||||||
|
const [notification, setNotification] = useState<ToastNotification | null>(null);
|
||||||
|
|
||||||
const fetchOrders = useCallback(
|
// Show a toast for 4 seconds then auto-dismiss — same timing as useDriver.ts
|
||||||
async (page = 1, limit = 20) => {
|
const notify = useCallback((n: ToastNotification) => {
|
||||||
dispatch({ type: "FETCH_START" });
|
setNotification(n);
|
||||||
try {
|
setTimeout(() => setNotification(null), 4000);
|
||||||
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(
|
// ── Fetch orders ───────────────────────────────────────────────────────
|
||||||
async (id: string, payload: UpdateOrderPayload) => {
|
const loadOrders = useCallback(async (p: number, q: string, status: string) => {
|
||||||
dispatch({ type: "SUBMIT_START" });
|
dispatch({ type: "LOAD_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 {
|
try {
|
||||||
await orderService.delete(id);
|
const res = await orderService.getAll({
|
||||||
dispatch({ type: "DELETE_SUCCESS", id });
|
page: p,
|
||||||
} catch (err: unknown) {
|
limit: 12,
|
||||||
dispatch({
|
...(q ? { search: q } : {}),
|
||||||
type: "FETCH_ERROR",
|
...(status ? { currentStatus: status } : {}),
|
||||||
error: err instanceof Error ? err.message : "Failed to delete order",
|
|
||||||
});
|
});
|
||||||
|
const payload = (res as unknown as { data: { data: Order[]; meta: { total: number; totalPages: number } } }).data ?? res;
|
||||||
|
|
||||||
|
dispatch({
|
||||||
|
type: "LOAD_OK",
|
||||||
|
orders: payload.data ?? [],
|
||||||
|
total: payload.meta?.total ?? 0,
|
||||||
|
pages: payload.meta?.totalPages ?? 1,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
dispatch({ type: "LOAD_ERR", error: "تعذّر تحميل بيانات الطلبات. يرجى المحاولة مجدداً." });
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (autoFetch) fetchOrders();
|
loadOrders(page, search, statusFilter);
|
||||||
}, [autoFetch, fetchOrders]);
|
}, [page, search, statusFilter, loadOrders]);
|
||||||
|
|
||||||
|
// ── Create ──────────────────────────────────────────────────────────────
|
||||||
|
const createOrder = useCallback(
|
||||||
|
async (payload: CreateOrderPayload): Promise<boolean> => {
|
||||||
|
try {
|
||||||
|
await orderService.create(payload);
|
||||||
|
notify({ type: "success", message: "تم إنشاء الطلب بنجاح." });
|
||||||
|
await loadOrders(page, search, statusFilter);
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
// نعرض رسالة الخطأ كـ toast برضو، مش بس نرميها لفوق
|
||||||
|
const message = err instanceof Error ? err.message : "تعذّر إنشاء الطلب. يرجى المحاولة لاحقاً.";
|
||||||
|
notify({ type: "error", message });
|
||||||
|
throw err; // يفضل يترمي عشان OrderFormModal يعرضه جوه المودال كمان لو محتاج
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[notify, loadOrders, page, search, statusFilter],
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Update ──────────────────────────────────────────────────────────────
|
||||||
|
const updateOrder = useCallback(
|
||||||
|
async (id: string, payload: UpdateOrderPayload): Promise<boolean> => {
|
||||||
|
try {
|
||||||
|
const res = await orderService.update(id, payload);
|
||||||
|
const updated = (res as unknown as { data: Order }).data ?? (res as unknown as Order);
|
||||||
|
dispatch({ type: "UPDATE", order: updated });
|
||||||
|
notify({ type: "success", message: "تم تحديث الطلب بنجاح." });
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : "تعذّر تحديث الطلب. يرجى المحاولة لاحقاً.";
|
||||||
|
notify({ type: "error", message });
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[notify],
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Update status (separate endpoint — orders/:id/status) ─────────────
|
||||||
|
const updateStatus = useCallback(
|
||||||
|
async (id: string, payload: UpdateOrderStatusPayload): Promise<boolean> => {
|
||||||
|
try {
|
||||||
|
const res = await orderService.updateStatus(id, payload);
|
||||||
|
const updated = (res as unknown as { data: Order }).data ?? (res as unknown as Order);
|
||||||
|
dispatch({ type: "UPDATE", order: updated });
|
||||||
|
notify({ type: "success", message: "تم تحديث حالة الطلب بنجاح." });
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : "تعذّر تحديث حالة الطلب.";
|
||||||
|
notify({ type: "error", message });
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[notify],
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Delete ──────────────────────────────────────────────────────────────
|
||||||
|
const deleteOrder = useCallback(
|
||||||
|
async (id: string): Promise<boolean> => {
|
||||||
|
try {
|
||||||
|
await orderService.delete(id);
|
||||||
|
dispatch({ type: "DELETE", id });
|
||||||
|
notify({ type: "success", message: "تم حذف الطلب بنجاح." });
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : "تعذّر حذف الطلب.";
|
||||||
|
notify({ type: "error", message });
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[notify],
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Search / filter helpers ────────────────────────────────────────────
|
||||||
|
const handleSearch = useCallback((q: string) => {
|
||||||
|
setSearch(q);
|
||||||
|
setPage(1);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleStatusFilter = useCallback((status: string) => {
|
||||||
|
setStatusFilter(status);
|
||||||
|
setPage(1);
|
||||||
|
}, []);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
fetchOrders,
|
page,
|
||||||
|
search,
|
||||||
|
statusFilter,
|
||||||
|
setPage,
|
||||||
|
handleSearch,
|
||||||
|
handleStatusFilter,
|
||||||
|
clearError: () => dispatch({ type: "CLEAR_ERR" }),
|
||||||
createOrder,
|
createOrder,
|
||||||
updateOrder,
|
updateOrder,
|
||||||
updateStatus,
|
updateStatus,
|
||||||
deleteOrder,
|
deleteOrder,
|
||||||
clearError: () => dispatch({ type: "CLEAR_ERROR" }),
|
notification,
|
||||||
|
reload: () => loadOrders(page, search, statusFilter),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
// services/order.service.ts
|
// services/order.service.ts
|
||||||
import { get, post, put, del } from "./api";
|
import { get, post, put, del, patch } from "./api";
|
||||||
import type {
|
import type {
|
||||||
Order,
|
Order,
|
||||||
CreateOrderPayload,
|
CreateOrderPayload,
|
||||||
@@ -27,11 +27,11 @@ export const orderService = {
|
|||||||
|
|
||||||
/** Update order metadata */
|
/** Update order metadata */
|
||||||
update: (id: string, payload: UpdateOrderPayload) =>
|
update: (id: string, payload: UpdateOrderPayload) =>
|
||||||
put<Order>(`orders/${id}`, payload),
|
patch<Order>(`orders/${id}`, payload),
|
||||||
|
|
||||||
/** Update order status with optional reason */
|
/** Update order status with optional reason */
|
||||||
updateStatus: (id: string, payload: UpdateOrderStatusPayload) =>
|
updateStatus: (id: string, payload: UpdateOrderStatusPayload) =>
|
||||||
put<Order>(`orders/${id}/status`, payload),
|
patch<Order>(`orders/${id}/status`, payload),
|
||||||
|
|
||||||
/** Transfer order to a different trip */
|
/** Transfer order to a different trip */
|
||||||
transfer: (id: string, payload: TransferOrderPayload) =>
|
transfer: (id: string, payload: TransferOrderPayload) =>
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ export type PaymentStatus = "Pending" | "Paid" | "Failed" | "Refunded";
|
|||||||
export interface OrderAddress {
|
export interface OrderAddress {
|
||||||
details?: {
|
details?: {
|
||||||
city?: string;
|
city?: string;
|
||||||
|
state?: string;
|
||||||
district?: string;
|
district?: string;
|
||||||
street?: string;
|
street?: string;
|
||||||
buildingNo?: string;
|
buildingNo?: string;
|
||||||
@@ -19,7 +20,7 @@ export interface OrderAddress {
|
|||||||
zipCode?: string;
|
zipCode?: string;
|
||||||
};
|
};
|
||||||
location?: {
|
location?: {
|
||||||
coordinates?: [number, number];
|
coordinates?: [number, number]; // [longitude, latitude]
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,8 +41,12 @@ export interface Order {
|
|||||||
type?: string | null;
|
type?: string | null;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
weight?: number | null;
|
weight?: number | null;
|
||||||
|
// Hybrid address IDs (stored in PostgreSQL, resolve to MongoDB docs)
|
||||||
deliveryAddressId?: string | null;
|
deliveryAddressId?: string | null;
|
||||||
pickupAddressId?: string | null;
|
pickupAddressId?: string | null;
|
||||||
|
// Populated address objects returned by the API (from MongoDB)
|
||||||
|
deliveryAddress?: OrderAddress | null;
|
||||||
|
pickupAddress?: OrderAddress | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
statusHistory?: Array<{
|
statusHistory?: Array<{
|
||||||
@@ -69,8 +74,11 @@ export interface CreateOrderPayload {
|
|||||||
type?: string;
|
type?: string;
|
||||||
quantity?: number;
|
quantity?: number;
|
||||||
weight?: number;
|
weight?: number;
|
||||||
|
// Delivery address: send a NEW address object (backend writes to MongoDB)
|
||||||
deliveryAddress?: OrderAddress;
|
deliveryAddress?: OrderAddress;
|
||||||
|
// Pickup: send an existing MongoDB ID OR a new address object
|
||||||
pickupAddressId?: string;
|
pickupAddressId?: string;
|
||||||
|
pickupAddress?: OrderAddress;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateOrderPayload extends Partial<CreateOrderPayload> {
|
export interface UpdateOrderPayload extends Partial<CreateOrderPayload> {
|
||||||
|
|||||||
19
src/utils/brandIcon.tsx
Normal file
19
src/utils/brandIcon.tsx
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
function BrandIcon({ size = 32, bg = "rgba(255,255,255,0.15)" }: { size?: number; bg?: string }) {
|
||||||
|
return (
|
||||||
|
<div style={{
|
||||||
|
width: size, height: size, background: bg, borderRadius: 8,
|
||||||
|
display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
|
||||||
|
}}>
|
||||||
|
<svg width={size * 0.56} height={size * 0.56} viewBox="0 0 24 24" fill="none"
|
||||||
|
stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||||
|
<path d="M5 17H3a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11a2 2 0 0 1 2 2v3"/>
|
||||||
|
<rect x="9" y="11" width="14" height="10" rx="2"/>
|
||||||
|
<circle cx="12" cy="21" r="1"/>
|
||||||
|
<circle cx="20" cy="21" r="1"/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export default BrandIcon
|
||||||
167
src/validations/order.validation.ts
Normal file
167
src/validations/order.validation.ts
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
import * as yup from "yup";
|
||||||
|
|
||||||
|
// ── Saudi mobile regex (05xxxxxxxx) ─────────────────────────────────────────
|
||||||
|
const SAUDI_PHONE_RE = /^(05\d{8}|009665\d{8}|\+9665\d{8})$/;
|
||||||
|
|
||||||
|
// ── Address sub-schemas (mirrors backend orderAddressSchema) ─────────────────
|
||||||
|
|
||||||
|
// Delivery address — location.coordinates required by the backend (MongoDB GeoJSON)
|
||||||
|
const deliveryAddressSchema = yup.object({
|
||||||
|
details: yup.object({
|
||||||
|
city: yup.string().trim().optional(),
|
||||||
|
state: yup.string().trim().optional(),
|
||||||
|
district: yup.string().trim().optional(),
|
||||||
|
street: yup.string().trim().optional(),
|
||||||
|
buildingNo: yup.string().trim().optional(),
|
||||||
|
unitNo: yup.string().trim().optional(),
|
||||||
|
zipCode: yup.string().trim().optional(),
|
||||||
|
}).optional(),
|
||||||
|
location: yup.object({
|
||||||
|
coordinates: yup
|
||||||
|
.array()
|
||||||
|
.of(yup.number().required())
|
||||||
|
.length(2, "الإحداثيات يجب أن تكون [خط الطول, خط العرض]")
|
||||||
|
.required("إحداثيات موقع التسليم مطلوبة"),
|
||||||
|
}).required("موقع التسليم مطلوب"),
|
||||||
|
}).optional();
|
||||||
|
|
||||||
|
// Pickup address — coordinates optional (user may supply an existing ID instead)
|
||||||
|
const pickupAddressSchema = yup.object({
|
||||||
|
details: yup.object({
|
||||||
|
city: yup.string().trim().optional(),
|
||||||
|
state: yup.string().trim().optional(),
|
||||||
|
district: yup.string().trim().optional(),
|
||||||
|
street: yup.string().trim().optional(),
|
||||||
|
buildingNo: yup.string().trim().optional(),
|
||||||
|
unitNo: yup.string().trim().optional(),
|
||||||
|
zipCode: yup.string().trim().optional(),
|
||||||
|
}).optional(),
|
||||||
|
location: yup.object({
|
||||||
|
coordinates: yup
|
||||||
|
.array()
|
||||||
|
.of(yup.number().required())
|
||||||
|
.length(2, "الإحداثيات يجب أن تكون [خط الطول, خط العرض]")
|
||||||
|
.optional(),
|
||||||
|
}).optional(),
|
||||||
|
}).optional();
|
||||||
|
|
||||||
|
// ── Base shape shared between create & update ────────────────────────────────
|
||||||
|
// Optional financial / shipment detail fields live here so both schemas
|
||||||
|
// inherit them without repetition.
|
||||||
|
const baseShape = {
|
||||||
|
// ── Optional: shipment details ──
|
||||||
|
type: yup.string().nullable().optional(),
|
||||||
|
quantity: yup
|
||||||
|
.number()
|
||||||
|
.typeError("الكمية يجب أن تكون رقمًا")
|
||||||
|
.min(1, "الكمية يجب أن تكون ١ أو أكثر")
|
||||||
|
.optional(),
|
||||||
|
weight: yup
|
||||||
|
.number()
|
||||||
|
.typeError("الوزن يجب أن يكون رقمًا")
|
||||||
|
.min(0, "الوزن لا يمكن أن يكون سالبًا")
|
||||||
|
.nullable()
|
||||||
|
.optional(),
|
||||||
|
|
||||||
|
// ── Optional: financial ──
|
||||||
|
subTotal: yup
|
||||||
|
.number()
|
||||||
|
.typeError("الإجمالي الفرعي يجب أن يكون رقمًا")
|
||||||
|
.min(0, "القيمة لا يمكن أن تكون سالبة")
|
||||||
|
.nullable()
|
||||||
|
.optional(),
|
||||||
|
vatRate: yup
|
||||||
|
.number()
|
||||||
|
.typeError("نسبة الضريبة يجب أن تكون رقمًا")
|
||||||
|
.min(0, "النسبة لا يمكن أن تكون سالبة")
|
||||||
|
.max(100, "النسبة لا يمكن أن تتجاوز ١٠٠%")
|
||||||
|
.nullable()
|
||||||
|
.optional(),
|
||||||
|
paymentMethod: yup
|
||||||
|
.mixed<"Cash" | "Card" | "Prepaid">()
|
||||||
|
.oneOf(["Cash", "Card", "Prepaid"], "طريقة الدفع غير صالحة")
|
||||||
|
.nullable()
|
||||||
|
.optional(),
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Create schema ─────────────────────────────────────────────────────────────
|
||||||
|
// The five fields mandated by the task spec are required here.
|
||||||
|
// deliveryAddressId / pickupAddressId intentionally excluded — the backend
|
||||||
|
// generates address records from deliveryAddressData / pickupAddressData.
|
||||||
|
|
||||||
|
export const createOrderSchema = yup.object({
|
||||||
|
// ── Required ──
|
||||||
|
tripId: yup
|
||||||
|
.string()
|
||||||
|
.required("الرحلة مطلوبة")
|
||||||
|
.min(1, "الرحلة مطلوبة"),
|
||||||
|
|
||||||
|
clientId: yup
|
||||||
|
.string()
|
||||||
|
.required("العميل مطلوب")
|
||||||
|
.min(1, "العميل مطلوب"),
|
||||||
|
|
||||||
|
shipmentNumber: yup
|
||||||
|
.string()
|
||||||
|
.required("رقم الشحنة مطلوب")
|
||||||
|
.min(2, "رقم الشحنة قصير جدًا"),
|
||||||
|
|
||||||
|
recipientName: yup
|
||||||
|
.string()
|
||||||
|
.required("اسم المستلم مطلوب")
|
||||||
|
.min(2, "اسم المستلم قصير جدًا"),
|
||||||
|
|
||||||
|
recipientPhone: yup
|
||||||
|
.string()
|
||||||
|
.required("رقم جوال المستلم مطلوب")
|
||||||
|
.matches(SAUDI_PHONE_RE, "أدخل رقم جوال سعودي صحيح (05xxxxxxxx)"),
|
||||||
|
|
||||||
|
// ── Optional: addresses ──
|
||||||
|
// deliveryAddress: always a new object (backend creates in MongoDB); coordinates required
|
||||||
|
deliveryAddress: deliveryAddressSchema,
|
||||||
|
// pickupAddress: new object OR existing ID — both optional; coordinates optional
|
||||||
|
pickupAddress: pickupAddressSchema,
|
||||||
|
pickupAddressId: yup.string().optional(),
|
||||||
|
|
||||||
|
// ── Optional inherited ──
|
||||||
|
...baseShape,
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Update schema ─────────────────────────────────────────────────────────────
|
||||||
|
// All fields are optional on update — the backend applies partial patches.
|
||||||
|
export const updateOrderSchema = yup.object({
|
||||||
|
tripId: yup.string().nullable().optional(),
|
||||||
|
clientId: yup.string().nullable().optional(),
|
||||||
|
shipmentNumber: yup.string().min(2, "رقم الشحنة قصير جدًا").optional(),
|
||||||
|
recipientName: yup.string().min(2, "اسم المستلم قصير جدًا").optional(),
|
||||||
|
recipientPhone: yup
|
||||||
|
.string()
|
||||||
|
.matches(SAUDI_PHONE_RE, "أدخل رقم جوال سعودي صحيح (05xxxxxxxx)")
|
||||||
|
.optional(),
|
||||||
|
|
||||||
|
paymentStatus: yup
|
||||||
|
.mixed<"Pending" | "Paid" | "Failed" | "Refunded">()
|
||||||
|
.oneOf(["Pending", "Paid", "Failed", "Refunded"], "حالة الدفع غير صالحة")
|
||||||
|
.nullable()
|
||||||
|
.optional(),
|
||||||
|
|
||||||
|
// ── Optional: addresses (delivery keeps coordinates required; pickup stays optional) ──
|
||||||
|
deliveryAddress: deliveryAddressSchema,
|
||||||
|
pickupAddress: pickupAddressSchema,
|
||||||
|
pickupAddressId: yup.string().optional(),
|
||||||
|
|
||||||
|
// ── Optional inherited ──
|
||||||
|
...baseShape,
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── SchemaErrors — typed error bag consumed by OrderFormModal ─────────────────
|
||||||
|
export type CreateOrderSchemaErrors = Partial<
|
||||||
|
Record<keyof yup.InferType<typeof createOrderSchema>, string>
|
||||||
|
>;
|
||||||
|
|
||||||
|
export type UpdateOrderSchemaErrors = Partial<
|
||||||
|
Record<keyof yup.InferType<typeof updateOrderSchema>, string>
|
||||||
|
>;
|
||||||
|
|
||||||
|
// Union used inside the modal so one type covers both modes
|
||||||
|
export type OrderSchemaErrors = CreateOrderSchemaErrors & UpdateOrderSchemaErrors;
|
||||||
Reference in New Issue
Block a user