make header one in all page
This commit is contained in:
@@ -1,12 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import * as yup from "yup";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { yupResolver } from "@hookform/resolvers/yup";
|
||||
import { Alert, Spinner } from "../UI";
|
||||
import { get } from "@/src/services/api";
|
||||
import { getStoredToken } from "@/src/lib/auth";
|
||||
import { createDriverSchema, updateDriverSchema } from "@/src/validations/driver.validator";
|
||||
import type { DriverSchemaErrors } from "@/src/validations/driver.validator";
|
||||
import type {
|
||||
Driver,
|
||||
CreateDriverPayload,
|
||||
@@ -72,6 +72,32 @@ function toIsoDateTime(val: string): string {
|
||||
return `${val}T00:00:00.000Z`;
|
||||
}
|
||||
|
||||
// ── Form values shape ────────────────────────────────────────────────────────
|
||||
|
||||
interface DriverFormValues {
|
||||
name: string;
|
||||
phone: string;
|
||||
email: string;
|
||||
address: string;
|
||||
nationality: string;
|
||||
nationalIdType: NationalIdType | "";
|
||||
nationalId: string;
|
||||
nationalIdExpiry: string;
|
||||
gosiNumber: string;
|
||||
licenseNumber: string;
|
||||
licenseType: string;
|
||||
licenseExpiry: string;
|
||||
driverCardNumber: string;
|
||||
driverCardType: DriverCardType | "";
|
||||
driverCardExpiry: string;
|
||||
driverType: string;
|
||||
branchId: string;
|
||||
status: DriverStatus;
|
||||
photo: File | null;
|
||||
nationalPhoto: File | null;
|
||||
driverCardPhoto: File | null;
|
||||
}
|
||||
|
||||
// ── Props ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface DriverFormModalProps {
|
||||
@@ -104,161 +130,123 @@ export function DriverFormModal({
|
||||
const token = getStoredToken();
|
||||
get<{ data: { data: Branch[] } }>("branches?limit=100", token)
|
||||
.then((res) => {
|
||||
const list =
|
||||
(res as unknown as { data: { data: Branch[] } }).data?.data ?? [];
|
||||
const list = (res as unknown as { data: { data: Branch[] } }).data?.data ?? [];
|
||||
setBranches(list);
|
||||
})
|
||||
.catch(() => { /* silently ignore */ });
|
||||
.catch(() => {
|
||||
/* silently ignore */
|
||||
});
|
||||
}, [branchesProp]);
|
||||
|
||||
// ── Form state ────────────────────────────────────────────────────────────
|
||||
const [name, setName] = useState(editDriver?.name ?? "");
|
||||
const [phone, setPhone] = useState(editDriver?.phone ?? "");
|
||||
const [email, setEmail] = useState(editDriver?.email ?? "");
|
||||
const [address, setAddress] = useState(editDriver?.address ?? "");
|
||||
const [nationality, setNationality] = useState(editDriver?.nationality ?? "");
|
||||
const [nationalIdType, setNationalIdType] = useState<NationalIdType | "">(
|
||||
editDriver?.nationalIdType ?? "",
|
||||
);
|
||||
const [nationalId, setNationalId] = useState(
|
||||
(editDriver as Driver & { nationalId?: string })?.nationalId ?? "",
|
||||
);
|
||||
const [nationalIdExpiry, setNationalIdExpiry] = useState(
|
||||
(editDriver as Driver & { nationalIdExpiry?: string })?.nationalIdExpiry?.slice(0, 10) ?? "",
|
||||
);
|
||||
const [gosiNumber, setGosiNumber] = useState(editDriver?.gosiNumber ?? "");
|
||||
const [licenseNumber, setLicenseNumber] = useState(editDriver?.licenseNumber ?? "");
|
||||
const [licenseType, setLicenseType] = useState(editDriver?.licenseType ?? "");
|
||||
const [licenseExpiry, setLicenseExpiry] = useState(
|
||||
editDriver?.licenseExpiry?.slice(0, 10) ?? "",
|
||||
);
|
||||
const [driverCardNumber, setDriverCardNumber] = useState(editDriver?.driverCardNumber ?? "");
|
||||
const [driverCardType, setDriverCardType] = useState<DriverCardType | "">(
|
||||
editDriver?.driverCardType ?? "",
|
||||
);
|
||||
const [driverCardExpiry, setDriverCardExpiry] = useState(
|
||||
editDriver?.driverCardExpiry?.slice(0, 10) ?? "",
|
||||
);
|
||||
const [driverType, setDriverType] = useState(editDriver?.driverType ?? "");
|
||||
const [branchId, setBranchId] = useState(
|
||||
(editDriver as Driver & { branchId?: string })?.branchId ?? "",
|
||||
);
|
||||
const [status, setStatus] = useState<DriverStatus>(editDriver?.status ?? "Active");
|
||||
// ── react-hook-form ────────────────────────────────────────────────────────
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
control,
|
||||
setError,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<DriverFormValues>({
|
||||
resolver: yupResolver(isNew ? createDriverSchema : updateDriverSchema) as never,
|
||||
defaultValues: {
|
||||
name: editDriver?.name ?? "",
|
||||
phone: editDriver?.phone ?? "",
|
||||
email: editDriver?.email ?? "",
|
||||
address: editDriver?.address ?? "",
|
||||
nationality: editDriver?.nationality ?? "",
|
||||
nationalIdType: editDriver?.nationalIdType ?? "",
|
||||
nationalId: (editDriver as Driver & { nationalId?: string })?.nationalId ?? "",
|
||||
nationalIdExpiry:
|
||||
(editDriver as Driver & { nationalIdExpiry?: string })?.nationalIdExpiry?.slice(0, 10) ?? "",
|
||||
gosiNumber: editDriver?.gosiNumber ?? "",
|
||||
licenseNumber: editDriver?.licenseNumber ?? "",
|
||||
licenseType: editDriver?.licenseType ?? "",
|
||||
licenseExpiry: editDriver?.licenseExpiry?.slice(0, 10) ?? "",
|
||||
driverCardNumber: editDriver?.driverCardNumber ?? "",
|
||||
driverCardType: editDriver?.driverCardType ?? "",
|
||||
driverCardExpiry: editDriver?.driverCardExpiry?.slice(0, 10) ?? "",
|
||||
driverType: editDriver?.driverType ?? "",
|
||||
branchId: (editDriver as Driver & { branchId?: string })?.branchId ?? "",
|
||||
status: editDriver?.status ?? "Active",
|
||||
photo: null,
|
||||
nationalPhoto: null,
|
||||
driverCardPhoto: null,
|
||||
},
|
||||
});
|
||||
|
||||
// Photo state (new uploads only)
|
||||
const [photo, setPhoto] = useState<File | null>(null);
|
||||
const [nationalPhoto, setNationalPhoto] = useState<File | null>(null);
|
||||
const [driverCardPhoto, setDriverCardPhoto] = useState<File | null>(null);
|
||||
|
||||
const [errors, setErrors] = useState<DriverSchemaErrors>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [apiError, setApiError] = useState("");
|
||||
const firstRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => { firstRef.current?.focus(); }, []);
|
||||
useEffect(() => {
|
||||
const h = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||
firstRef.current?.focus();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const h = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", h);
|
||||
return () => window.removeEventListener("keydown", h);
|
||||
}, [onClose]);
|
||||
|
||||
// ── Input error style ──────────────────────────────────────────────────────
|
||||
const inputStyle = (field: keyof DriverSchemaErrors): 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 clearFieldError = (field: keyof DriverSchemaErrors) =>
|
||||
setErrors((p) => ({ ...p, [field]: undefined }));
|
||||
// ── Submit ────────────────────────────────────────────────────────────────
|
||||
|
||||
// ── Submit with yup validation ────────────────────────────────────────────
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const submitHandler = useCallback(
|
||||
async (data: DriverFormValues) => {
|
||||
const payload: Record<string, unknown> = { name: data.name, phone: data.phone };
|
||||
if (data.email) payload.email = data.email;
|
||||
if (data.address) payload.address = data.address;
|
||||
if (data.nationality) payload.nationality = data.nationality;
|
||||
if (data.nationalIdType) payload.nationalIdType = data.nationalIdType;
|
||||
if (data.nationalId) payload.nationalId = data.nationalId;
|
||||
if (data.nationalIdExpiry) payload.nationalIdExpiry = toIsoDateTime(data.nationalIdExpiry);
|
||||
if (data.gosiNumber) payload.gosiNumber = data.gosiNumber;
|
||||
if (data.licenseNumber) payload.licenseNumber = data.licenseNumber;
|
||||
if (data.licenseType) payload.licenseType = data.licenseType;
|
||||
if (data.licenseExpiry) payload.licenseExpiry = toIsoDateTime(data.licenseExpiry);
|
||||
if (data.driverCardNumber) payload.driverCardNumber = data.driverCardNumber;
|
||||
if (data.driverCardType) payload.driverCardType = data.driverCardType;
|
||||
if (data.driverCardExpiry) payload.driverCardExpiry = toIsoDateTime(data.driverCardExpiry);
|
||||
if (data.driverType) payload.driverType = data.driverType;
|
||||
if (data.branchId) payload.branchId = data.branchId;
|
||||
if (!isNew) payload.status = data.status;
|
||||
// File fields are excluded from the JSON diff unless actually chosen —
|
||||
// matches the pre-refactor behavior exactly.
|
||||
if (data.photo) payload.photo = data.photo;
|
||||
if (data.nationalPhoto) payload.nationalPhoto = data.nationalPhoto;
|
||||
if (data.driverCardPhoto) payload.driverCardPhoto = data.driverCardPhoto;
|
||||
|
||||
// Build the raw object to validate
|
||||
const raw: Record<string, unknown> = {
|
||||
name: name || undefined,
|
||||
phone: phone || undefined,
|
||||
email: email || undefined,
|
||||
address: address || undefined,
|
||||
nationality: nationality || undefined,
|
||||
nationalIdType: nationalIdType || undefined,
|
||||
gosiNumber: gosiNumber || undefined,
|
||||
licenseNumber: licenseNumber || undefined,
|
||||
licenseType: licenseType || undefined,
|
||||
licenseExpiry: licenseExpiry || undefined,
|
||||
driverCardNumber: driverCardNumber || undefined,
|
||||
driverCardType: driverCardType || undefined,
|
||||
driverCardExpiry: driverCardExpiry || undefined,
|
||||
driverType: driverType || undefined,
|
||||
branchId: branchId || undefined,
|
||||
...(!isNew ? { status } : {}),
|
||||
};
|
||||
|
||||
try {
|
||||
const schema = isNew ? createDriverSchema : updateDriverSchema;
|
||||
await schema.validate(raw, { abortEarly: false });
|
||||
} catch (err) {
|
||||
if (err instanceof yup.ValidationError) {
|
||||
const fieldErrors: DriverSchemaErrors = {};
|
||||
err.inner.forEach((e) => {
|
||||
if (e.path) {
|
||||
fieldErrors[e.path as keyof DriverSchemaErrors] = e.message;
|
||||
}
|
||||
});
|
||||
setErrors(fieldErrors);
|
||||
return;
|
||||
setApiError("");
|
||||
try {
|
||||
const ok = await onSubmit(payload as unknown as CreateDriverPayload, isNew);
|
||||
if (ok) {
|
||||
onClose();
|
||||
} else {
|
||||
setError("name", { message: "حدث خطأ غير متوقع. يرجى المحاولة لاحقاً." });
|
||||
setApiError("حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.");
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.";
|
||||
setError("name", { message });
|
||||
setApiError(message);
|
||||
}
|
||||
}
|
||||
},
|
||||
[isNew, onSubmit, onClose, setError],
|
||||
);
|
||||
|
||||
const payload: Record<string, unknown> = { name, phone };
|
||||
if (email) payload.email = email;
|
||||
if (address) payload.address = address;
|
||||
if (nationality) payload.nationality = nationality;
|
||||
if (nationalIdType) payload.nationalIdType = nationalIdType;
|
||||
if (nationalId) payload.nationalId = nationalId;
|
||||
if (nationalIdExpiry) payload.nationalIdExpiry = toIsoDateTime(nationalIdExpiry);
|
||||
if (gosiNumber) payload.gosiNumber = gosiNumber;
|
||||
if (licenseNumber) payload.licenseNumber = licenseNumber;
|
||||
if (licenseType) payload.licenseType = licenseType;
|
||||
if (licenseExpiry) payload.licenseExpiry = toIsoDateTime(licenseExpiry);
|
||||
if (driverCardNumber) payload.driverCardNumber = driverCardNumber;
|
||||
if (driverCardType) payload.driverCardType = driverCardType;
|
||||
if (driverCardExpiry) payload.driverCardExpiry = toIsoDateTime(driverCardExpiry);
|
||||
if (driverType) payload.driverType = driverType;
|
||||
if (branchId) payload.branchId = branchId;
|
||||
if (!isNew) payload.status = status;
|
||||
if (photo) payload.photo = photo;
|
||||
if (nationalPhoto) payload.nationalPhoto = nationalPhoto;
|
||||
if (driverCardPhoto) payload.driverCardPhoto = driverCardPhoto;
|
||||
// ── Render ────────────────────────────────────────────────────────────────
|
||||
|
||||
setSaving(true);
|
||||
setApiError("");
|
||||
|
||||
try {
|
||||
const ok = await onSubmit(payload as unknown as CreateDriverPayload, isNew);
|
||||
if (ok) {
|
||||
onClose();
|
||||
} else {
|
||||
// onSubmit returned false without throwing — show generic fallback
|
||||
setApiError("حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.");
|
||||
}
|
||||
} catch (err) {
|
||||
// onSubmit threw — surface the real API error message
|
||||
const message = err instanceof Error ? err.message : "حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.";
|
||||
setApiError(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="driver-modal-title"
|
||||
onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
|
||||
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)",
|
||||
@@ -305,7 +293,7 @@ export function DriverFormModal({
|
||||
|
||||
{/* Form */}
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
onSubmit={handleSubmit(submitHandler)}
|
||||
noValidate
|
||||
style={{
|
||||
padding: "1.5rem",
|
||||
@@ -314,8 +302,8 @@ export function DriverFormModal({
|
||||
}}
|
||||
dir="rtl"
|
||||
>
|
||||
{apiError && (
|
||||
<Alert type="error" message={apiError} onClose={() => setApiError("")} />
|
||||
{errors.name?.type === "manual" && (
|
||||
<Alert type="error" message={errors.name.message ?? ""} onClose={() => setApiError("")} />
|
||||
)}
|
||||
|
||||
{/* ── Section: Personal Info ── */}
|
||||
@@ -327,27 +315,27 @@ export function DriverFormModal({
|
||||
الاسم الكامل *
|
||||
<input
|
||||
ref={firstRef}
|
||||
style={inputStyle("name")}
|
||||
value={name}
|
||||
onChange={(e) => { setName(e.target.value); clearFieldError("name"); }}
|
||||
style={withError(!!errors.name && errors.name.type !== "manual")}
|
||||
{...register("name")}
|
||||
placeholder="محمد عبدالله"
|
||||
dir="rtl"
|
||||
autoComplete="off"
|
||||
/>
|
||||
{errors.name && <span style={errorTextStyle}>{errors.name}</span>}
|
||||
{errors.name && errors.name.type !== "manual" && (
|
||||
<span style={errorTextStyle}>{errors.name.message}</span>
|
||||
)}
|
||||
</label>
|
||||
|
||||
{/* Phone — required */}
|
||||
<label style={labelStyle}>
|
||||
رقم الجوال *
|
||||
<input
|
||||
style={inputStyle("phone")}
|
||||
value={phone}
|
||||
onChange={(e) => { setPhone(e.target.value); clearFieldError("phone"); }}
|
||||
style={withError(!!errors.phone)}
|
||||
{...register("phone")}
|
||||
placeholder="05XXXXXXXX"
|
||||
dir="ltr"
|
||||
/>
|
||||
{errors.phone && <span style={errorTextStyle}>{errors.phone}</span>}
|
||||
{errors.phone && <span style={errorTextStyle}>{errors.phone.message}</span>}
|
||||
</label>
|
||||
|
||||
{/* Email — optional */}
|
||||
@@ -355,14 +343,13 @@ export function DriverFormModal({
|
||||
البريد الإلكتروني
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<input
|
||||
style={inputStyle("email")}
|
||||
style={withError(!!errors.email)}
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => { setEmail(e.target.value); clearFieldError("email"); }}
|
||||
{...register("email")}
|
||||
placeholder="example@mail.com"
|
||||
dir="ltr"
|
||||
/>
|
||||
{errors.email && <span style={errorTextStyle}>{errors.email}</span>}
|
||||
{errors.email && <span style={errorTextStyle}>{errors.email.message}</span>}
|
||||
</label>
|
||||
|
||||
{/* Nationality — optional */}
|
||||
@@ -370,13 +357,12 @@ export function DriverFormModal({
|
||||
الجنسية
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<input
|
||||
style={inputBase}
|
||||
value={nationality}
|
||||
onChange={(e) => { setNationality(e.target.value); clearFieldError("nationality"); }}
|
||||
style={withError(!!errors.nationality)}
|
||||
{...register("nationality")}
|
||||
placeholder="سعودي"
|
||||
dir="rtl"
|
||||
/>
|
||||
{errors.nationality && <span style={errorTextStyle}>{errors.nationality}</span>}
|
||||
{errors.nationality && <span style={errorTextStyle}>{errors.nationality.message}</span>}
|
||||
</label>
|
||||
|
||||
{/* Address — optional, full width */}
|
||||
@@ -384,13 +370,12 @@ export function DriverFormModal({
|
||||
العنوان
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<input
|
||||
style={inputStyle("address")}
|
||||
value={address}
|
||||
onChange={(e) => { setAddress(e.target.value); clearFieldError("address"); }}
|
||||
style={withError(!!errors.address)}
|
||||
{...register("address")}
|
||||
placeholder="الرياض، حي..."
|
||||
dir="rtl"
|
||||
/>
|
||||
{errors.address && <span style={errorTextStyle}>{errors.address}</span>}
|
||||
{errors.address && <span style={errorTextStyle}>{errors.address.message}</span>}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
@@ -403,9 +388,8 @@ export function DriverFormModal({
|
||||
نوع الهوية
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<select
|
||||
style={{ ...inputStyle("nationalIdType"), cursor: "pointer" }}
|
||||
value={nationalIdType}
|
||||
onChange={(e) => { setNationalIdType(e.target.value as NationalIdType | ""); clearFieldError("nationalIdType"); }}
|
||||
style={{ ...withError(!!errors.nationalIdType), cursor: "pointer" }}
|
||||
{...register("nationalIdType")}
|
||||
dir="rtl"
|
||||
>
|
||||
<option value="">اختر النوع</option>
|
||||
@@ -413,45 +397,28 @@ export function DriverFormModal({
|
||||
<option value="Iqama">إقامة</option>
|
||||
<option value="Passport">جواز سفر</option>
|
||||
</select>
|
||||
{errors.nationalIdType && <span style={errorTextStyle}>{errors.nationalIdType}</span>}
|
||||
{errors.nationalIdType && <span style={errorTextStyle}>{errors.nationalIdType.message}</span>}
|
||||
</label>
|
||||
|
||||
{/* National ID number */}
|
||||
<label style={labelStyle}>
|
||||
رقم الهوية
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<input
|
||||
style={inputBase}
|
||||
value={nationalId}
|
||||
onChange={(e) => setNationalId(e.target.value)}
|
||||
placeholder="1XXXXXXXXX"
|
||||
dir="ltr"
|
||||
/>
|
||||
<input style={inputBase} {...register("nationalId")} placeholder="1XXXXXXXXX" dir="ltr" />
|
||||
</label>
|
||||
|
||||
{/* National ID expiry */}
|
||||
<label style={labelStyle}>
|
||||
انتهاء الهوية
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<input
|
||||
style={inputBase}
|
||||
type="date"
|
||||
value={nationalIdExpiry}
|
||||
onChange={(e) => setNationalIdExpiry(e.target.value)}
|
||||
/>
|
||||
<input style={inputBase} type="date" {...register("nationalIdExpiry")} />
|
||||
</label>
|
||||
|
||||
{/* GOSI — optional */}
|
||||
<label style={labelStyle}>
|
||||
رقم GOSI
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<input
|
||||
style={inputBase}
|
||||
value={gosiNumber}
|
||||
onChange={(e) => setGosiNumber(e.target.value)}
|
||||
placeholder="GOSI-XXXX"
|
||||
dir="ltr"
|
||||
/>
|
||||
<input style={inputBase} {...register("gosiNumber")} placeholder="GOSI-XXXX" dir="ltr" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
@@ -464,39 +431,27 @@ export function DriverFormModal({
|
||||
رقم الرخصة
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<input
|
||||
style={inputStyle("licenseNumber")}
|
||||
value={licenseNumber}
|
||||
onChange={(e) => { setLicenseNumber(e.target.value); clearFieldError("licenseNumber"); }}
|
||||
style={withError(!!errors.licenseNumber)}
|
||||
{...register("licenseNumber")}
|
||||
placeholder="LIC-XXXX"
|
||||
dir="ltr"
|
||||
/>
|
||||
{errors.licenseNumber && <span style={errorTextStyle}>{errors.licenseNumber}</span>}
|
||||
{errors.licenseNumber && <span style={errorTextStyle}>{errors.licenseNumber.message}</span>}
|
||||
</label>
|
||||
|
||||
{/* License type — optional */}
|
||||
<label style={labelStyle}>
|
||||
نوع الرخصة
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<input
|
||||
style={inputBase}
|
||||
value={licenseType}
|
||||
onChange={(e) => setLicenseType(e.target.value)}
|
||||
placeholder="خاص / عام"
|
||||
dir="rtl"
|
||||
/>
|
||||
<input style={inputBase} {...register("licenseType")} placeholder="خاص / عام" dir="rtl" />
|
||||
</label>
|
||||
|
||||
{/* License expiry — optional, validated if provided */}
|
||||
<label style={labelStyle}>
|
||||
انتهاء الرخصة
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<input
|
||||
style={inputStyle("licenseExpiry")}
|
||||
type="date"
|
||||
value={licenseExpiry}
|
||||
onChange={(e) => { setLicenseExpiry(e.target.value); clearFieldError("licenseExpiry"); }}
|
||||
/>
|
||||
{errors.licenseExpiry && <span style={errorTextStyle}>{errors.licenseExpiry}</span>}
|
||||
<input style={withError(!!errors.licenseExpiry)} type="date" {...register("licenseExpiry")} />
|
||||
{errors.licenseExpiry && <span style={errorTextStyle}>{errors.licenseExpiry.message}</span>}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
@@ -508,13 +463,7 @@ export function DriverFormModal({
|
||||
<label style={labelStyle}>
|
||||
رقم البطاقة
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<input
|
||||
style={inputBase}
|
||||
value={driverCardNumber}
|
||||
onChange={(e) => setDriverCardNumber(e.target.value)}
|
||||
placeholder="CARD-XXXX"
|
||||
dir="ltr"
|
||||
/>
|
||||
<input style={inputBase} {...register("driverCardNumber")} placeholder="CARD-XXXX" dir="ltr" />
|
||||
</label>
|
||||
|
||||
{/* Card type — optional */}
|
||||
@@ -522,9 +471,8 @@ export function DriverFormModal({
|
||||
نوع البطاقة
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<select
|
||||
style={{ ...inputStyle("driverCardType"), cursor: "pointer" }}
|
||||
value={driverCardType}
|
||||
onChange={(e) => { setDriverCardType(e.target.value as DriverCardType | ""); clearFieldError("driverCardType"); }}
|
||||
style={{ ...withError(!!errors.driverCardType), cursor: "pointer" }}
|
||||
{...register("driverCardType")}
|
||||
dir="rtl"
|
||||
>
|
||||
<option value="">اختر النوع</option>
|
||||
@@ -533,7 +481,7 @@ export function DriverFormModal({
|
||||
<option value="Annual">سنوية</option>
|
||||
<option value="Restricted">مقيدة</option>
|
||||
</select>
|
||||
{errors.driverCardType && <span style={errorTextStyle}>{errors.driverCardType}</span>}
|
||||
{errors.driverCardType && <span style={errorTextStyle}>{errors.driverCardType.message}</span>}
|
||||
</label>
|
||||
|
||||
{/* Card expiry — optional, validated if provided */}
|
||||
@@ -541,12 +489,13 @@ export function DriverFormModal({
|
||||
انتهاء البطاقة
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<input
|
||||
style={inputStyle("driverCardExpiry")}
|
||||
style={withError(!!errors.driverCardExpiry)}
|
||||
type="date"
|
||||
value={driverCardExpiry}
|
||||
onChange={(e) => { setDriverCardExpiry(e.target.value); clearFieldError("driverCardExpiry"); }}
|
||||
{...register("driverCardExpiry")}
|
||||
/>
|
||||
{errors.driverCardExpiry && <span style={errorTextStyle}>{errors.driverCardExpiry}</span>}
|
||||
{errors.driverCardExpiry && (
|
||||
<span style={errorTextStyle}>{errors.driverCardExpiry.message}</span>
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
@@ -559,9 +508,8 @@ export function DriverFormModal({
|
||||
الفرع
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<select
|
||||
style={{ ...inputStyle("branchId"), cursor: "pointer" }}
|
||||
value={branchId}
|
||||
onChange={(e) => { setBranchId(e.target.value); clearFieldError("branchId"); }}
|
||||
style={{ ...withError(!!errors.branchId), cursor: "pointer" }}
|
||||
{...register("branchId")}
|
||||
dir="rtl"
|
||||
>
|
||||
<option value="">اختر الفرع</option>
|
||||
@@ -569,32 +517,21 @@ export function DriverFormModal({
|
||||
<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>
|
||||
|
||||
{/* Driver type — optional */}
|
||||
<label style={labelStyle}>
|
||||
نوع السائق
|
||||
<span style={optionalLabelStyle}>(اختياري)</span>
|
||||
<input
|
||||
style={inputBase}
|
||||
value={driverType}
|
||||
onChange={(e) => setDriverType(e.target.value)}
|
||||
placeholder="رئيسي / احتياطي"
|
||||
dir="rtl"
|
||||
/>
|
||||
<input style={inputBase} {...register("driverType")} placeholder="رئيسي / احتياطي" dir="rtl" />
|
||||
</label>
|
||||
|
||||
{/* Status — edit only */}
|
||||
{!isNew && (
|
||||
<label style={labelStyle}>
|
||||
الحالة
|
||||
<select
|
||||
style={{ ...inputBase, cursor: "pointer" }}
|
||||
value={status}
|
||||
onChange={(e) => setStatus(e.target.value as DriverStatus)}
|
||||
dir="rtl"
|
||||
>
|
||||
<select style={{ ...inputBase, cursor: "pointer" }} {...register("status")} dir="rtl">
|
||||
<option value="Active">نشط</option>
|
||||
<option value="InTrip">في رحلة</option>
|
||||
<option value="Inactive">غير نشط</option>
|
||||
@@ -611,9 +548,29 @@ export function DriverFormModal({
|
||||
</p>
|
||||
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "0.75rem" }}>
|
||||
<FileInput label="صورة السائق" current={photo} onChange={setPhoto} />
|
||||
<FileInput label="صورة الهوية" current={nationalPhoto} onChange={setNationalPhoto} />
|
||||
<FileInput label="صورة البطاقة" current={driverCardPhoto} onChange={setDriverCardPhoto} />
|
||||
{/* File inputs cannot use register() directly — bind via Controller
|
||||
to the existing FileInput component's current/onChange props. */}
|
||||
<Controller
|
||||
name="photo"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FileInput label="صورة السائق" current={field.value} onChange={field.onChange} />
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="nationalPhoto"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FileInput label="صورة الهوية" current={field.value} onChange={field.onChange} />
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="driverCardPhoto"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FileInput label="صورة البطاقة" current={field.value} onChange={field.onChange} />
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ── Actions ── */}
|
||||
@@ -621,14 +578,14 @@ export function DriverFormModal({
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
disabled={saving}
|
||||
disabled={isSubmitting}
|
||||
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",
|
||||
cursor: isSubmitting ? "not-allowed" : "pointer",
|
||||
fontFamily: "var(--font-sans)",
|
||||
}}
|
||||
>
|
||||
@@ -636,20 +593,20 @@ export function DriverFormModal({
|
||||
</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>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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>
|
||||
);
|
||||
}
|
||||
}
|
||||
179
src/Components/UI/Header.tsx
Normal file
179
src/Components/UI/Header.tsx
Normal file
@@ -0,0 +1,179 @@
|
||||
export default function Header({
|
||||
state,
|
||||
search,
|
||||
setSearch,
|
||||
module,
|
||||
setModule,
|
||||
setPage,
|
||||
title,
|
||||
mainTitle,
|
||||
name,
|
||||
isAudit = false,
|
||||
onAdd,
|
||||
}: {
|
||||
state: any;
|
||||
search: string;
|
||||
setSearch: (search: string) => void;
|
||||
module: string;
|
||||
setModule: (module: string) => void;
|
||||
setPage: (page: number) => void;
|
||||
title: string;
|
||||
mainTitle: string;
|
||||
name: string;
|
||||
isAudit?: boolean;
|
||||
onAdd?: () => void;
|
||||
}) {
|
||||
return (
|
||||
<header
|
||||
style={{
|
||||
borderRadius: "var(--radius-xl)",
|
||||
border: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface)",
|
||||
padding: "1.5rem 2rem",
|
||||
boxShadow: "var(--shadow-card)",
|
||||
}}
|
||||
>
|
||||
<p
|
||||
style={{
|
||||
fontSize: 11,
|
||||
letterSpacing: "0.3em",
|
||||
textTransform: "uppercase",
|
||||
color: "#2563EB",
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
{title}
|
||||
</p>
|
||||
<div className="mt-3 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div>
|
||||
<h1
|
||||
style={{
|
||||
fontSize: "1.5rem",
|
||||
fontWeight: 700,
|
||||
color: "var(--color-text-primary)",
|
||||
margin: 0,
|
||||
}}
|
||||
>
|
||||
{mainTitle}
|
||||
</h1>
|
||||
<p
|
||||
style={{
|
||||
marginTop: "0.25rem",
|
||||
fontSize: 13,
|
||||
color: "var(--color-text-muted)",
|
||||
}}
|
||||
>
|
||||
إجمالي{" "}
|
||||
<strong style={{ color: "var(--color-text-primary)" }}>
|
||||
{state.total}
|
||||
</strong>{" "}
|
||||
{name}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: "0.5rem",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="بحث "
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
dir="rtl"
|
||||
style={{
|
||||
width: 220,
|
||||
height: 40,
|
||||
padding: "0 0.75rem",
|
||||
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)",
|
||||
}}
|
||||
/>
|
||||
{isAudit ? (
|
||||
<select
|
||||
value={module}
|
||||
onChange={(e) => {
|
||||
setModule(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
dir="rtl"
|
||||
style={{
|
||||
height: 40,
|
||||
padding: "0 0.75rem",
|
||||
borderRadius: "var(--radius-lg)",
|
||||
border: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface)",
|
||||
fontSize: 13,
|
||||
color: "var(--color-text-secondary)",
|
||||
outline: "none",
|
||||
fontFamily: "var(--font-sans)",
|
||||
}}
|
||||
>
|
||||
<option value="">كل الوحدات</option>
|
||||
{[
|
||||
"User",
|
||||
"Driver",
|
||||
"Car",
|
||||
"Trip",
|
||||
"Order",
|
||||
"Client",
|
||||
"Role",
|
||||
"Branch",
|
||||
].map((m) => (
|
||||
<option key={m} value={m}>
|
||||
{m}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAdd}
|
||||
style={{
|
||||
height: 40,
|
||||
padding: "0 1.125rem",
|
||||
borderRadius: "var(--radius-lg)",
|
||||
border: "none",
|
||||
background: "var(--color-brand-600)",
|
||||
fontSize: 13,
|
||||
fontWeight: 700,
|
||||
color: "#FFF",
|
||||
cursor: "pointer",
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
gap: 7,
|
||||
fontFamily: "var(--font-sans)",
|
||||
boxShadow: "0 1px 4px rgba(37,99,235,.35)",
|
||||
whiteSpace: "nowrap",
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2.5"
|
||||
>
|
||||
<line x1="12" y1="5" x2="12" y2="19" />
|
||||
<line x1="5" y1="12" x2="19" y2="12" />
|
||||
</svg>
|
||||
إضافة {name}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import * as yup from "yup";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { yupResolver } from "@hookform/resolvers/yup";
|
||||
import { Alert, Spinner } from "../UI";
|
||||
import { getStoredToken } from "@/src/lib/auth";
|
||||
import {
|
||||
@@ -10,7 +11,6 @@ import {
|
||||
} from "@/src/validations/car.validator";
|
||||
import type {
|
||||
Car,
|
||||
CarFormErrors,
|
||||
CreateCarPayload,
|
||||
InsuranceStatus,
|
||||
UpdateCarPayload,
|
||||
@@ -18,7 +18,6 @@ import type {
|
||||
import type { Branch } from "@/src/types/branch";
|
||||
import { branchService } from "@/src/services/branch.service";
|
||||
|
||||
|
||||
// ── Shared input style ────────────────────────────────────────────────────────
|
||||
|
||||
const inputBase: React.CSSProperties = {
|
||||
@@ -49,27 +48,14 @@ const errorTextStyle: React.CSSProperties = {
|
||||
fontWeight: 500,
|
||||
};
|
||||
|
||||
// ── yup validation ────────────────────────────────────────────────────────────
|
||||
|
||||
async function validate(
|
||||
form: Partial<CreateCarPayload>,
|
||||
isNew: boolean,
|
||||
): Promise<CarFormErrors> {
|
||||
const schema = isNew ? createCarSchema : updateCarSchema;
|
||||
try {
|
||||
await schema.validate(form, { abortEarly: false });
|
||||
return {};
|
||||
} catch (err) {
|
||||
if (err instanceof yup.ValidationError) {
|
||||
return err.inner.reduce<CarFormErrors>((acc, e) => {
|
||||
const field = e.path as keyof CarFormErrors;
|
||||
if (field && !acc[field]) acc[field] = e.message;
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
return {};
|
||||
}
|
||||
}
|
||||
const sectionHeadingStyle: React.CSSProperties = {
|
||||
fontSize: 11,
|
||||
letterSpacing: "0.25em",
|
||||
textTransform: "uppercase",
|
||||
color: "var(--color-text-hint)",
|
||||
fontWeight: 700,
|
||||
margin: "0.5rem 0 0",
|
||||
};
|
||||
|
||||
// ── Date helper ───────────────────────────────────────────────────────────────
|
||||
// <input type="date"> gives "YYYY-MM-DD"; backend expects full ISO-8601.
|
||||
@@ -80,6 +66,30 @@ function toIsoDateTime(val: string): string {
|
||||
return `${val}T00:00:00.000Z`;
|
||||
}
|
||||
|
||||
// ── Form values shape ─────────────────────────────────────────────────────────
|
||||
// Mirrors the subset of CreateCarPayload/UpdateCarPayload actually edited here.
|
||||
|
||||
interface CarFormValues {
|
||||
manufacturer: string;
|
||||
model: string;
|
||||
color: string;
|
||||
plateNumber: string;
|
||||
plateLetters: string;
|
||||
plateType: string;
|
||||
registrationNumber: string;
|
||||
vinNumber: string;
|
||||
branchId: string;
|
||||
currentStatus: Car["currentStatus"];
|
||||
insuranceStatus: InsuranceStatus;
|
||||
registrationExpiryDate: string;
|
||||
insuranceExpiryDate: string;
|
||||
inspectionExpiryDate: string;
|
||||
gpsDeviceId: string;
|
||||
year: number | undefined;
|
||||
capacity: number | undefined;
|
||||
weight: number | undefined;
|
||||
}
|
||||
|
||||
// ── Props ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface CarFormModalProps {
|
||||
@@ -104,67 +114,60 @@ export function CarFormModal({
|
||||
const isNew = editCar === null;
|
||||
|
||||
// ── Local branches (auto-fetched if prop is empty) ─────────────────────────
|
||||
const [branches, setBranches] = useState<Branch[]>(branchesProp);
|
||||
const loadBranches = useCallback(() => {
|
||||
if (branchesProp.length > 0) {
|
||||
queueMicrotask(() => setBranches(branchesProp));
|
||||
return;
|
||||
}
|
||||
const token = getStoredToken();
|
||||
branchService
|
||||
.getOptions(token)
|
||||
.then((list) => {
|
||||
queueMicrotask(() => setBranches(list as unknown as Branch[]));
|
||||
})
|
||||
.catch(() => {
|
||||
/* silently ignore */
|
||||
});
|
||||
}, [branchesProp]);
|
||||
const [branches, setBranches] = useState<Branch[]>(branchesProp);
|
||||
const loadBranches = useCallback(() => {
|
||||
if (branchesProp.length > 0) {
|
||||
queueMicrotask(() => setBranches(branchesProp));
|
||||
return;
|
||||
}
|
||||
const token = getStoredToken();
|
||||
branchService
|
||||
.getOptions(token)
|
||||
.then((list) => {
|
||||
queueMicrotask(() => setBranches(list as unknown as Branch[]));
|
||||
})
|
||||
.catch(() => {
|
||||
/* silently ignore */
|
||||
});
|
||||
}, [branchesProp]);
|
||||
|
||||
useEffect(() => {
|
||||
loadBranches();
|
||||
}, [loadBranches]);
|
||||
|
||||
// ── Form state ─────────────────────────────────────────────────────────────
|
||||
const [manufacturer, setManufacturer] = useState(editCar?.manufacturer ?? "");
|
||||
const [model, setModel] = useState(editCar?.model ?? "");
|
||||
const [color, setColor] = useState(editCar?.color ?? "");
|
||||
const [plateNumber, setPlateNumber] = useState(editCar?.plateNumber ?? "");
|
||||
const [plateLetters, setPlateLetters] = useState(editCar?.plateLetters ?? "");
|
||||
const [plateType, setPlateType] = useState(editCar?.plateType ?? "");
|
||||
const [registrationNumber, setRegistrationNumber] = useState(
|
||||
editCar?.registrationNumber ?? "",
|
||||
);
|
||||
const [vinNumber, setVinNumber] = useState(editCar?.vinNumber ?? "");
|
||||
const [branchId, setBranchId] = useState(editCar?.branch?.id ?? "");
|
||||
const [currentStatus, setCurrentStatus] = useState<Car["currentStatus"]>(
|
||||
editCar?.currentStatus ?? "Active",
|
||||
);
|
||||
const [insuranceStatus, setInsuranceStatus] = useState<InsuranceStatus>(
|
||||
(editCar?.insuranceStatus as InsuranceStatus) ?? "Valid",
|
||||
);
|
||||
const [registrationExpiryDate, setRegistrationExpiryDate] = useState(
|
||||
editCar?.registrationExpiryDate?.slice(0, 10) ?? "",
|
||||
);
|
||||
const [insuranceExpiryDate, setInsuranceExpiryDate] = useState(
|
||||
editCar?.insuranceExpiryDate?.slice(0, 10) ?? "",
|
||||
);
|
||||
const [inspectionExpiryDate, setInspectionExpiryDate] = useState(
|
||||
editCar?.inspectionExpiryDate?.slice(0, 10) ?? "",
|
||||
);
|
||||
const [gpsDeviceId, setGpsDeviceId] = useState(editCar?.gpsDeviceId ?? "");
|
||||
const [year, setYear] = useState<number | undefined>(
|
||||
editCar?.year ?? new Date().getFullYear(),
|
||||
);
|
||||
const [capacity, setCapacity] = useState<number | undefined>(
|
||||
editCar?.capacity ?? undefined,
|
||||
);
|
||||
const [weight, setWeight] = useState<number | undefined>(
|
||||
editCar?.weight ?? undefined,
|
||||
);
|
||||
// ── react-hook-form ────────────────────────────────────────────────────────
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
setError,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<CarFormValues>({
|
||||
resolver: yupResolver(isNew ? createCarSchema : updateCarSchema) as never,
|
||||
defaultValues: {
|
||||
manufacturer: editCar?.manufacturer ?? "",
|
||||
model: editCar?.model ?? "",
|
||||
color: editCar?.color ?? "",
|
||||
plateNumber: editCar?.plateNumber ?? "",
|
||||
plateLetters: editCar?.plateLetters ?? "",
|
||||
plateType: editCar?.plateType ?? "",
|
||||
registrationNumber: editCar?.registrationNumber ?? "",
|
||||
vinNumber: editCar?.vinNumber ?? "",
|
||||
branchId: editCar?.branch?.id ?? "",
|
||||
currentStatus: editCar?.currentStatus ?? "Active",
|
||||
insuranceStatus: (editCar?.insuranceStatus as InsuranceStatus) ?? "Valid",
|
||||
registrationExpiryDate: editCar?.registrationExpiryDate?.slice(0, 10) ?? "",
|
||||
insuranceExpiryDate: editCar?.insuranceExpiryDate?.slice(0, 10) ?? "",
|
||||
inspectionExpiryDate: editCar?.inspectionExpiryDate?.slice(0, 10) ?? "",
|
||||
gpsDeviceId: editCar?.gpsDeviceId ?? "",
|
||||
// NOTE: kept as number | undefined instead of RHF's valueAsNumber so an
|
||||
// empty input maps to `undefined` (matches the old parseNum() guard)
|
||||
// rather than NaN, which would otherwise trip the yup .typeError() rule.
|
||||
year: editCar?.year ?? new Date().getFullYear(),
|
||||
capacity: editCar?.capacity ?? undefined,
|
||||
weight: editCar?.weight ?? undefined,
|
||||
},
|
||||
});
|
||||
|
||||
const [errors, setErrors] = useState<CarFormErrors>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [apiError, setApiError] = useState("");
|
||||
const firstRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
@@ -179,84 +182,63 @@ const loadBranches = useCallback(() => {
|
||||
return () => window.removeEventListener("keydown", h);
|
||||
}, [onClose]);
|
||||
|
||||
const parseNum = (v: string): number | undefined =>
|
||||
v.trim() === "" ? undefined : Number(v);
|
||||
// Numeric fields: empty string -> undefined (never NaN), matching the
|
||||
// behavior of the old parseNum() helper.
|
||||
const numberField = (
|
||||
field: "year" | "capacity" | "weight",
|
||||
) =>
|
||||
register(field, {
|
||||
setValueAs: (v) => (v === "" || v === null ? undefined : Number(v)),
|
||||
});
|
||||
|
||||
const inputStyle = (field: keyof CarFormErrors): 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 clearFieldError = (field: keyof CarFormErrors) =>
|
||||
setErrors((p) => ({ ...p, [field]: undefined }));
|
||||
|
||||
// ── Submit ────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
// Build snapshot for yup — include all fields so optional rules also run
|
||||
const formSnapshot: Partial<CreateCarPayload> = {
|
||||
manufacturer,
|
||||
model,
|
||||
year,
|
||||
plateNumber,
|
||||
plateLetters,
|
||||
currentStatus,
|
||||
insuranceStatus,
|
||||
registrationNumber,
|
||||
vinNumber,
|
||||
...(color && { color }),
|
||||
...(plateType && { plateType }),
|
||||
...(branchId && { branchId }),
|
||||
...(registrationExpiryDate && { registrationExpiryDate }),
|
||||
...(insuranceExpiryDate && { insuranceExpiryDate }),
|
||||
...(inspectionExpiryDate && { inspectionExpiryDate }),
|
||||
...(gpsDeviceId && { gpsDeviceId }),
|
||||
...(capacity !== undefined && { capacity }),
|
||||
...(weight !== undefined && { weight }),
|
||||
};
|
||||
|
||||
const errs = await validate(formSnapshot, isNew);
|
||||
if (Object.keys(errs).length) {
|
||||
setErrors(errs);
|
||||
return;
|
||||
}
|
||||
|
||||
// Build final payload — convert date strings to ISO-8601 for the backend
|
||||
const submitHandler = async (data: CarFormValues) => {
|
||||
// Build final payload — convert date strings to ISO-8601 for the backend,
|
||||
// and drop empty-optional fields exactly like the pre-refactor version did.
|
||||
const raw: Record<string, unknown> = {
|
||||
manufacturer,
|
||||
model,
|
||||
year,
|
||||
plateNumber,
|
||||
plateLetters,
|
||||
currentStatus,
|
||||
manufacturer: data.manufacturer,
|
||||
model: data.model,
|
||||
year: data.year,
|
||||
plateNumber: data.plateNumber,
|
||||
plateLetters: data.plateLetters,
|
||||
currentStatus: data.currentStatus,
|
||||
};
|
||||
if (color) raw.color = color;
|
||||
if (plateType) raw.plateType = plateType;
|
||||
if (registrationNumber) raw.registrationNumber = registrationNumber;
|
||||
if (vinNumber) raw.vinNumber = vinNumber;
|
||||
if (branchId) raw.branchId = branchId;
|
||||
if (insuranceStatus) raw.insuranceStatus = insuranceStatus;
|
||||
if (registrationExpiryDate)
|
||||
raw.registrationExpiryDate = toIsoDateTime(registrationExpiryDate);
|
||||
if (insuranceExpiryDate)
|
||||
raw.insuranceExpiryDate = toIsoDateTime(insuranceExpiryDate);
|
||||
if (inspectionExpiryDate)
|
||||
raw.inspectionExpiryDate = toIsoDateTime(inspectionExpiryDate);
|
||||
if (gpsDeviceId) raw.gpsDeviceId = gpsDeviceId;
|
||||
if (capacity !== undefined) raw.capacity = capacity;
|
||||
if (weight !== undefined) raw.weight = weight;
|
||||
if (data.color) raw.color = data.color;
|
||||
if (data.plateType) raw.plateType = data.plateType;
|
||||
if (data.registrationNumber) raw.registrationNumber = data.registrationNumber;
|
||||
if (data.vinNumber) raw.vinNumber = data.vinNumber;
|
||||
if (data.branchId) raw.branchId = data.branchId;
|
||||
if (data.insuranceStatus) raw.insuranceStatus = data.insuranceStatus;
|
||||
if (data.registrationExpiryDate)
|
||||
raw.registrationExpiryDate = toIsoDateTime(data.registrationExpiryDate);
|
||||
if (data.insuranceExpiryDate)
|
||||
raw.insuranceExpiryDate = toIsoDateTime(data.insuranceExpiryDate);
|
||||
if (data.inspectionExpiryDate)
|
||||
raw.inspectionExpiryDate = toIsoDateTime(data.inspectionExpiryDate);
|
||||
if (data.gpsDeviceId) raw.gpsDeviceId = data.gpsDeviceId;
|
||||
// Defensive re-coercion: mirrors CarMaintenanceFormModal's
|
||||
// toNumberOrUndefined() safeguard, in case capacity/weight ever round-trip
|
||||
// as numeric strings from a Decimal-backed field on the backend.
|
||||
if (data.capacity !== undefined && data.capacity !== null && !Number.isNaN(Number(data.capacity)))
|
||||
raw.capacity = Number(data.capacity);
|
||||
if (data.weight !== undefined && data.weight !== null && !Number.isNaN(Number(data.weight)))
|
||||
raw.weight = Number(data.weight);
|
||||
|
||||
const payload = raw as unknown as CreateCarPayload;
|
||||
setSaving(true);
|
||||
setApiError("");
|
||||
const ok = await onSubmit(payload, isNew);
|
||||
setSaving(false);
|
||||
if (ok) onClose();
|
||||
else setApiError("حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.");
|
||||
if (ok) {
|
||||
onClose();
|
||||
} else {
|
||||
setError("manufacturer", { message: "حدث خطأ غير متوقع. يرجى المحاولة لاحقاً." });
|
||||
setApiError("حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.");
|
||||
}
|
||||
};
|
||||
|
||||
// ── Render ────────────────────────────────────────────────────────────────
|
||||
@@ -328,9 +310,7 @@ const loadBranches = useCallback(() => {
|
||||
margin: "4px 0 0",
|
||||
}}
|
||||
>
|
||||
{isNew
|
||||
? "مركبة جديدة"
|
||||
: `${editCar?.manufacturer} ${editCar?.model}`}
|
||||
{isNew ? "مركبة جديدة" : `${editCar?.manufacturer} ${editCar?.model}`}
|
||||
</h2>
|
||||
</div>
|
||||
<button
|
||||
@@ -357,7 +337,7 @@ const loadBranches = useCallback(() => {
|
||||
|
||||
{/* Form */}
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
onSubmit={handleSubmit(submitHandler)}
|
||||
noValidate
|
||||
style={{
|
||||
padding: "1.5rem",
|
||||
@@ -369,241 +349,130 @@ const loadBranches = useCallback(() => {
|
||||
}}
|
||||
dir="rtl"
|
||||
>
|
||||
{apiError && (
|
||||
{errors.manufacturer?.type === "manual" && (
|
||||
<Alert
|
||||
type="error"
|
||||
message={apiError}
|
||||
message={errors.manufacturer.message ?? ""}
|
||||
onClose={() => setApiError("")}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── Section: Basic Info ── */}
|
||||
<p
|
||||
style={{
|
||||
fontSize: 11,
|
||||
letterSpacing: "0.25em",
|
||||
textTransform: "uppercase",
|
||||
color: "var(--color-text-hint)",
|
||||
fontWeight: 700,
|
||||
margin: 0,
|
||||
}}
|
||||
>
|
||||
بيانات أساسية
|
||||
</p>
|
||||
<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}>
|
||||
الشركة المصنعة *
|
||||
<input
|
||||
ref={firstRef}
|
||||
style={inputStyle("manufacturer")}
|
||||
value={manufacturer}
|
||||
onChange={(e) => {
|
||||
setManufacturer(e.target.value);
|
||||
clearFieldError("manufacturer");
|
||||
}}
|
||||
style={withError(!!errors.manufacturer && errors.manufacturer.type !== "manual")}
|
||||
{...register("manufacturer")}
|
||||
placeholder="تويوتا"
|
||||
dir="rtl"
|
||||
autoComplete="off"
|
||||
/>
|
||||
{errors.manufacturer && (
|
||||
<span style={errorTextStyle}>{errors.manufacturer}</span>
|
||||
{errors.manufacturer && errors.manufacturer.type !== "manual" && (
|
||||
<span style={errorTextStyle}>{errors.manufacturer.message}</span>
|
||||
)}
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
الموديل *
|
||||
<input
|
||||
style={inputStyle("model")}
|
||||
value={model}
|
||||
onChange={(e) => {
|
||||
setModel(e.target.value);
|
||||
clearFieldError("model");
|
||||
}}
|
||||
style={withError(!!errors.model)}
|
||||
{...register("model")}
|
||||
placeholder="لاند كروزر"
|
||||
dir="rtl"
|
||||
/>
|
||||
{errors.model && (
|
||||
<span style={errorTextStyle}>{errors.model}</span>
|
||||
)}
|
||||
{errors.model && <span style={errorTextStyle}>{errors.model.message}</span>}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "1fr 1fr 1fr",
|
||||
gap: "0.75rem",
|
||||
}}
|
||||
>
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "0.75rem" }}>
|
||||
<label style={labelStyle}>
|
||||
سنة الصنع *
|
||||
<input
|
||||
style={inputStyle("year")}
|
||||
style={withError(!!errors.year)}
|
||||
type="number"
|
||||
min={1900}
|
||||
max={new Date().getFullYear() + 1}
|
||||
value={year ?? ""}
|
||||
onChange={(e) => {
|
||||
setYear(parseNum(e.target.value));
|
||||
clearFieldError("year");
|
||||
}}
|
||||
{...numberField("year")}
|
||||
dir="ltr"
|
||||
/>
|
||||
{errors.year && <span style={errorTextStyle}>{errors.year}</span>}
|
||||
{errors.year && <span style={errorTextStyle}>{errors.year.message}</span>}
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
اللون
|
||||
<input
|
||||
style={inputBase}
|
||||
value={color}
|
||||
onChange={(e) => setColor(e.target.value)}
|
||||
placeholder="أبيض"
|
||||
dir="rtl"
|
||||
/>
|
||||
<input style={inputBase} {...register("color")} placeholder="أبيض" dir="rtl" />
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
نوع اللوحة
|
||||
<input
|
||||
style={inputBase}
|
||||
value={plateType}
|
||||
onChange={(e) => setPlateType(e.target.value)}
|
||||
placeholder="خاص"
|
||||
dir="rtl"
|
||||
/>
|
||||
<input style={inputBase} {...register("plateType")} placeholder="خاص" dir="rtl" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* ── Section: Plate ── */}
|
||||
<p
|
||||
style={{
|
||||
fontSize: 11,
|
||||
letterSpacing: "0.25em",
|
||||
textTransform: "uppercase",
|
||||
color: "var(--color-text-hint)",
|
||||
fontWeight: 700,
|
||||
margin: "0.5rem 0 0",
|
||||
}}
|
||||
>
|
||||
بيانات اللوحة
|
||||
</p>
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "1fr 1fr",
|
||||
gap: "0.75rem",
|
||||
}}
|
||||
>
|
||||
<p style={sectionHeadingStyle}>بيانات اللوحة</p>
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
|
||||
<label style={labelStyle}>
|
||||
رقم اللوحة *
|
||||
<input
|
||||
style={inputStyle("plateNumber")}
|
||||
value={plateNumber}
|
||||
onChange={(e) => {
|
||||
setPlateNumber(e.target.value);
|
||||
clearFieldError("plateNumber");
|
||||
}}
|
||||
style={withError(!!errors.plateNumber)}
|
||||
{...register("plateNumber")}
|
||||
placeholder="1234"
|
||||
dir="ltr"
|
||||
/>
|
||||
{errors.plateNumber && (
|
||||
<span style={errorTextStyle}>{errors.plateNumber}</span>
|
||||
<span style={errorTextStyle}>{errors.plateNumber.message}</span>
|
||||
)}
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
حروف اللوحة *
|
||||
<input
|
||||
style={inputStyle("plateLetters")}
|
||||
value={plateLetters}
|
||||
onChange={(e) => {
|
||||
setPlateLetters(e.target.value);
|
||||
clearFieldError("plateLetters");
|
||||
}}
|
||||
style={withError(!!errors.plateLetters)}
|
||||
{...register("plateLetters")}
|
||||
placeholder="أ ب ج"
|
||||
dir="rtl"
|
||||
/>
|
||||
{errors.plateLetters && (
|
||||
<span style={errorTextStyle}>{errors.plateLetters}</span>
|
||||
<span style={errorTextStyle}>{errors.plateLetters.message}</span>
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* ── Section: Registration & Legal ── */}
|
||||
<p
|
||||
style={{
|
||||
fontSize: 11,
|
||||
letterSpacing: "0.25em",
|
||||
textTransform: "uppercase",
|
||||
color: "var(--color-text-hint)",
|
||||
fontWeight: 700,
|
||||
margin: "0.5rem 0 0",
|
||||
}}
|
||||
>
|
||||
الترخيص والتأمين
|
||||
</p>
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "1fr 1fr",
|
||||
gap: "0.75rem",
|
||||
}}
|
||||
>
|
||||
<p style={sectionHeadingStyle}>الترخيص والتأمين</p>
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
|
||||
<label style={labelStyle}>
|
||||
رقم الاستمارة *
|
||||
<input
|
||||
style={inputStyle("registrationNumber")}
|
||||
value={registrationNumber}
|
||||
onChange={(e) => {
|
||||
setRegistrationNumber(e.target.value);
|
||||
clearFieldError("registrationNumber");
|
||||
}}
|
||||
style={withError(!!errors.registrationNumber)}
|
||||
{...register("registrationNumber")}
|
||||
placeholder="SA-001234"
|
||||
dir="ltr"
|
||||
/>
|
||||
{errors.registrationNumber && (
|
||||
<span style={errorTextStyle}>{errors.registrationNumber}</span>
|
||||
<span style={errorTextStyle}>{errors.registrationNumber.message}</span>
|
||||
)}
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
رقم الهيكل (VIN)
|
||||
<input
|
||||
style={inputStyle("vinNumber")}
|
||||
value={vinNumber}
|
||||
onChange={(e) => {
|
||||
setVinNumber(e.target.value);
|
||||
clearFieldError("vinNumber");
|
||||
}}
|
||||
style={withError(!!errors.vinNumber)}
|
||||
{...register("vinNumber")}
|
||||
placeholder="1HGBH41JXMN109186"
|
||||
dir="ltr"
|
||||
/>
|
||||
{errors.vinNumber && (
|
||||
<span style={errorTextStyle}>{errors.vinNumber}</span>
|
||||
<span style={errorTextStyle}>{errors.vinNumber.message}</span>
|
||||
)}
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
انتهاء الاستمارة
|
||||
<input
|
||||
style={inputBase}
|
||||
type="date"
|
||||
value={registrationExpiryDate}
|
||||
onChange={(e) => setRegistrationExpiryDate(e.target.value)}
|
||||
/>
|
||||
<input style={inputBase} type="date" {...register("registrationExpiryDate")} />
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
حالة التأمين
|
||||
<select
|
||||
style={{ ...inputBase, cursor: "pointer" }}
|
||||
value={insuranceStatus}
|
||||
onChange={(e) =>
|
||||
setInsuranceStatus(e.target.value as InsuranceStatus)
|
||||
}
|
||||
dir="rtl"
|
||||
>
|
||||
<select style={{ ...inputBase, cursor: "pointer" }} {...register("insuranceStatus")} dir="rtl">
|
||||
<option value="Valid">سارٍ</option>
|
||||
<option value="Expired">منتهي</option>
|
||||
<option value="NotInsured">غير مؤمَّن</option>
|
||||
@@ -611,52 +480,20 @@ const loadBranches = useCallback(() => {
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
انتهاء التأمين
|
||||
<input
|
||||
style={inputBase}
|
||||
type="date"
|
||||
value={insuranceExpiryDate}
|
||||
onChange={(e) => setInsuranceExpiryDate(e.target.value)}
|
||||
/>
|
||||
<input style={inputBase} type="date" {...register("insuranceExpiryDate")} />
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
انتهاء الفحص الدوري
|
||||
<input
|
||||
style={inputBase}
|
||||
type="date"
|
||||
value={inspectionExpiryDate}
|
||||
onChange={(e) => setInspectionExpiryDate(e.target.value)}
|
||||
/>
|
||||
<input style={inputBase} type="date" {...register("inspectionExpiryDate")} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* ── Section: Operational ── */}
|
||||
<p
|
||||
style={{
|
||||
fontSize: 11,
|
||||
letterSpacing: "0.25em",
|
||||
textTransform: "uppercase",
|
||||
color: "var(--color-text-hint)",
|
||||
fontWeight: 700,
|
||||
margin: "0.5rem 0 0",
|
||||
}}
|
||||
>
|
||||
بيانات تشغيلية
|
||||
</p>
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "1fr 1fr 1fr",
|
||||
gap: "0.75rem",
|
||||
}}
|
||||
>
|
||||
<p style={sectionHeadingStyle}>بيانات تشغيلية</p>
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "0.75rem" }}>
|
||||
<label style={labelStyle}>
|
||||
الفرع
|
||||
<select
|
||||
style={{ ...inputBase, cursor: "pointer" }}
|
||||
value={branchId}
|
||||
onChange={(e) => setBranchId(e.target.value)}
|
||||
dir="rtl"
|
||||
>
|
||||
<select style={{ ...inputBase, cursor: "pointer" }} {...register("branchId")} dir="rtl">
|
||||
<option value="">اختر الفرع</option>
|
||||
{branches.map((b) => (
|
||||
<option key={b.id} value={b.id}>
|
||||
@@ -667,14 +504,7 @@ const loadBranches = useCallback(() => {
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
الحالة
|
||||
<select
|
||||
style={{ ...inputBase, cursor: "pointer" }}
|
||||
value={currentStatus}
|
||||
onChange={(e) =>
|
||||
setCurrentStatus(e.target.value as Car["currentStatus"])
|
||||
}
|
||||
dir="rtl"
|
||||
>
|
||||
<select style={{ ...inputBase, cursor: "pointer" }} {...register("currentStatus")} dir="rtl">
|
||||
<option value="Active">نشط</option>
|
||||
<option value="InMaintenance">صيانة</option>
|
||||
<option value="InTrip">في رحلة</option>
|
||||
@@ -683,65 +513,42 @@ const loadBranches = useCallback(() => {
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
رقم GPS
|
||||
<input
|
||||
style={inputBase}
|
||||
value={gpsDeviceId}
|
||||
onChange={(e) => setGpsDeviceId(e.target.value)}
|
||||
placeholder="GPS-001"
|
||||
dir="ltr"
|
||||
/>
|
||||
<input style={inputBase} {...register("gpsDeviceId")} placeholder="GPS-001" dir="ltr" />
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
الطاقة الاستيعابية
|
||||
<input
|
||||
style={inputStyle("capacity")}
|
||||
style={withError(!!errors.capacity)}
|
||||
type="number"
|
||||
min={0}
|
||||
value={capacity ?? ""}
|
||||
onChange={(e) => {
|
||||
setCapacity(parseNum(e.target.value));
|
||||
clearFieldError("capacity");
|
||||
}}
|
||||
{...numberField("capacity")}
|
||||
placeholder="0"
|
||||
dir="ltr"
|
||||
/>
|
||||
{errors.capacity && (
|
||||
<span style={errorTextStyle}>{errors.capacity}</span>
|
||||
<span style={errorTextStyle}>{errors.capacity.message}</span>
|
||||
)}
|
||||
</label>
|
||||
<label style={labelStyle}>
|
||||
الوزن (كجم)
|
||||
<input
|
||||
style={inputStyle("weight")}
|
||||
style={withError(!!errors.weight)}
|
||||
type="number"
|
||||
min={0}
|
||||
value={weight ?? ""}
|
||||
onChange={(e) => {
|
||||
setWeight(parseNum(e.target.value));
|
||||
clearFieldError("weight");
|
||||
}}
|
||||
{...numberField("weight")}
|
||||
placeholder="0"
|
||||
dir="ltr"
|
||||
/>
|
||||
{errors.weight && (
|
||||
<span style={errorTextStyle}>{errors.weight}</span>
|
||||
)}
|
||||
{errors.weight && <span style={errorTextStyle}>{errors.weight.message}</span>}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* ── 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",
|
||||
@@ -751,7 +558,7 @@ const loadBranches = useCallback(() => {
|
||||
fontSize: 13,
|
||||
fontWeight: 600,
|
||||
color: "var(--color-text-secondary)",
|
||||
cursor: saving ? "not-allowed" : "pointer",
|
||||
cursor: isSubmitting ? "not-allowed" : "pointer",
|
||||
fontFamily: "var(--font-sans)",
|
||||
}}
|
||||
>
|
||||
@@ -759,35 +566,29 @@ const loadBranches = useCallback(() => {
|
||||
</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>
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user