make header one in all page

This commit is contained in:
m7amedez5511
2026-07-19 16:20:11 +03:00
parent 538111d726
commit d23866d7fc
14 changed files with 1479 additions and 2484 deletions

View File

@@ -1,14 +1,14 @@
"use client";
import { useEffect, useRef, useState } from "react";
import * as yup from "yup";
import { Spinner } from "../UI";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { Alert, Spinner } from "../UI";
import { getStoredToken } from "@/src/lib/auth";
import {
createTripSchema,
updateTripSchema,
} from "@/src/validations/trip.validator";
import type { TripSchemaErrors } from "@/src/validations/trip.validator";
import type {
Trip,
TripStatus,
@@ -21,7 +21,6 @@ import type { DriverOption } from "@/src/types/driver";
import type { CarOption } from "@/src/types/car";
import type { BranchOption } from "@/src/types/branch";
// ── Shared styles ────────────────────────────────────────────────────────────
const inputBase: React.CSSProperties = {
@@ -68,9 +67,28 @@ const optionalLabelStyle: React.CSSProperties = {
marginRight: 4,
};
// ── Form values shape ────────────────────────────────────────────────────────
// startTime/endTime store the ISO-8601 string (via setValueAs on register),
// while the <input type="datetime-local"> DOM element itself keeps showing
// the raw "YYYY-MM-DDTHH:mm" value the user typed — the transform only
// affects what's handed to the yup resolver and to onSubmit.
interface TripFormValues {
title: string;
driverId: string;
carId: string;
branchId: string;
status: TripStatus;
startTime: string;
endTime: string;
collectedCount: number | undefined;
deliveredCount: number | undefined;
returnedCount: number | undefined;
totalCashCollected: number | undefined;
notes: string;
endReason: string;
reason: string; // update-only
}
// ── Props ────────────────────────────────────────────────────────────────────
@@ -97,45 +115,41 @@ export function TripFormModal({
const [cars, setCars] = useState<CarOption[]>([]);
const [branches, setBranches] = useState<BranchOption[]>([]);
useEffect(() => {
const token = getStoredToken();
driverService.getActiveOptions(token).then(setDrivers).catch(() => {});
carService.getActiveOptions(token).then(setCars).catch(() => {});
branchService.getOptions(token).then(setBranches).catch(() => {});
}, []);
//console.log("cars", cars);
// ── Form state ────────────────────────────────────────────────────────────
const [title, setTitle] = useState(editTrip?.title ?? "");
const [driverId, setDriverId] = useState(editTrip?.driverId ?? "");
const [carId, setCarId] = useState(editTrip?.carId ?? "");
const [branchId, setBranchId] = useState(editTrip?.branchId ?? "");
const [status, setStatus] = useState<TripStatus>(
editTrip?.status ?? "Scheduled",
);
const [startTime, setStartTime] = useState(
editTrip?.startTime?.slice(0, 16) ?? "",
);
const [endTime, setEndTime] = useState(editTrip?.endTime?.slice(0, 16) ?? "");
const [collectedCount, setCollectedCount] = useState<string>(
editTrip?.collectedCount != null ? String(editTrip.collectedCount) : "",
);
const [deliveredCount, setDeliveredCount] = useState<string>(
editTrip?.deliveredCount != null ? String(editTrip.deliveredCount) : "",
);
const [returnedCount, setReturnedCount] = useState<string>(
editTrip?.returnedCount != null ? String(editTrip.returnedCount) : "",
);
const [totalCashCollected, setTotalCashCollected] = useState<string>(
editTrip?.totalCashCollected != null
? String(editTrip.totalCashCollected)
: "",
);
const [notes, setNotes] = useState(editTrip?.notes ?? "");
const [endReason, setEndReason] = useState(editTrip?.endReason ?? "");
const [reason, setReason] = useState(""); // update-only
useEffect(() => {
const token = getStoredToken();
driverService.getActiveOptions(token).then(setDrivers).catch(() => {});
carService.getActiveOptions(token).then(setCars).catch(() => {});
branchService.getOptions(token).then(setBranches).catch(() => {});
}, []);
const [errors, setErrors] = useState<TripSchemaErrors>({});
const [saving, setSaving] = useState(false);
// ── react-hook-form ────────────────────────────────────────────────────────
const {
register,
handleSubmit,
setError,
formState: { errors, isSubmitting },
} = useForm<TripFormValues>({
resolver: yupResolver(isNew ? createTripSchema : updateTripSchema) as never,
defaultValues: {
title: editTrip?.title ?? "",
driverId: editTrip?.driverId ?? "",
carId: editTrip?.carId ?? "",
branchId: editTrip?.branchId ?? "",
status: editTrip?.status ?? "Scheduled",
startTime: editTrip?.startTime?.slice(0, 16) ?? "",
endTime: editTrip?.endTime?.slice(0, 16) ?? "",
collectedCount: editTrip?.collectedCount ?? undefined,
deliveredCount: editTrip?.deliveredCount ?? undefined,
returnedCount: editTrip?.returnedCount ?? undefined,
totalCashCollected:
editTrip?.totalCashCollected != null ? Number(editTrip.totalCashCollected) : undefined,
notes: editTrip?.notes ?? "",
endReason: editTrip?.endReason ?? "",
reason: "",
},
});
const [apiError, setApiError] = useState("");
const firstRef = useRef<HTMLInputElement>(null);
useEffect(() => {
@@ -149,67 +163,58 @@ export function TripFormModal({
return () => window.removeEventListener("keydown", h);
}, [onClose]);
// ── Error style helper ────────────────────────────────────────────────────
const inputStyle = (field: keyof TripSchemaErrors): React.CSSProperties => ({
const withError = (hasError: boolean): React.CSSProperties => ({
...inputBase,
...(errors[field]
? { borderColor: "var(--color-danger)", background: "#FEF2F2" }
: {}),
...(hasError ? { borderColor: "var(--color-danger)", background: "#FEF2F2" } : {}),
});
const clearErr = (field: keyof TripSchemaErrors) =>
setErrors((p) => ({ ...p, [field]: undefined }));
const numberField = (
field: "collectedCount" | "deliveredCount" | "returnedCount" | "totalCashCollected",
) =>
register(field, {
setValueAs: (v) => (v === "" || v === null ? undefined : Number(v)),
});
// datetime-local -> ISO-8601, applied at the RHF-value level only (DOM input
// keeps showing the raw datetime-local string the user picked).
const dateTimeField = (field: "startTime" | "endTime") =>
register(field, {
setValueAs: (v) => (v ? `${v}:00.000Z` : ""),
});
// ── Submit ────────────────────────────────────────────────────────────────
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const submitHandler = async (data: TripFormValues) => {
const raw: Record<string, unknown> = {
title: title || undefined,
driverId: driverId || undefined,
carId: carId || undefined,
branchId: branchId || undefined,
status: status || undefined,
startTime: startTime ? `${startTime}:00.000Z` : undefined,
endTime: endTime ? `${endTime}:00.000Z` : undefined,
collectedCount:
collectedCount !== "" ? Number(collectedCount) : undefined,
deliveredCount:
deliveredCount !== "" ? Number(deliveredCount) : undefined,
returnedCount: returnedCount !== "" ? Number(returnedCount) : undefined,
totalCashCollected:
totalCashCollected !== "" ? Number(totalCashCollected) : undefined,
notes: notes || undefined,
endReason: endReason || undefined,
...(!isNew && reason ? { reason } : {}),
title: data.title || undefined,
driverId: data.driverId || undefined,
carId: data.carId || undefined,
branchId: data.branchId || undefined,
status: data.status || undefined,
startTime: data.startTime || undefined,
endTime: data.endTime || undefined,
collectedCount: data.collectedCount,
deliveredCount: data.deliveredCount,
returnedCount: data.returnedCount,
totalCashCollected: data.totalCashCollected,
notes: data.notes || undefined,
endReason: data.endReason || undefined,
...(!isNew && data.reason ? { reason: data.reason } : {}),
};
// ── Client-side validation ────────────────────────────────────────────
setApiError("");
try {
const schema = isNew ? createTripSchema : updateTripSchema;
await schema.validate(raw, { abortEarly: false });
} catch (err) {
if (err instanceof yup.ValidationError) {
const map: TripSchemaErrors = {};
err.inner.forEach((e) => {
if (e.path) (map as Record<string, string>)[e.path] = e.message;
});
setErrors(map);
const ok = await onSubmit(raw as CreateTripPayload | UpdateTripPayload, isNew);
if (ok) {
onClose();
} else {
setError("title", { message: "حدث خطأ غير متوقع. يرجى المحاولة لاحقاً." });
setApiError("حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.");
}
return;
}
// ── Call parent handler (notification emitted by the hook) ────────────
setSaving(true);
try {
const ok = await onSubmit(
raw as CreateTripPayload | UpdateTripPayload,
isNew,
);
if (ok) onClose();
// on failure the hook already fired an error notification — nothing extra needed here
} finally {
setSaving(false);
} catch (err) {
const message = err instanceof Error ? err.message : "حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.";
setError("title", { message });
setApiError(message);
}
};
@@ -279,14 +284,7 @@ export function TripFormModal({
padding: 4,
}}
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.5"
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
@@ -295,7 +293,7 @@ export function TripFormModal({
{/* Form */}
<form
onSubmit={handleSubmit}
onSubmit={handleSubmit(submitHandler)}
noValidate
style={{
padding: "1.5rem",
@@ -304,6 +302,10 @@ export function TripFormModal({
gap: "1rem",
}}
>
{errors.title?.type === "manual" && (
<Alert type="error" message={errors.title.message ?? ""} onClose={() => setApiError("")} />
)}
{/* ── Section:trip management── */}
<p style={sectionHeadingStyle}>أساسيات الرحلة</p>
@@ -312,37 +314,21 @@ export function TripFormModal({
عنوان الرحلة <span style={{ color: "var(--color-danger)" }}>*</span>
<input
ref={firstRef}
style={inputStyle("title")}
value={title}
onChange={(e) => {
setTitle(e.target.value);
clearErr("title");
}}
style={withError(!!errors.title && errors.title.type !== "manual")}
{...register("title")}
placeholder="مثال: توزيع الرياض الشمالي"
dir="rtl"
/>
{errors.title && <span style={errorTextStyle}>{errors.title}</span>}
{errors.title && errors.title.type !== "manual" && (
<span style={errorTextStyle}>{errors.title.message}</span>
)}
</label>
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr",
gap: "0.75rem",
}}
>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
{/* Driver */}
<label style={labelStyle}>
السائق <span style={{ color: "var(--color-danger)" }}>*</span>
<select
style={{ ...inputStyle("driverId"), cursor: "pointer" }}
value={driverId}
onChange={(e) => {
setDriverId(e.target.value);
clearErr("driverId");
}}
dir="rtl"
>
<select style={{ ...withError(!!errors.driverId), cursor: "pointer" }} {...register("driverId")} dir="rtl">
<option value="">اختر السائق</option>
{drivers.map((d) => (
<option key={d.id} value={d.id}>
@@ -350,23 +336,13 @@ export function TripFormModal({
</option>
))}
</select>
{errors.driverId && (
<span style={errorTextStyle}>{errors.driverId}</span>
)}
{errors.driverId && <span style={errorTextStyle}>{errors.driverId.message}</span>}
</label>
{/* Car */}
<label style={labelStyle}>
السيارة <span style={{ color: "var(--color-danger)" }}>*</span>
<select
style={{ ...inputStyle("carId"), cursor: "pointer" }}
value={carId}
onChange={(e) => {
setCarId(e.target.value);
clearErr("carId");
}}
dir="rtl"
>
<select style={{ ...withError(!!errors.carId), cursor: "pointer" }} {...register("carId")} dir="rtl">
<option value="">اختر السيارة</option>
{cars.map((c) => (
<option key={c.id} value={c.id}>
@@ -374,52 +350,27 @@ export function TripFormModal({
</option>
))}
</select>
{errors.carId && (
<span style={errorTextStyle}>{errors.carId}</span>
)}
{errors.carId && <span style={errorTextStyle}>{errors.carId.message}</span>}
</label>
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr",
gap: "0.75rem",
}}
>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
{/* Branch */}
<label style={labelStyle}>
الفرع <span style={{ color: "var(--color-danger)" }}>*</span>
<select
style={{ ...inputStyle("branchId"), cursor: "pointer" }}
value={branchId}
onChange={(e) => {
setBranchId(e.target.value);
clearErr("branchId");
}}
dir="rtl"
>
<select style={{ ...withError(!!errors.branchId), cursor: "pointer" }} {...register("branchId")} dir="rtl">
<option value="">اختر الفرع</option>
{branches.map((b) => (
<option key={b.id} value={b.id}>
{b.name}
</option>
<option key={b.id} value={b.id}>{b.name}</option>
))}
</select>
{errors.branchId && (
<span style={errorTextStyle}>{errors.branchId}</span>
)}
{errors.branchId && <span style={errorTextStyle}>{errors.branchId.message}</span>}
</label>
{/* Status */}
<label style={labelStyle}>
الحالة
<select
style={{ ...inputBase, cursor: "pointer" }}
value={status}
onChange={(e) => setStatus(e.target.value as TripStatus)}
dir="rtl"
>
<select style={{ ...inputBase, cursor: "pointer" }} {...register("status")} dir="rtl">
<option value="Scheduled">مجدولة</option>
<option value="InProgress">جارية</option>
<option value="Completed">مكتملة</option>
@@ -431,186 +382,73 @@ export function TripFormModal({
{/* ── Section: التوقيت ── */}
<p style={sectionHeadingStyle}>التوقيت</p>
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr",
gap: "0.75rem",
}}
>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
<label style={labelStyle}>
وقت البدء <span style={optionalLabelStyle}>(اختياري)</span>
<input
type="datetime-local"
style={inputStyle("startTime")}
value={startTime}
onChange={(e) => {
setStartTime(e.target.value);
clearErr("startTime");
}}
/>
{errors.startTime && (
<span style={errorTextStyle}>{errors.startTime}</span>
)}
<input type="datetime-local" style={withError(!!errors.startTime)} {...dateTimeField("startTime")} />
{errors.startTime && <span style={errorTextStyle}>{errors.startTime.message}</span>}
</label>
<label style={labelStyle}>
وقت الانتهاء <span style={optionalLabelStyle}>(اختياري)</span>
<input
type="datetime-local"
style={inputStyle("endTime")}
value={endTime}
onChange={(e) => {
setEndTime(e.target.value);
clearErr("endTime");
}}
/>
{errors.endTime && (
<span style={errorTextStyle}>{errors.endTime}</span>
)}
<input type="datetime-local" style={withError(!!errors.endTime)} {...dateTimeField("endTime")} />
{errors.endTime && <span style={errorTextStyle}>{errors.endTime.message}</span>}
</label>
</div>
{/* ── Section: الأعداد والمبالغ ── */}
<p style={sectionHeadingStyle}>الأعداد والمبالغ</p>
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr 1fr 1fr",
gap: "0.75rem",
}}
>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: "0.75rem" }}>
<label style={labelStyle}>
المجمّع <span style={optionalLabelStyle}>(اختياري)</span>
<input
type="number"
min="0"
style={inputStyle("collectedCount")}
value={collectedCount}
onChange={(e) => {
setCollectedCount(e.target.value);
clearErr("collectedCount");
}}
placeholder="0"
dir="ltr"
/>
{errors.collectedCount && (
<span style={errorTextStyle}>{errors.collectedCount}</span>
)}
<input type="number" min="0" style={withError(!!errors.collectedCount)} {...numberField("collectedCount")} placeholder="0" dir="ltr" />
{errors.collectedCount && <span style={errorTextStyle}>{errors.collectedCount.message}</span>}
</label>
<label style={labelStyle}>
المُسلَّم <span style={optionalLabelStyle}>(اختياري)</span>
<input
type="number"
min="0"
style={inputStyle("deliveredCount")}
value={deliveredCount}
onChange={(e) => {
setDeliveredCount(e.target.value);
clearErr("deliveredCount");
}}
placeholder="0"
dir="ltr"
/>
{errors.deliveredCount && (
<span style={errorTextStyle}>{errors.deliveredCount}</span>
)}
<input type="number" min="0" style={withError(!!errors.deliveredCount)} {...numberField("deliveredCount")} placeholder="0" dir="ltr" />
{errors.deliveredCount && <span style={errorTextStyle}>{errors.deliveredCount.message}</span>}
</label>
<label style={labelStyle}>
المُرتجع <span style={optionalLabelStyle}>(اختياري)</span>
<input
type="number"
min="0"
style={inputStyle("returnedCount")}
value={returnedCount}
onChange={(e) => {
setReturnedCount(e.target.value);
clearErr("returnedCount");
}}
placeholder="0"
dir="ltr"
/>
{errors.returnedCount && (
<span style={errorTextStyle}>{errors.returnedCount}</span>
)}
<input type="number" min="0" style={withError(!!errors.returnedCount)} {...numberField("returnedCount")} placeholder="0" dir="ltr" />
{errors.returnedCount && <span style={errorTextStyle}>{errors.returnedCount.message}</span>}
</label>
<label style={labelStyle}>
النقد المحصّل <span style={optionalLabelStyle}>(اختياري)</span>
<input
type="number"
min="0"
step="0.01"
style={inputStyle("totalCashCollected")}
value={totalCashCollected}
onChange={(e) => {
setTotalCashCollected(e.target.value);
clearErr("totalCashCollected");
}}
placeholder="0.00"
dir="ltr"
/>
{errors.totalCashCollected && (
<span style={errorTextStyle}>{errors.totalCashCollected}</span>
)}
<input type="number" min="0" step="0.01" style={withError(!!errors.totalCashCollected)} {...numberField("totalCashCollected")} placeholder="0.00" dir="ltr" />
{errors.totalCashCollected && <span style={errorTextStyle}>{errors.totalCashCollected.message}</span>}
</label>
</div>
{/* ── Section: ملاحظات ── */}
<p style={sectionHeadingStyle}>ملاحظات</p>
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr",
gap: "0.75rem",
}}
>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
<label style={labelStyle}>
ملاحظات <span style={optionalLabelStyle}>(اختياري)</span>
<textarea
style={{
...inputBase,
height: 72,
padding: "0.5rem 0.75rem",
resize: "vertical",
}}
value={notes}
onChange={(e) => {
setNotes(e.target.value);
clearErr("notes");
}}
style={{ ...withError(!!errors.notes), height: 72, padding: "0.5rem 0.75rem", resize: "vertical" }}
{...register("notes")}
placeholder="أي ملاحظات إضافية…"
dir="rtl"
/>
{errors.notes && (
<span style={errorTextStyle}>{errors.notes}</span>
)}
{errors.notes && <span style={errorTextStyle}>{errors.notes.message}</span>}
</label>
<label style={labelStyle}>
سبب الإنهاء <span style={optionalLabelStyle}>(اختياري)</span>
<textarea
style={{
...inputBase,
height: 72,
padding: "0.5rem 0.75rem",
resize: "vertical",
}}
value={endReason}
onChange={(e) => {
setEndReason(e.target.value);
clearErr("endReason");
}}
style={{ ...withError(!!errors.endReason), height: 72, padding: "0.5rem 0.75rem", resize: "vertical" }}
{...register("endReason")}
placeholder="سبب إنهاء أو إلغاء الرحلة…"
dir="rtl"
/>
{errors.endReason && (
<span style={errorTextStyle}>{errors.endReason}</span>
)}
{errors.endReason && <span style={errorTextStyle}>{errors.endReason.message}</span>}
</label>
</div>
@@ -620,13 +458,10 @@ export function TripFormModal({
<p style={sectionHeadingStyle}>سجل التغيير</p>
<label style={labelStyle}>
سبب التعديل{" "}
<span style={optionalLabelStyle}>
(مطلوب عند تغيير السائق أو السيارة)
</span>
<span style={optionalLabelStyle}>(مطلوب عند تغيير السائق أو السيارة)</span>
<input
style={inputBase}
value={reason}
onChange={(e) => setReason(e.target.value)}
{...register("reason")}
placeholder="مثال: تغيير السائق بسبب إجازة طارئة"
dir="rtl"
/>
@@ -635,18 +470,11 @@ export function TripFormModal({
)}
{/* ── Actions ── */}
<div
style={{
display: "flex",
gap: "0.5rem",
justifyContent: "flex-end",
paddingTop: "0.5rem",
}}
>
<div style={{ display: "flex", gap: "0.5rem", justifyContent: "flex-end", paddingTop: "0.5rem" }}>
<button
type="button"
onClick={onClose}
disabled={saving}
disabled={isSubmitting}
style={{
height: 40,
padding: "0 1.25rem",
@@ -656,7 +484,7 @@ export function TripFormModal({
fontSize: 13,
fontWeight: 600,
color: "var(--color-text-secondary)",
cursor: saving ? "not-allowed" : "pointer",
cursor: isSubmitting ? "not-allowed" : "pointer",
fontFamily: "var(--font-sans)",
}}
>
@@ -664,35 +492,29 @@ export function TripFormModal({
</button>
<button
type="submit"
disabled={saving}
disabled={isSubmitting}
style={{
height: 40,
padding: "0 1.5rem",
borderRadius: "var(--radius-md)",
border: "none",
background: saving
? "var(--color-brand-400)"
: "var(--color-brand-600)",
background: isSubmitting ? "var(--color-brand-400)" : "var(--color-brand-600)",
fontSize: 13,
fontWeight: 700,
color: "#FFF",
cursor: saving ? "not-allowed" : "pointer",
cursor: isSubmitting ? "not-allowed" : "pointer",
display: "flex",
alignItems: "center",
gap: 8,
fontFamily: "var(--font-sans)",
}}
>
{saving && <Spinner size="sm" className="text-white" />}
{saving
? "جارٍ الحفظ…"
: isNew
? "إضافة الرحلة"
: "حفظ التغييرات"}
{isSubmitting && <Spinner size="sm" className="text-white" />}
{isSubmitting ? "جارٍ الحفظ…" : isNew ? "إضافة الرحلة" : "حفظ التغييرات"}
</button>
</div>
</form>
</div>
</div>
);
}
}