finsh user,car,driver pages also add validator layer to app build trip page

This commit is contained in:
m7amedez5511
2026-06-18 16:51:31 +03:00
parent a23d21f222
commit c1b77f89cd
45 changed files with 4128 additions and 1690 deletions

View File

@@ -1,12 +1,14 @@
"use client";
import { useEffect, useRef, useState } from "react";
import * as yup from "yup";
import { Alert, Spinner } from "../UI";
import { createUserSchema, updateUserSchema } from "@/validations/user.validator";
import type { Branch } from "../../types/branch";
import type { Role } from "../../types/role";
import type { FormErrors, User, UserFormData } from "../../types/user";
// ── fixed styles ─────────────────────────────────────────────────
// ── fixed styles ─────────────────────────────────────────
const S = {
input: {
width: "100%", height: 40, padding: "0 0.75rem",
@@ -24,26 +26,27 @@ const S = {
errorText: { fontSize: 11, color: "var(--color-danger)", fontWeight: 500 } as React.CSSProperties,
};
// ── macksure data validation ─────────────────────────────────────────────────────
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const PHONE_RE = /^\+?[0-9]{10,15}$/;
function validate(data: UserFormData, isNew: boolean): FormErrors {
const e: FormErrors = {};
if (!data.name.trim()) e.name = "الاسم الكامل مطلوب";
if (data.email && !EMAIL_RE.test(data.email)) e.email = "صيغة البريد الإلكتروني غير صحيحة";
if (!data.phone.trim()) e.phone = "رقم الهاتف مطلوب";
else if (!PHONE_RE.test(data.phone.replace(/\s/g, ""))) e.phone = "رقم هاتف غير صالح (1015 رقم)";
if (isNew && !data.password) e.password = "كلمة المرور مطلوبة";
if (isNew && data.password && data.password.length < 6) e.password = "كلمة المرور 6 أحرف على الأقل";
if (!data.roleId) e.roleId = "الدور مطلوب";
if (!data.branchId) e.branchId = "الفرع مطلوب";
return e;
// ── yup validation ────────────────────────────────────────────────────────────
async function validate(data: UserFormData, isNew: boolean): Promise<FormErrors> {
const schema = isNew ? createUserSchema : updateUserSchema;
try {
await schema.validate(data, { abortEarly: false });
return {};
} catch (err) {
if (err instanceof yup.ValidationError) {
return err.inner.reduce<FormErrors>((acc, e) => {
const field = e.path as keyof FormErrors;
if (field && !acc[field]) acc[field] = e.message;
return acc;
}, {});
}
return {};
}
}
// ── Props ─────────────────────────────────────────────────────────────────────
interface UserFormModalProps {
editUser: User | null;
editUser: User | null;
roles: Role[];
branches: Branch[];
onClose: () => void;
@@ -55,12 +58,12 @@ export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }:
const isNew = editUser === null;
const [form, setForm] = useState<UserFormData>({
name: editUser?.name ?? "",
email: editUser?.email ?? "",
phone: editUser?.phone ?? "",
name: editUser?.name ?? "",
email: editUser?.email ?? "",
phone: editUser?.phone ?? "",
password: "",
roleId: editUser?.role?.id ?? "",
branchId: editUser?.branch?.id ?? "",
roleId: editUser?.role?.id ?? "",
branchId: editUser?.branch?.id ?? "",
});
const [errors, setErrors] = useState<FormErrors>({});
const [saving, setSaving] = useState(false);
@@ -77,22 +80,24 @@ export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }:
const set = (field: keyof UserFormData) =>
(e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
setForm(p => ({ ...p, [field]: e.target.value }));
// clear field error on change
if (errors[field]) setErrors(p => ({ ...p, [field]: undefined }));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
// makesure data is valid before sending to API
const errs = validate(form, isNew);
const errs = await validate(
!isNew && !form.password
? { ...form, password: undefined as unknown as string }
: form,
isNew,
);
if (Object.keys(errs).length) { setErrors(errs); return; }
// final check to prevent sending bad data to API (shouldn't happen because of validation, but just in case)
if (!form.name.trim() || !form.phone.trim() || !form.roleId || !form.branchId) {
setApiError("يرجى التأكد من إدخال جميع البيانات المطلوبة.");
return;
}
setSaving(true);
setApiError("");
const ok = await onSubmit(form, isNew);
const payload: Partial<UserFormData> = { ...form };
if (!isNew && !payload.password) delete payload.password;
const ok = await onSubmit(payload as UserFormData, isNew);
setSaving(false);
if (ok) onClose();
else setApiError("حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.");
@@ -146,18 +151,18 @@ export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }:
</button>
</div>
{/* body*/}
{/* body */}
<form onSubmit={handleSubmit} noValidate style={{ padding: "1.5rem", display: "flex", flexDirection: "column", gap: "1rem" }}>
{apiError && <Alert type="error" message={apiError} onClose={() => setApiError("")} />}
{/* name field*/}
{/* name */}
<label style={S.label}>
الاسم الكامل *
<input ref={firstInputRef} style={inputStyle("name")} value={form.name} onChange={set("name")} placeholder="أحمد الرشيدي" autoComplete="name" dir="rtl" />
{errors.name && <span style={S.errorText}>{errors.name}</span>}
</label>
{/* email and phone fields */}
{/* email + phone */}
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
<label style={S.label}>
البريد الإلكتروني
@@ -171,14 +176,14 @@ export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }:
</label>
</div>
{/* password field */}
{/* password */}
<label style={S.label}>
{isNew ? "كلمة المرور *" : "كلمة المرور الجديدة (اتركها فارغة إذا لا تريد تغييرها)"}
<input style={inputStyle("password")} type="password" value={form.password} onChange={set("password")} placeholder="••••••••" autoComplete={isNew ? "new-password" : "off"} dir="ltr" />
{errors.password && <span style={S.errorText}>{errors.password}</span>}
</label>
{/* role and branch fields */}
{/* role + branch */}
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
<label style={S.label}>
الدور *
@@ -198,7 +203,7 @@ export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }:
</label>
</div>
{/* action buttons */}
{/* actions */}
<div style={{ display: "flex", gap: "0.5rem", justifyContent: "flex-end", paddingTop: "0.5rem" }}>
<button type="button" onClick={onClose} disabled={saving}
style={{ height: 40, padding: "0 1.25rem", borderRadius: "var(--radius-md)", border: "1px solid var(--color-border)", background: "var(--color-surface)", fontSize: 13, fontWeight: 600, color: "var(--color-text-secondary)", cursor: saving ? "not-allowed" : "pointer", fontFamily: "var(--font-sans)" }}>