refactor(forms): migrate form modals to react-hook-form + yupResolver, and adopt shared UI kit components across Role/Order/User/Trip modals and tables
Replace manual useState + validate() wiring with react-hook-form and
yupResolver across CarFormModal, DriverFormModal, Tripformmodal,
OrderFormModal, BranchFormModal, CarMaintananceFormModal, RoleFormModal,
and UserFormModal, following the existing pattern in Addressformmodal.
- Pin yupResolver's generic explicitly (yupResolver<FormValues>(schema as any))
since create/update schemas differ structurally and yup can't unify them
into a single inferred type on its own.
- Replace manual ref-based autofocus (useRef + ref={firstRef}) with
autoFocus/setFocus to avoid ref collisions with register()'s own ref.
- DriverFormModal: bind photo/nationalPhoto/driverCardPhoto file fields via
Controller instead of register.
- Tripformmodal: convert startTime/endTime to ISO-8601 via setValueAs while
keeping the datetime-local input display unaffected.
- OrderFormModal: register nested deliveryAddress/pickupAddress fields via
dot-path syntax; keep pickupMode as local state; preserve conditional
address payload assembly.
- CarMaintananceFormModal: keep toNumberOrUndefined cost coercion and
ISO-8601 date conversion at submit time.
- RoleFormModal: bind permissionIds checkbox group via Controller.
- UserFormModal: add a custom resolver wrapper to preserve the
empty-password-on-edit behavior (skip password validation when editing
with a blank password field).
Also replace raw HTML elements with the shared UI kit components
(Modal, Input, Textarea, Select, Button, Alert, Badge, EmptyState) across
form modals, detail modals, and tables:
- RoleFormModal: Modal, Input, Textarea, Button
- OrderFormModal: Modal, Input, Select, Button
- UserDetailModal / Archiveduserdetailmodal: Modal, Alert, Button
- UserTable / Archivedusertable: Badge, Button, EmptyState
- RoleDetailModal / ArchivedRoleDetailModal: Modal, Alert, Select, Button
- RoleTable / ArchivedRoleTable: Button, EmptyState
- Tripreportpanel: Button with built-in loading state instead of manual
Spinner/disabled/color wiring
StatusBadge, IconBtn, and other per-action custom chips/checkboxes are kept
as-is in every file — the shared Badge/Button components don't support dot
indicators or per-action color-coding, so forcing them in would misshape or
strip semantics from these controls.
Archivedusersmodal, ArchivedRolesModal, and ArchivedTripList required no
changes — already fully compliant with the shared UI kit.
No changes to visual layout, CSS, or Arabic labels/section headings beyond
what's required by the component swaps above.
This commit is contained in:
@@ -1,31 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import * as yup from "yup";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { yupResolver } from "@hookform/resolvers/yup";
|
||||
import { Alert, Button, Input, Modal } from "../UI";
|
||||
import { createBranchSchema, updateBranchSchema } from "@/src/validations/branch.validator";
|
||||
import type { Branch, BranchFormData, FormErrors } from "@/src/types/branch";
|
||||
import type { Branch, BranchFormData } from "@/src/types/branch";
|
||||
|
||||
const FORM_ID = "branch-form";
|
||||
|
||||
// ── yup validation ────────────────────────────────────────────────────────────
|
||||
async function validate(data: BranchFormData, isNew: boolean): Promise<FormErrors> {
|
||||
const schema = isNew ? createBranchSchema : updateBranchSchema;
|
||||
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 BranchFormModalProps {
|
||||
editBranch: Branch | null;
|
||||
@@ -37,45 +19,41 @@ interface BranchFormModalProps {
|
||||
export function BranchFormModal({ editBranch, onClose, onSubmit }: BranchFormModalProps) {
|
||||
const isNew = editBranch === null;
|
||||
|
||||
const [form, setForm] = useState<BranchFormData>({
|
||||
name: editBranch?.name ?? "",
|
||||
email: editBranch?.email ?? "",
|
||||
phone: editBranch?.phone ?? "",
|
||||
country: editBranch?.country ?? "SA",
|
||||
city: editBranch?.city ?? "",
|
||||
state: editBranch?.state ?? "",
|
||||
district: editBranch?.district ?? "",
|
||||
street: editBranch?.street ?? "",
|
||||
buildingNo: editBranch?.buildingNo ?? "",
|
||||
unitNo: editBranch?.unitNo ?? "",
|
||||
zipCode: editBranch?.zipCode ?? "",
|
||||
latitude: editBranch?.latitude != null ? String(editBranch.latitude) : "",
|
||||
longitude: editBranch?.longitude != null ? String(editBranch.longitude) : "",
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
setError,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<BranchFormData>({
|
||||
// Cast the schema itself and pin the generic explicitly on yupResolver —
|
||||
// create/update schemas differ structurally in which fields are required
|
||||
// (e.g. city/street are optional on update), so yup can't unify them
|
||||
// into the single flat BranchFormData shape on its own.
|
||||
resolver: yupResolver<BranchFormData>((isNew ? createBranchSchema : updateBranchSchema) as any),
|
||||
defaultValues: {
|
||||
name: editBranch?.name ?? "",
|
||||
email: editBranch?.email ?? "",
|
||||
phone: editBranch?.phone ?? "",
|
||||
country: editBranch?.country ?? "SA",
|
||||
city: editBranch?.city ?? "",
|
||||
state: editBranch?.state ?? "",
|
||||
district: editBranch?.district ?? "",
|
||||
street: editBranch?.street ?? "",
|
||||
buildingNo: editBranch?.buildingNo ?? "",
|
||||
unitNo: editBranch?.unitNo ?? "",
|
||||
zipCode: editBranch?.zipCode ?? "",
|
||||
latitude: editBranch?.latitude != null ? String(editBranch.latitude) : "",
|
||||
longitude: editBranch?.longitude != null ? String(editBranch.longitude) : "",
|
||||
},
|
||||
});
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [apiError, setApiError] = useState("");
|
||||
const firstInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => { firstInputRef.current?.focus(); }, []);
|
||||
|
||||
const set = (field: keyof BranchFormData) =>
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
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();
|
||||
const errs = await validate(form, isNew);
|
||||
if (Object.keys(errs).length) { setErrors(errs); return; }
|
||||
setSaving(true);
|
||||
setApiError("");
|
||||
const ok = await onSubmit(form, isNew);
|
||||
setSaving(false);
|
||||
if (ok) onClose();
|
||||
else setApiError("حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.");
|
||||
const submitHandler = async (data: BranchFormData) => {
|
||||
const ok = await onSubmit(data, isNew);
|
||||
if (ok) {
|
||||
onClose();
|
||||
} else {
|
||||
setError("name", { message: "حدث خطأ غير متوقع. يرجى المحاولة لاحقاً." });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -87,10 +65,10 @@ export function BranchFormModal({ editBranch, onClose, onSubmit }: BranchFormMod
|
||||
size="md"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={saving}>
|
||||
<Button variant="secondary" onClick={onClose} disabled={isSubmitting}>
|
||||
إلغاء
|
||||
</Button>
|
||||
<Button type="submit" form={FORM_ID} loading={saving}>
|
||||
<Button type="submit" form={FORM_ID} loading={isSubmitting}>
|
||||
{isNew ? "إضافة الفرع" : "حفظ التغييرات"}
|
||||
</Button>
|
||||
</>
|
||||
@@ -98,21 +76,22 @@ export function BranchFormModal({ editBranch, onClose, onSubmit }: BranchFormMod
|
||||
>
|
||||
<form
|
||||
id={FORM_ID}
|
||||
onSubmit={handleSubmit}
|
||||
onSubmit={handleSubmit(submitHandler)}
|
||||
noValidate
|
||||
style={{ display: "flex", flexDirection: "column", gap: "1rem" }}
|
||||
>
|
||||
{apiError && <Alert type="error" message={apiError} onClose={() => setApiError("")} />}
|
||||
{errors.name?.type === "manual" && (
|
||||
<Alert type="error" message={errors.name.message ?? ""} onClose={() => {}} />
|
||||
)}
|
||||
|
||||
{/* name */}
|
||||
<Input
|
||||
ref={firstInputRef}
|
||||
label="اسم الفرع *"
|
||||
value={form.name}
|
||||
onChange={set("name")}
|
||||
error={errors.name}
|
||||
{...register("name")}
|
||||
error={errors.name && errors.name.type !== "manual" ? errors.name.message : undefined}
|
||||
placeholder="فرع الرياض"
|
||||
autoComplete="organization"
|
||||
autoFocus
|
||||
dir="rtl"
|
||||
/>
|
||||
|
||||
@@ -121,9 +100,8 @@ export function BranchFormModal({ editBranch, onClose, onSubmit }: BranchFormMod
|
||||
<Input
|
||||
label="البريد الإلكتروني"
|
||||
type="email"
|
||||
value={form.email}
|
||||
onChange={set("email")}
|
||||
error={errors.email}
|
||||
{...register("email")}
|
||||
error={errors.email?.message}
|
||||
placeholder="branch@co.sa"
|
||||
autoComplete="email"
|
||||
dir="ltr"
|
||||
@@ -131,9 +109,8 @@ export function BranchFormModal({ editBranch, onClose, onSubmit }: BranchFormMod
|
||||
<Input
|
||||
label="رقم الهاتف"
|
||||
type="tel"
|
||||
value={form.phone}
|
||||
onChange={set("phone")}
|
||||
error={errors.phone}
|
||||
{...register("phone")}
|
||||
error={errors.phone?.message}
|
||||
placeholder="+966 5x xxx xxxx"
|
||||
autoComplete="tel"
|
||||
dir="ltr"
|
||||
@@ -144,17 +121,15 @@ export function BranchFormModal({ editBranch, onClose, onSubmit }: BranchFormMod
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
|
||||
<Input
|
||||
label="المدينة *"
|
||||
value={form.city}
|
||||
onChange={set("city")}
|
||||
error={errors.city}
|
||||
{...register("city")}
|
||||
error={errors.city?.message}
|
||||
placeholder="الرياض"
|
||||
dir="rtl"
|
||||
/>
|
||||
<Input
|
||||
label="الشارع *"
|
||||
value={form.street}
|
||||
onChange={set("street")}
|
||||
error={errors.street}
|
||||
{...register("street")}
|
||||
error={errors.street?.message}
|
||||
placeholder="شارع الملك فهد"
|
||||
dir="rtl"
|
||||
/>
|
||||
@@ -164,17 +139,15 @@ export function BranchFormModal({ editBranch, onClose, onSubmit }: BranchFormMod
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
|
||||
<Input
|
||||
label="المنطقة"
|
||||
value={form.state}
|
||||
onChange={set("state")}
|
||||
error={errors.state}
|
||||
{...register("state")}
|
||||
error={errors.state?.message}
|
||||
placeholder="منطقة الرياض"
|
||||
dir="rtl"
|
||||
/>
|
||||
<Input
|
||||
label="الحي"
|
||||
value={form.district}
|
||||
onChange={set("district")}
|
||||
error={errors.district}
|
||||
{...register("district")}
|
||||
error={errors.district?.message}
|
||||
placeholder="حي العليا"
|
||||
dir="rtl"
|
||||
/>
|
||||
@@ -184,25 +157,22 @@ export function BranchFormModal({ editBranch, onClose, onSubmit }: BranchFormMod
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "0.75rem" }}>
|
||||
<Input
|
||||
label="رقم المبنى"
|
||||
value={form.buildingNo}
|
||||
onChange={set("buildingNo")}
|
||||
error={errors.buildingNo}
|
||||
{...register("buildingNo")}
|
||||
error={errors.buildingNo?.message}
|
||||
placeholder="1234"
|
||||
dir="ltr"
|
||||
/>
|
||||
<Input
|
||||
label="رقم الوحدة"
|
||||
value={form.unitNo}
|
||||
onChange={set("unitNo")}
|
||||
error={errors.unitNo}
|
||||
{...register("unitNo")}
|
||||
error={errors.unitNo?.message}
|
||||
placeholder="5"
|
||||
dir="ltr"
|
||||
/>
|
||||
<Input
|
||||
label="الرمز البريدي"
|
||||
value={form.zipCode}
|
||||
onChange={set("zipCode")}
|
||||
error={errors.zipCode}
|
||||
{...register("zipCode")}
|
||||
error={errors.zipCode?.message}
|
||||
placeholder="12345"
|
||||
dir="ltr"
|
||||
/>
|
||||
@@ -211,9 +181,8 @@ export function BranchFormModal({ editBranch, onClose, onSubmit }: BranchFormMod
|
||||
{/* country */}
|
||||
<Input
|
||||
label="الدولة"
|
||||
value={form.country}
|
||||
onChange={set("country")}
|
||||
error={errors.country}
|
||||
{...register("country")}
|
||||
error={errors.country?.message}
|
||||
placeholder="SA"
|
||||
dir="ltr"
|
||||
/>
|
||||
@@ -222,18 +191,16 @@ export function BranchFormModal({ editBranch, onClose, onSubmit }: BranchFormMod
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
|
||||
<Input
|
||||
label="خط العرض (اختياري)"
|
||||
value={form.latitude}
|
||||
onChange={set("latitude")}
|
||||
error={errors.latitude}
|
||||
{...register("latitude")}
|
||||
error={errors.latitude?.message}
|
||||
placeholder="24.7136"
|
||||
dir="ltr"
|
||||
inputMode="decimal"
|
||||
/>
|
||||
<Input
|
||||
label="خط الطول (اختياري)"
|
||||
value={form.longitude}
|
||||
onChange={set("longitude")}
|
||||
error={errors.longitude}
|
||||
{...register("longitude")}
|
||||
error={errors.longitude?.message}
|
||||
placeholder="46.6753"
|
||||
dir="ltr"
|
||||
inputMode="decimal"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import * as yup from "yup";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { yupResolver } from "@hookform/resolvers/yup";
|
||||
import { Alert, Button, Input, Modal } from "../UI";
|
||||
import {
|
||||
createMaintenanceSchema,
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
import type {
|
||||
CarMaintenance,
|
||||
CreateMaintenancePayload,
|
||||
MaintenanceFormErrors,
|
||||
UpdateMaintenancePayload,
|
||||
} from "@/src/types/carMaintanance";
|
||||
|
||||
@@ -19,11 +18,8 @@ const FORM_ID = "maintenance-form";
|
||||
// ── Number coercion helper ────────────────────────────────────────────────────
|
||||
// The backend can return `cost` as a numeric string (common with Decimal
|
||||
// columns getting JSON-serialized as strings), even though our TS type says
|
||||
// `number`. If that untouched value round-trips back out on update without
|
||||
// ever passing through the `<input type="number">` onChange handler, it
|
||||
// stays a string and fails the backend's strict `z.number()` check. Coerce
|
||||
// defensively both when hydrating the form AND right before building the
|
||||
// submit payload, so this can never happen regardless of the source.
|
||||
// `number`. Coerce defensively both when hydrating the form AND right before
|
||||
// building the submit payload, so this can never slip through as a string.
|
||||
|
||||
function toNumberOrUndefined(v: unknown): number | undefined {
|
||||
if (v === undefined || v === null || v === "") return undefined;
|
||||
@@ -31,30 +27,6 @@ function toNumberOrUndefined(v: unknown): number | undefined {
|
||||
return Number.isNaN(n) ? undefined : n;
|
||||
}
|
||||
|
||||
// ── yup validation ────────────────────────────────────────────────────────────
|
||||
// Checks the form values against the right schema and turns any problems
|
||||
// into a simple field -> message map the inputs below can read from.
|
||||
|
||||
async function validate(
|
||||
form: Partial<CreateMaintenancePayload>,
|
||||
isNew: boolean,
|
||||
): Promise<MaintenanceFormErrors> {
|
||||
const schema = isNew ? createMaintenanceSchema : updateMaintenanceSchema;
|
||||
try {
|
||||
await schema.validate(form, { abortEarly: false });
|
||||
return {};
|
||||
} catch (err) {
|
||||
if (err instanceof yup.ValidationError) {
|
||||
return err.inner.reduce<MaintenanceFormErrors>((acc, e) => {
|
||||
const field = e.path as keyof MaintenanceFormErrors;
|
||||
if (field && !acc[field]) acc[field] = e.message;
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
// ── Date helper ───────────────────────────────────────────────────────────────
|
||||
// <input type="date"> gives "YYYY-MM-DD"; the backend expects full ISO-8601.
|
||||
|
||||
@@ -64,6 +36,19 @@ function toIsoDateTime(val: string): string {
|
||||
return `${val}T00:00:00.000Z`;
|
||||
}
|
||||
|
||||
// ── Form values shape ────────────────────────────────────────────────────────
|
||||
// `cost` stays number | undefined (via setValueAs) so an empty input maps to
|
||||
// `undefined` rather than NaN; startAt/endAt stay as raw "YYYY-MM-DD" strings
|
||||
// while typed — yup's dateString test accepts that format directly — and are
|
||||
// only converted to full ISO-8601 right before the payload is built.
|
||||
|
||||
interface MaintenanceFormValues {
|
||||
reason: string;
|
||||
cost: number | undefined;
|
||||
startAt: string;
|
||||
endAt: string;
|
||||
}
|
||||
|
||||
// ── Props ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface CarMaintenanceFormModalProps {
|
||||
@@ -88,64 +73,52 @@ export function CarMaintenanceFormModal({
|
||||
}: CarMaintenanceFormModalProps) {
|
||||
const isNew = editRecord === null;
|
||||
|
||||
// ── Form state ─────────────────────────────────────────────────────────────
|
||||
const [reason, setReason] = useState(editRecord?.reason ?? "");
|
||||
// Coerced defensively: editRecord.cost may arrive as a numeric string from
|
||||
// the backend (e.g. a Decimal column serialized to JSON as "150").
|
||||
const [cost, setCost] = useState<number | undefined>(toNumberOrUndefined(editRecord?.cost));
|
||||
const [startAt, setStartAt] = useState(editRecord?.startAt?.slice(0, 10) ?? "");
|
||||
const [endAt, setEndAt] = useState(editRecord?.endAt?.slice(0, 10) ?? "");
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
setError,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<MaintenanceFormValues>({
|
||||
// Cast the schema itself and pin the generic explicitly — create/update
|
||||
// schemas differ structurally in which fields are required, so yup can't
|
||||
// unify them into MaintenanceFormValues on its own.
|
||||
resolver: yupResolver<MaintenanceFormValues>(
|
||||
(isNew ? createMaintenanceSchema : updateMaintenanceSchema) as any,
|
||||
),
|
||||
defaultValues: {
|
||||
reason: editRecord?.reason ?? "",
|
||||
// Coerced defensively: editRecord.cost may arrive as a numeric string
|
||||
// from the backend (e.g. a Decimal column serialized to JSON as "150").
|
||||
cost: toNumberOrUndefined(editRecord?.cost),
|
||||
startAt: editRecord?.startAt?.slice(0, 10) ?? "",
|
||||
endAt: editRecord?.endAt?.slice(0, 10) ?? "",
|
||||
},
|
||||
});
|
||||
|
||||
const [errors, setErrors] = useState<MaintenanceFormErrors>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [apiError, setApiError] = useState("");
|
||||
const firstRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => { firstRef.current?.focus(); }, []);
|
||||
|
||||
const parseNum = (v: string): number | undefined =>
|
||||
v.trim() === "" ? undefined : Number(v);
|
||||
|
||||
const clearFieldError = (field: keyof MaintenanceFormErrors) =>
|
||||
setErrors((p) => ({ ...p, [field]: undefined }));
|
||||
const costField = register("cost", {
|
||||
setValueAs: (v) => (v === "" || v === null ? undefined : Number(v)),
|
||||
});
|
||||
|
||||
// ── Submit ────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
const submitHandler = async (data: MaintenanceFormValues) => {
|
||||
// Belt-and-braces: re-coerce cost right before it's used, in case it
|
||||
// somehow slipped back into a string (e.g. untouched value hydrated
|
||||
// from a record whose `cost` came back as a numeric string).
|
||||
const safeCost = toNumberOrUndefined(cost);
|
||||
// somehow slipped back into a string.
|
||||
const safeCost = toNumberOrUndefined(data.cost);
|
||||
|
||||
// Build a snapshot for yup — include everything so optional rules also run.
|
||||
const formSnapshot: Partial<CreateMaintenancePayload> = {
|
||||
reason,
|
||||
cost: safeCost,
|
||||
...(startAt && { startAt }),
|
||||
...(endAt && { endAt }),
|
||||
};
|
||||
|
||||
const errs = await validate(formSnapshot, isNew);
|
||||
if (Object.keys(errs).length) {
|
||||
setErrors(errs);
|
||||
return;
|
||||
}
|
||||
|
||||
// Build the final payload — dates go out as full ISO-8601 strings, and
|
||||
// cost always goes out as a real number, never a string.
|
||||
const raw: Record<string, unknown> = { reason, cost: safeCost };
|
||||
if (startAt) raw.startAt = toIsoDateTime(startAt);
|
||||
if (endAt) raw.endAt = toIsoDateTime(endAt);
|
||||
// Dates go out as full ISO-8601 strings, and cost always goes out as a
|
||||
// real number, never a string.
|
||||
const raw: Record<string, unknown> = { reason: data.reason, cost: safeCost };
|
||||
if (data.startAt) raw.startAt = toIsoDateTime(data.startAt);
|
||||
if (data.endAt) raw.endAt = toIsoDateTime(data.endAt);
|
||||
|
||||
const payload = raw as unknown as CreateMaintenancePayload;
|
||||
setSaving(true);
|
||||
setApiError("");
|
||||
const ok = await onSubmit(payload, isNew);
|
||||
setSaving(false);
|
||||
if (ok) onClose();
|
||||
else setApiError("حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.");
|
||||
if (ok) {
|
||||
onClose();
|
||||
} else {
|
||||
setError("reason", { message: "حدث خطأ غير متوقع. يرجى المحاولة لاحقاً." });
|
||||
}
|
||||
};
|
||||
|
||||
// ── Render ────────────────────────────────────────────────────────────────
|
||||
@@ -159,10 +132,10 @@ export function CarMaintenanceFormModal({
|
||||
title={carLabel ?? (isNew ? "سجل صيانة جديد" : "تعديل السجل")}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" type="button" onClick={onClose} disabled={saving}>
|
||||
<Button variant="secondary" type="button" onClick={onClose} disabled={isSubmitting}>
|
||||
إلغاء
|
||||
</Button>
|
||||
<Button type="submit" form={FORM_ID} loading={saving}>
|
||||
<Button type="submit" form={FORM_ID} loading={isSubmitting}>
|
||||
{isNew ? "إضافة السجل" : "حفظ التغييرات"}
|
||||
</Button>
|
||||
</>
|
||||
@@ -170,21 +143,22 @@ export function CarMaintenanceFormModal({
|
||||
>
|
||||
<form
|
||||
id={FORM_ID}
|
||||
onSubmit={handleSubmit}
|
||||
onSubmit={handleSubmit(submitHandler)}
|
||||
noValidate
|
||||
dir="rtl"
|
||||
className="flex flex-col gap-4"
|
||||
>
|
||||
{apiError && <Alert type="error" message={apiError} onClose={() => setApiError("")} />}
|
||||
{errors.reason?.type === "manual" && (
|
||||
<Alert type="error" message={errors.reason.message ?? ""} onClose={() => {}} />
|
||||
)}
|
||||
|
||||
<Input
|
||||
ref={firstRef}
|
||||
label="سبب الصيانة *"
|
||||
value={reason}
|
||||
onChange={(e) => { setReason(e.target.value); clearFieldError("reason"); }}
|
||||
{...register("reason")}
|
||||
error={errors.reason && errors.reason.type !== "manual" ? errors.reason.message : undefined}
|
||||
placeholder="تغيير زيت المحرك"
|
||||
dir="rtl"
|
||||
error={errors.reason}
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
@@ -192,28 +166,25 @@ export function CarMaintenanceFormModal({
|
||||
label="التكلفة (ر.س) *"
|
||||
type="number"
|
||||
min={0}
|
||||
value={cost ?? ""}
|
||||
onChange={(e) => { setCost(parseNum(e.target.value)); clearFieldError("cost"); }}
|
||||
{...costField}
|
||||
error={errors.cost?.message}
|
||||
placeholder="0"
|
||||
dir="ltr"
|
||||
error={errors.cost}
|
||||
/>
|
||||
|
||||
<Input
|
||||
label="تاريخ البدء *"
|
||||
type="date"
|
||||
value={startAt}
|
||||
onChange={(e) => { setStartAt(e.target.value); clearFieldError("startAt"); }}
|
||||
error={errors.startAt}
|
||||
{...register("startAt")}
|
||||
error={errors.startAt?.message}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
label="تاريخ الانتهاء"
|
||||
type="date"
|
||||
value={endAt}
|
||||
onChange={(e) => { setEndAt(e.target.value); clearFieldError("endAt"); }}
|
||||
error={errors.endAt}
|
||||
{...register("endAt")}
|
||||
error={errors.endAt?.message}
|
||||
hint="اتركه فارغاً إذا كانت الصيانة ما زالت جارية."
|
||||
/>
|
||||
</form>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { Spinner ,Toast} from "../UI";
|
||||
import { Button, Toast } from "../UI";
|
||||
import { tripService } from "@/src/services/trip.service";
|
||||
import { getStoredToken } from "@/src/lib/auth";
|
||||
import type { TripNotification } from "@/src/hooks/useTrip";
|
||||
@@ -78,30 +78,9 @@ export function TripReportPanel({ tripId }: TripReportPanelProps) {
|
||||
إنشاء تقرير الرحلة
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleGenerate}
|
||||
disabled={loading}
|
||||
style={{
|
||||
height: 38,
|
||||
padding: "0 1.25rem",
|
||||
borderRadius: "var(--radius-md)",
|
||||
border: "none",
|
||||
fontSize: 13,
|
||||
fontWeight: 700,
|
||||
color: "#FFF",
|
||||
background: loading ? "var(--color-brand-400)" : "var(--color-brand-600)",
|
||||
cursor: loading ? "not-allowed" : "pointer",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
fontFamily: "var(--font-sans)",
|
||||
whiteSpace: "nowrap",
|
||||
}}
|
||||
>
|
||||
{loading && <Spinner size="sm" className="text-white" />}
|
||||
<Button type="button" onClick={handleGenerate} loading={loading}>
|
||||
{loading ? "جارٍ الإنشاء…" : "إنشاء تقرير البيان"}
|
||||
</button>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Toast
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Spinner } from "../UI";
|
||||
import { Alert, Button, Modal, Spinner } from "../UI";
|
||||
import { getStoredToken } from "@/src/lib/auth";
|
||||
import { userService } from "@/src/services/user.service";
|
||||
import type { UserDetail } from "@/src/types/user";
|
||||
@@ -12,6 +12,8 @@ interface UserDetailModalProps {
|
||||
}
|
||||
|
||||
// ── small helper components ───────────────────────────────────────────────────
|
||||
// (No equivalents in the shared UI kit — DetailRow/StatusBadge/Avatar are
|
||||
// purpose-built layouts, not generic form/action controls, so they stay custom.)
|
||||
function DetailRow({ label, value }: { label: string; value?: string | null }) {
|
||||
return (
|
||||
<div style={{
|
||||
@@ -29,6 +31,9 @@ function DetailRow({ label, value }: { label: string; value?: string | null }) {
|
||||
);
|
||||
}
|
||||
|
||||
// Kept custom rather than swapped for <Badge/>: Badge only renders a label
|
||||
// pill (no dot indicator), and the pulse-dot is the whole point of this status
|
||||
// chip's design.
|
||||
function StatusBadge({ active }: { active: boolean }) {
|
||||
return (
|
||||
<span style={{
|
||||
@@ -68,29 +73,22 @@ export function UserDetailModal({ userId, onClose }: UserDetailModalProps) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// close on Escape
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [onClose]);
|
||||
|
||||
// fetch user details on mount
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const data = await userService.getById(userId, token);
|
||||
if (!cancelled) setUser(data);
|
||||
} catch {
|
||||
if (!cancelled) setError("تعذّر تحميل بيانات المستخدم. يرجى المحاولة لاحقاً.");
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [userId]);
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const data = await userService.getById(userId, token);
|
||||
if (!cancelled) setUser(data);
|
||||
} catch {
|
||||
if (!cancelled) setError("تعذّر تحميل بيانات المستخدم. يرجى المحاولة لاحقاً.");
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [userId]);
|
||||
|
||||
// ── helpers ───────────────────────────────────────────────────────────────
|
||||
const fmt = (iso?: string | null) =>
|
||||
@@ -98,144 +96,67 @@ export function UserDetailModal({ userId, onClose }: UserDetailModalProps) {
|
||||
|
||||
// ── render ────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div
|
||||
role="dialog" aria-modal="true" aria-labelledby="detail-title"
|
||||
onClick={e => { if (e.target === e.currentTarget) onClose(); }}
|
||||
style={{
|
||||
position: "fixed", inset: 0, zIndex: 55,
|
||||
background: "rgba(15,23,42,0.55)", backdropFilter: "blur(4px)",
|
||||
display: "flex", alignItems: "center", justifyContent: "center", padding: "1rem",
|
||||
}}
|
||||
<Modal
|
||||
open
|
||||
title={user?.name ?? "عرض المستخدم"}
|
||||
subtitle="بيانات المستخدم"
|
||||
onClose={onClose}
|
||||
size="md"
|
||||
footer={
|
||||
<Button type="button" variant="secondary" onClick={onClose}>
|
||||
إغلاق
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div
|
||||
onClick={e => e.stopPropagation()}
|
||||
style={{
|
||||
width: "100%", maxWidth: 480,
|
||||
background: "var(--color-surface)",
|
||||
borderRadius: "var(--radius-2xl)",
|
||||
border: "1px solid var(--color-border)",
|
||||
boxShadow: "0 24px 64px rgba(0,0,0,.18)",
|
||||
overflow: "hidden",
|
||||
display: "flex", flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
{/* ── header ── */}
|
||||
<div style={{
|
||||
display: "flex", alignItems: "center", justifyContent: "space-between",
|
||||
padding: "1.25rem 1.5rem",
|
||||
borderBottom: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface-muted)",
|
||||
}}>
|
||||
<div>
|
||||
<p style={{ fontSize: 11, letterSpacing: "0.3em", textTransform: "uppercase", color: "#2563EB", fontWeight: 600, margin: 0 }}>
|
||||
بيانات المستخدم
|
||||
</p>
|
||||
<h2 id="detail-title" style={{ fontSize: 17, fontWeight: 700, color: "var(--color-text-primary)", margin: "4px 0 0" }}>
|
||||
{user?.name ?? "عرض المستخدم"}
|
||||
</h2>
|
||||
</div>
|
||||
<button
|
||||
type="button" onClick={onClose} aria-label="إغلاق"
|
||||
style={{
|
||||
width: 34, height: 34, borderRadius: "var(--radius-md)",
|
||||
border: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface)",
|
||||
cursor: "pointer", fontSize: 18,
|
||||
color: "var(--color-text-muted)",
|
||||
display: "flex", alignItems: "center", justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
{/* loading */}
|
||||
{loading && (
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, padding: "3rem 0", color: "var(--color-text-muted)" }}>
|
||||
<Spinner size="sm" className="text-blue-600" />
|
||||
<span style={{ fontSize: 13 }}>جارٍ التحميل…</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── body ── */}
|
||||
<div style={{ padding: "1.5rem", overflowY: "auto", maxHeight: "70vh" }}>
|
||||
{/* error */}
|
||||
{!loading && error && <Alert type="error" message={error} />}
|
||||
|
||||
{/* loading */}
|
||||
{loading && (
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, padding: "3rem 0", color: "var(--color-text-muted)" }}>
|
||||
<Spinner size="sm" className="text-blue-600" />
|
||||
<span style={{ fontSize: 13 }}>جارٍ التحميل…</span>
|
||||
</div>
|
||||
)}
|
||||
{/* content */}
|
||||
{!loading && user && (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 0 }} dir="rtl">
|
||||
|
||||
{/* error */}
|
||||
{!loading && error && (
|
||||
<div style={{
|
||||
padding: "1rem 1.25rem",
|
||||
borderRadius: "var(--radius-lg)",
|
||||
background: "#FEF2F2", border: "1px solid #FECACA",
|
||||
fontSize: 13, color: "#991B1B", fontWeight: 500,
|
||||
textAlign: "center",
|
||||
}}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* content */}
|
||||
{!loading && user && (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 0 }} dir="rtl">
|
||||
|
||||
{/* avatar + name + status row */}
|
||||
<div style={{
|
||||
display: "flex", alignItems: "center", gap: "1rem",
|
||||
padding: "0 0 1.25rem",
|
||||
borderBottom: "1px solid var(--color-border)",
|
||||
marginBottom: "0.25rem",
|
||||
}}>
|
||||
<Avatar name={user.name} />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<p style={{ fontSize: 16, fontWeight: 700, color: "var(--color-text-primary)", margin: 0 }}>{user.name}</p>
|
||||
{user.userName && (
|
||||
<p style={{ marginTop: 3, fontFamily: "var(--font-mono)", fontSize: 12, color: "#2563EB", fontWeight: 600 }}>
|
||||
@{user.userName}
|
||||
</p>
|
||||
)}
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<StatusBadge active={user.isActive} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* detail rows */}
|
||||
<DetailRow label="رقم الهاتف" value={user.phone} />
|
||||
<DetailRow label="البريد الإلكتروني" value={user.email} />
|
||||
<DetailRow label="الدور" value={user.role?.name} />
|
||||
<DetailRow label="وصف الدور" value={user.role?.description} />
|
||||
<DetailRow label="الفرع" value={user.branch?.name} />
|
||||
<DetailRow label="تاريخ الإنشاء" value={fmt(user.createdAt)} />
|
||||
<DetailRow label="آخر تحديث" value={fmt(user.updatedAt)} />
|
||||
{user.passwordChangedAt && (
|
||||
<DetailRow label="آخر تغيير لكلمة المرور" value={fmt(user.passwordChangedAt)} />
|
||||
{/* avatar + name + status row */}
|
||||
<div style={{
|
||||
display: "flex", alignItems: "center", gap: "1rem",
|
||||
padding: "0 0 1.25rem",
|
||||
borderBottom: "1px solid var(--color-border)",
|
||||
marginBottom: "0.25rem",
|
||||
}}>
|
||||
<Avatar name={user.name} />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<p style={{ fontSize: 16, fontWeight: 700, color: "var(--color-text-primary)", margin: 0 }}>{user.name}</p>
|
||||
{user.userName && (
|
||||
<p style={{ marginTop: 3, fontFamily: "var(--font-mono)", fontSize: 12, color: "#2563EB", fontWeight: 600 }}>
|
||||
@{user.userName}
|
||||
</p>
|
||||
)}
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<StatusBadge active={user.isActive} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* detail rows */}
|
||||
<DetailRow label="رقم الهاتف" value={user.phone} />
|
||||
<DetailRow label="البريد الإلكتروني" value={user.email} />
|
||||
<DetailRow label="الدور" value={user.role?.name} />
|
||||
<DetailRow label="وصف الدور" value={user.role?.description} />
|
||||
<DetailRow label="الفرع" value={user.branch?.name} />
|
||||
<DetailRow label="تاريخ الإنشاء" value={fmt(user.createdAt)} />
|
||||
<DetailRow label="آخر تحديث" value={fmt(user.updatedAt)} />
|
||||
{user.passwordChangedAt && (
|
||||
<DetailRow label="آخر تغيير لكلمة المرور" value={fmt(user.passwordChangedAt)} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── footer ── */}
|
||||
<div style={{
|
||||
padding: "1rem 1.5rem",
|
||||
borderTop: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface-muted)",
|
||||
display: "flex", justifyContent: "flex-end",
|
||||
}}>
|
||||
<button
|
||||
type="button" onClick={onClose}
|
||||
style={{
|
||||
height: 40, padding: "0 1.5rem",
|
||||
borderRadius: "var(--radius-md)",
|
||||
border: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface)",
|
||||
fontSize: 13, fontWeight: 600,
|
||||
color: "var(--color-text-secondary)",
|
||||
cursor: "pointer", fontFamily: "var(--font-sans)",
|
||||
}}
|
||||
>
|
||||
إغلاق
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,30 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import * as yup from "yup";
|
||||
import { Alert, Button, Input, Select, Spinner } from "../UI";
|
||||
import { useForm } from "react-hook-form";
|
||||
import type { Resolver } from "react-hook-form";
|
||||
import { yupResolver } from "@hookform/resolvers/yup";
|
||||
import { Alert, Button, Input, Select } from "../UI";
|
||||
import { createUserSchema, updateUserSchema } from "@/src/validations/user.validator";
|
||||
import type { Branch } from "@/src/types/branch";
|
||||
import type { Role } from "@/src/types/role";
|
||||
import type { FormErrors, User, UserFormData } from "@/src/types/user";
|
||||
|
||||
// ── 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 {};
|
||||
}
|
||||
}
|
||||
import type { User, UserFormData } from "@/src/types/user";
|
||||
|
||||
// ── Props ─────────────────────────────────────────────────────────────────────
|
||||
interface UserFormModalProps {
|
||||
@@ -39,50 +22,43 @@ interface UserFormModalProps {
|
||||
export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }: UserFormModalProps) {
|
||||
const isNew = editUser === null;
|
||||
|
||||
const [form, setForm] = useState<UserFormData>({
|
||||
name: editUser?.name ?? "",
|
||||
email: editUser?.email ?? "",
|
||||
phone: editUser?.phone ?? "",
|
||||
password: "",
|
||||
roleId: editUser?.role?.id ?? "",
|
||||
branchId: editUser?.branch?.id ?? "",
|
||||
// Custom resolver wrapper — on edit, an empty password field must be
|
||||
// treated as "not provided" (skip the min(8) rule entirely) rather than
|
||||
// validated as an empty string, exactly like the old validate() call did
|
||||
// by stripping `password` from the object before running the schema.
|
||||
const resolver: Resolver<UserFormData> = async (values, context, options) => {
|
||||
const schema = isNew ? createUserSchema : updateUserSchema;
|
||||
const data = !isNew && !values.password ? { ...values, password: undefined } : values;
|
||||
return yupResolver<UserFormData>(schema as any)(data as UserFormData, context, options);
|
||||
};
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
setError,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<UserFormData>({
|
||||
resolver,
|
||||
defaultValues: {
|
||||
name: editUser?.name ?? "",
|
||||
email: editUser?.email ?? "",
|
||||
phone: editUser?.phone ?? "",
|
||||
password: "",
|
||||
roleId: editUser?.role?.id ?? "",
|
||||
branchId: editUser?.branch?.id ?? "",
|
||||
},
|
||||
});
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [apiError, setApiError] = useState("");
|
||||
const firstInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => { firstInputRef.current?.focus(); }, []);
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [onClose]);
|
||||
|
||||
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();
|
||||
const errs = await validate(
|
||||
!isNew && !form.password
|
||||
? { ...form, password: undefined as unknown as string }
|
||||
: form,
|
||||
isNew,
|
||||
);
|
||||
if (Object.keys(errs).length) { setErrors(errs); return; }
|
||||
setSaving(true);
|
||||
setApiError("");
|
||||
const payload: Partial<UserFormData> = { ...form };
|
||||
const submitHandler = async (data: UserFormData) => {
|
||||
const payload: Partial<UserFormData> = { ...data };
|
||||
if (!isNew && !payload.password) delete payload.password;
|
||||
|
||||
const ok = await onSubmit(payload as UserFormData, isNew);
|
||||
setSaving(false);
|
||||
if (ok) onClose();
|
||||
else setApiError("حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.");
|
||||
if (ok) {
|
||||
onClose();
|
||||
} else {
|
||||
setError("name", { message: "حدث خطأ غير متوقع. يرجى المحاولة لاحقاً." });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -133,18 +109,19 @@ export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }:
|
||||
</div>
|
||||
|
||||
{/* body */}
|
||||
<form onSubmit={handleSubmit} noValidate style={{ padding: "1.5rem", display: "flex", flexDirection: "column", gap: "1rem" }}>
|
||||
{apiError && <Alert type="error" message={apiError} onClose={() => setApiError("")} />}
|
||||
<form onSubmit={handleSubmit(submitHandler)} noValidate style={{ padding: "1.5rem", display: "flex", flexDirection: "column", gap: "1rem" }}>
|
||||
{errors.name?.type === "manual" && (
|
||||
<Alert type="error" message={errors.name.message ?? ""} onClose={() => {}} />
|
||||
)}
|
||||
|
||||
{/* name */}
|
||||
<Input
|
||||
ref={firstInputRef}
|
||||
label="الاسم الكامل *"
|
||||
value={form.name}
|
||||
onChange={set("name")}
|
||||
error={errors.name}
|
||||
{...register("name")}
|
||||
error={errors.name && errors.name.type !== "manual" ? errors.name.message : undefined}
|
||||
placeholder="أحمد الرشيدي"
|
||||
autoComplete="name"
|
||||
autoFocus
|
||||
dir="rtl"
|
||||
/>
|
||||
|
||||
@@ -153,9 +130,8 @@ export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }:
|
||||
<Input
|
||||
label="البريد الإلكتروني"
|
||||
type="email"
|
||||
value={form.email}
|
||||
onChange={set("email")}
|
||||
error={errors.email}
|
||||
{...register("email")}
|
||||
error={errors.email?.message}
|
||||
placeholder="ahmed@co.sa"
|
||||
autoComplete="email"
|
||||
dir="ltr"
|
||||
@@ -163,9 +139,8 @@ export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }:
|
||||
<Input
|
||||
label="رقم الهاتف *"
|
||||
type="tel"
|
||||
value={form.phone}
|
||||
onChange={set("phone")}
|
||||
error={errors.phone}
|
||||
{...register("phone")}
|
||||
error={errors.phone?.message}
|
||||
placeholder="+966 5x xxx xxxx"
|
||||
autoComplete="tel"
|
||||
dir="ltr"
|
||||
@@ -176,9 +151,8 @@ export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }:
|
||||
<Input
|
||||
label={isNew ? "كلمة المرور *" : "كلمة المرور الجديدة (اتركها فارغة إذا لا تريد تغييرها)"}
|
||||
type="password"
|
||||
value={form.password}
|
||||
onChange={set("password")}
|
||||
error={errors.password}
|
||||
{...register("password")}
|
||||
error={errors.password?.message}
|
||||
placeholder="••••••••"
|
||||
autoComplete={isNew ? "new-password" : "off"}
|
||||
dir="ltr"
|
||||
@@ -188,9 +162,8 @@ export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }:
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
|
||||
<Select
|
||||
label="الدور *"
|
||||
value={form.roleId}
|
||||
onChange={set("roleId")}
|
||||
error={errors.roleId}
|
||||
{...register("roleId")}
|
||||
error={errors.roleId?.message}
|
||||
dir="rtl"
|
||||
>
|
||||
<option value="">اختر الدور</option>
|
||||
@@ -198,9 +171,8 @@ export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }:
|
||||
</Select>
|
||||
<Select
|
||||
label="الفرع *"
|
||||
value={form.branchId}
|
||||
onChange={set("branchId")}
|
||||
error={errors.branchId}
|
||||
{...register("branchId")}
|
||||
error={errors.branchId?.message}
|
||||
dir="rtl"
|
||||
>
|
||||
<option value="">اختر الفرع</option>
|
||||
@@ -210,11 +182,11 @@ export function UserFormModal({ editUser, roles, branches, onClose, onSubmit }:
|
||||
|
||||
{/* actions */}
|
||||
<div style={{ display: "flex", gap: "0.5rem", justifyContent: "flex-end", paddingTop: "0.5rem" }}>
|
||||
<Button type="button" variant="secondary" onClick={onClose} disabled={saving}>
|
||||
<Button type="button" variant="secondary" onClick={onClose} disabled={isSubmitting}>
|
||||
إلغاء
|
||||
</Button>
|
||||
<Button type="submit" variant="primary" loading={saving}>
|
||||
{saving ? "جارٍ الحفظ…" : isNew ? "إضافة المستخدم" : "حفظ التغييرات"}
|
||||
<Button type="submit" variant="primary" loading={isSubmitting}>
|
||||
{isSubmitting ? "جارٍ الحفظ…" : isNew ? "إضافة المستخدم" : "حفظ التغييرات"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -1,19 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { Spinner } from "../UI";
|
||||
import { Badge, Button, EmptyState, Spinner } from "../UI";
|
||||
import type { User } from "@/src/types/user";
|
||||
|
||||
// ── role badge ───────────────────────────────────────────────────────────────
|
||||
function RoleBadge({ name }: { name?: string }) {
|
||||
const isAdmin = name === "مدير النظام";
|
||||
return (
|
||||
<span style={{ display: "inline-flex", alignItems: "center", borderRadius: "var(--radius-full)", border: isAdmin ? "1px solid #BFDBFE" : "1px solid var(--color-border)", background: isAdmin ? "#EFF6FF" : "var(--color-surface-muted)", padding: "0.2rem 0.625rem", fontSize: 11, fontWeight: 600, color: isAdmin ? "#1D4ED8" : "var(--color-text-muted)" }}>
|
||||
{name ?? "—"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// ── status badge ─────────────────────────────────────────────────────────────
|
||||
// Kept custom rather than swapped for <Badge/>: Badge only renders a label
|
||||
// pill (no dot indicator), and the pulse-dot is the whole point of this chip.
|
||||
function StatusBadge({ active }: { active: boolean }) {
|
||||
return (
|
||||
<span style={{ display: "inline-flex", alignItems: "center", gap: 5, borderRadius: "var(--radius-full)", border: active ? "1px solid #BBF7D0" : "1px solid #FECACA", background: active ? "#DCFCE7" : "#FEF2F2", padding: "0.2rem 0.625rem", fontSize: 11, fontWeight: 600, color: active ? "#166534" : "#991B1B" }}>
|
||||
@@ -24,6 +16,11 @@ function StatusBadge({ active }: { active: boolean }) {
|
||||
}
|
||||
|
||||
// ── icon button ──────────────────────────────────────────────────────────────
|
||||
// Kept custom rather than swapped for <Button/>: Button's variants only cover
|
||||
// primary/secondary/ghost/danger (one accent color each) and its size scale
|
||||
// (h-8/h-10/h-11 with horizontal padding) isn't built for a fixed 32×32
|
||||
// square icon chip. Forcing it here would collapse the view/edit/delete
|
||||
// green/blue/red color-coding into a single variant and misshape the button.
|
||||
function IconBtn({ onClick, title, color, bg, borderColor, children }: { onClick: () => void; title: string; color: string; bg: string; borderColor: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<button type="button" title={title} aria-label={title} onClick={e => { e.stopPropagation(); onClick(); }}
|
||||
@@ -82,17 +79,17 @@ export function UserTable({ users, loading, search, page, pages, onEdit, onDelet
|
||||
</div>
|
||||
) : users.length === 0 ? (
|
||||
/* empty state */
|
||||
<div style={{ textAlign: "center", padding: "4rem 1rem" }}>
|
||||
<p style={{ fontSize: 13, color: "var(--color-text-muted)" }}>
|
||||
{search ? `لا توجد نتائج لـ "${search}"` : "لا يوجد مستخدمون لعرضهم."}
|
||||
</p>
|
||||
{!search && (
|
||||
<button type="button" onClick={onAddFirst}
|
||||
style={{ marginTop: 12, fontSize: 13, fontWeight: 600, color: "var(--color-brand-600)", background: "none", border: "none", cursor: "pointer", textDecoration: "underline" }}>
|
||||
أضف أول مستخدم
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<EmptyState
|
||||
icon="👥"
|
||||
title={search ? `لا توجد نتائج لـ "${search}"` : "لا يوجد مستخدمون لعرضهم."}
|
||||
action={
|
||||
!search && (
|
||||
<Button type="button" variant="ghost" size="sm" onClick={onAddFirst}>
|
||||
أضف أول مستخدم
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
/* data rows */
|
||||
<ul dir="rtl" style={{ listStyle: "none", margin: 0, padding: 0 }}>
|
||||
@@ -110,7 +107,7 @@ export function UserTable({ users, loading, search, page, pages, onEdit, onDelet
|
||||
</div>
|
||||
<span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "#2563EB", fontWeight: 600 }}>{u.userName ?? "—"}</span>
|
||||
<span style={{ color: "var(--color-text-secondary)" }}>{u.branch?.name ?? "—"}</span>
|
||||
<RoleBadge name={u.role?.name} />
|
||||
<Badge label={u.role?.name ?? "—"} color={u.role?.name === "مدير النظام" ? "indigo" : "slate"} />
|
||||
<StatusBadge active={u.isActive} />
|
||||
<span style={{ textAlign: "center", fontSize: 11, color: "var(--color-text-muted)" }}>
|
||||
{new Date(u.createdAt).toLocaleDateString("ar-SA", { year: "numeric", month: "short", day: "numeric" })}
|
||||
@@ -150,15 +147,24 @@ export function UserTable({ users, loading, search, page, pages, onEdit, onDelet
|
||||
صفحة <strong style={{ color: "var(--color-text-primary)" }}>{page}</strong> من <strong style={{ color: "var(--color-text-primary)" }}>{pages}</strong>
|
||||
</span>
|
||||
<div style={{ display: "flex", gap: "0.5rem" }}>
|
||||
{[
|
||||
{ label: "السابق", action: () => onPageChange(Math.max(1, page - 1)), disabled: page === 1 },
|
||||
{ label: "التالي", action: () => onPageChange(Math.min(pages, page + 1)), disabled: page === pages },
|
||||
].map(btn => (
|
||||
<button key={btn.label} type="button" onClick={btn.action} disabled={btn.disabled}
|
||||
style={{ borderRadius: "var(--radius-lg)", border: "1px solid var(--color-border)", background: "var(--color-surface-muted)", padding: "0.375rem 0.875rem", fontSize: 12, color: "var(--color-text-secondary)", cursor: btn.disabled ? "not-allowed" : "pointer", opacity: btn.disabled ? 0.4 : 1, fontFamily: "var(--font-sans)" }}>
|
||||
{btn.label}
|
||||
</button>
|
||||
))}
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onPageChange(Math.max(1, page - 1))}
|
||||
disabled={page === 1}
|
||||
>
|
||||
السابق
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onPageChange(Math.min(pages, page + 1))}
|
||||
disabled={page === pages}
|
||||
>
|
||||
التالي
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Spinner } from "../../UI";
|
||||
import { Alert, Button, Modal, Spinner } from "../../UI";
|
||||
import { getStoredToken } from "@/src/lib/auth";
|
||||
import { archivedUserService } from "@/src/services/archive/archivedUser.service";
|
||||
import type { ArchivedUser } from "@/src/types/user";
|
||||
@@ -12,6 +12,8 @@ interface ArchivedUserDetailModalProps {
|
||||
}
|
||||
|
||||
// ── small helper components ───────────────────────────────────────────────────
|
||||
// (No equivalents in the shared UI kit — DetailRow/StatusBadge/Avatar are
|
||||
// purpose-built layouts, not generic form/action controls, so they stay custom.)
|
||||
function DetailRow({ label, value }: { label: string; value?: string | null }) {
|
||||
return (
|
||||
<div style={{
|
||||
@@ -29,6 +31,9 @@ function DetailRow({ label, value }: { label: string; value?: string | null }) {
|
||||
);
|
||||
}
|
||||
|
||||
// Kept custom rather than swapped for <Badge/>: Badge only renders a label
|
||||
// pill (no dot indicator), and the pulse-dot is the whole point of this status
|
||||
// chip's design.
|
||||
function StatusBadge({ active }: { active: boolean }) {
|
||||
return (
|
||||
<span style={{
|
||||
@@ -68,29 +73,22 @@ export function ArchivedUserDetailModal({ userId, onClose }: ArchivedUserDetailM
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// close on Escape
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [onClose]);
|
||||
|
||||
// fetch archived user details on mount
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const data = await archivedUserService.getById(userId, token);
|
||||
if (!cancelled) setUser(data);
|
||||
} catch {
|
||||
if (!cancelled) setError("تعذّر تحميل بيانات المستخدم المؤرشف. يرجى المحاولة لاحقاً.");
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [userId]);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const data = await archivedUserService.getById(userId, token);
|
||||
if (!cancelled) setUser(data);
|
||||
} catch {
|
||||
if (!cancelled) setError("تعذّر تحميل بيانات المستخدم المؤرشف. يرجى المحاولة لاحقاً.");
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [userId]);
|
||||
|
||||
// ── helpers ───────────────────────────────────────────────────────────────
|
||||
const fmt = (iso?: string | null) =>
|
||||
@@ -98,138 +96,61 @@ useEffect(() => {
|
||||
|
||||
// ── render ────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div
|
||||
role="dialog" aria-modal="true" aria-labelledby="archived-detail-title"
|
||||
onClick={e => { if (e.target === e.currentTarget) onClose(); }}
|
||||
style={{
|
||||
position: "fixed", inset: 0, zIndex: 55,
|
||||
background: "rgba(15,23,42,0.55)", backdropFilter: "blur(4px)",
|
||||
display: "flex", alignItems: "center", justifyContent: "center", padding: "1rem",
|
||||
}}
|
||||
<Modal
|
||||
open
|
||||
title={user?.name ?? "عرض المستخدم"}
|
||||
subtitle="مستخدم مؤرشف"
|
||||
onClose={onClose}
|
||||
size="md"
|
||||
footer={
|
||||
<Button type="button" variant="secondary" onClick={onClose}>
|
||||
إغلاق
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div
|
||||
onClick={e => e.stopPropagation()}
|
||||
style={{
|
||||
width: "100%", maxWidth: 480,
|
||||
background: "var(--color-surface)",
|
||||
borderRadius: "var(--radius-2xl)",
|
||||
border: "1px solid var(--color-border)",
|
||||
boxShadow: "0 24px 64px rgba(0,0,0,.18)",
|
||||
overflow: "hidden",
|
||||
display: "flex", flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
{/* ── header ── */}
|
||||
<div style={{
|
||||
display: "flex", alignItems: "center", justifyContent: "space-between",
|
||||
padding: "1.25rem 1.5rem",
|
||||
borderBottom: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface-muted)",
|
||||
}}>
|
||||
<div>
|
||||
<p style={{ fontSize: 11, letterSpacing: "0.3em", textTransform: "uppercase", color: "#EA580C", fontWeight: 600, margin: 0 }}>
|
||||
مستخدم مؤرشف
|
||||
</p>
|
||||
<h2 id="archived-detail-title" style={{ fontSize: 17, fontWeight: 700, color: "var(--color-text-primary)", margin: "4px 0 0" }}>
|
||||
{user?.name ?? "عرض المستخدم"}
|
||||
</h2>
|
||||
</div>
|
||||
<button
|
||||
type="button" onClick={onClose} aria-label="إغلاق"
|
||||
style={{
|
||||
width: 34, height: 34, borderRadius: "var(--radius-md)",
|
||||
border: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface)",
|
||||
cursor: "pointer", fontSize: 18,
|
||||
color: "var(--color-text-muted)",
|
||||
display: "flex", alignItems: "center", justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
{/* loading */}
|
||||
{loading && (
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, padding: "3rem 0", color: "var(--color-text-muted)" }}>
|
||||
<Spinner size="sm" className="text-blue-600" />
|
||||
<span style={{ fontSize: 13 }}>جارٍ التحميل…</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── body ── */}
|
||||
<div style={{ padding: "1.5rem", overflowY: "auto", maxHeight: "70vh" }}>
|
||||
{/* error */}
|
||||
{!loading && error && <Alert type="error" message={error} />}
|
||||
|
||||
{/* loading */}
|
||||
{loading && (
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, padding: "3rem 0", color: "var(--color-text-muted)" }}>
|
||||
<Spinner size="sm" className="text-blue-600" />
|
||||
<span style={{ fontSize: 13 }}>جارٍ التحميل…</span>
|
||||
</div>
|
||||
)}
|
||||
{/* content */}
|
||||
{!loading && user && (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 0 }} dir="rtl">
|
||||
|
||||
{/* error */}
|
||||
{!loading && error && (
|
||||
<div style={{
|
||||
padding: "1rem 1.25rem",
|
||||
borderRadius: "var(--radius-lg)",
|
||||
background: "#FEF2F2", border: "1px solid #FECACA",
|
||||
fontSize: 13, color: "#991B1B", fontWeight: 500,
|
||||
textAlign: "center",
|
||||
}}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* content */}
|
||||
{!loading && user && (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 0 }} dir="rtl">
|
||||
|
||||
{/* avatar + name + status row */}
|
||||
<div style={{
|
||||
display: "flex", alignItems: "center", gap: "1rem",
|
||||
padding: "0 0 1.25rem",
|
||||
borderBottom: "1px solid var(--color-border)",
|
||||
marginBottom: "0.25rem",
|
||||
}}>
|
||||
<Avatar name={user.name} />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<p style={{ fontSize: 16, fontWeight: 700, color: "var(--color-text-primary)", margin: 0 }}>{user.name}</p>
|
||||
{user.userName && (
|
||||
<p style={{ marginTop: 3, fontFamily: "var(--font-mono)", fontSize: 12, color: "#2563EB", fontWeight: 600 }}>
|
||||
@{user.userName}
|
||||
</p>
|
||||
)}
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<StatusBadge active={user.isActive} />
|
||||
</div>
|
||||
</div>
|
||||
{/* avatar + name + status row */}
|
||||
<div style={{
|
||||
display: "flex", alignItems: "center", gap: "1rem",
|
||||
padding: "0 0 1.25rem",
|
||||
borderBottom: "1px solid var(--color-border)",
|
||||
marginBottom: "0.25rem",
|
||||
}}>
|
||||
<Avatar name={user.name} />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<p style={{ fontSize: 16, fontWeight: 700, color: "var(--color-text-primary)", margin: 0 }}>{user.name}</p>
|
||||
{user.userName && (
|
||||
<p style={{ marginTop: 3, fontFamily: "var(--font-mono)", fontSize: 12, color: "#2563EB", fontWeight: 600 }}>
|
||||
@{user.userName}
|
||||
</p>
|
||||
)}
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<StatusBadge active={user.isActive} />
|
||||
</div>
|
||||
|
||||
{/* detail rows */}
|
||||
<DetailRow label="رقم الهاتف" value={user.phone} />
|
||||
<DetailRow label="البريد الإلكتروني" value={user.email} />
|
||||
<DetailRow label="تاريخ الإنشاء" value={fmt(user.createdAt)} />
|
||||
<DetailRow label="آخر تحديث" value={fmt(user.updatedAt)} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── footer ── */}
|
||||
<div style={{
|
||||
padding: "1rem 1.5rem",
|
||||
borderTop: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface-muted)",
|
||||
display: "flex", justifyContent: "flex-end",
|
||||
}}>
|
||||
<button
|
||||
type="button" onClick={onClose}
|
||||
style={{
|
||||
height: 40, padding: "0 1.5rem",
|
||||
borderRadius: "var(--radius-md)",
|
||||
border: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface)",
|
||||
fontSize: 13, fontWeight: 600,
|
||||
color: "var(--color-text-secondary)",
|
||||
cursor: "pointer", fontFamily: "var(--font-sans)",
|
||||
}}
|
||||
>
|
||||
إغلاق
|
||||
</button>
|
||||
{/* detail rows */}
|
||||
<DetailRow label="رقم الهاتف" value={user.phone} />
|
||||
<DetailRow label="البريد الإلكتروني" value={user.email} />
|
||||
<DetailRow label="تاريخ الإنشاء" value={fmt(user.createdAt)} />
|
||||
<DetailRow label="آخر تحديث" value={fmt(user.updatedAt)} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { Spinner } from "../../UI";
|
||||
import { Button, EmptyState, Spinner } from "../../UI";
|
||||
import type { ArchivedUser } from "@/src/types/user";
|
||||
|
||||
// ── status badge ─────────────────────────────────────────────────────────────
|
||||
// Kept custom rather than swapped for <Badge/>: Badge only renders a label
|
||||
// pill (no dot indicator), and the pulse-dot is the whole point of this chip.
|
||||
function StatusBadge({ active }: { active: boolean }) {
|
||||
return (
|
||||
<span style={{ display: "inline-flex", alignItems: "center", gap: 5, borderRadius: "var(--radius-full)", border: active ? "1px solid #BBF7D0" : "1px solid #FECACA", background: active ? "#DCFCE7" : "#FEF2F2", padding: "0.2rem 0.625rem", fontSize: 11, fontWeight: 600, color: active ? "#166534" : "#991B1B" }}>
|
||||
@@ -14,6 +16,11 @@ function StatusBadge({ active }: { active: boolean }) {
|
||||
}
|
||||
|
||||
// ── icon button ──────────────────────────────────────────────────────────────
|
||||
// Kept custom rather than swapped for <Button/>: Button's variants only cover
|
||||
// primary/secondary/ghost/danger (one accent color each) and its size scale
|
||||
// (h-8/h-10/h-11 with horizontal padding) isn't built for a fixed 32×32
|
||||
// square icon chip. Forcing it here would misshape the button and drop the
|
||||
// semantic green "view" color.
|
||||
function IconBtn({ onClick, title, color, bg, borderColor, children }: { onClick: () => void; title: string; color: string; bg: string; borderColor: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<button type="button" title={title} aria-label={title} onClick={e => { e.stopPropagation(); onClick(); }}
|
||||
@@ -68,11 +75,10 @@ export function ArchivedUserTable({ users, loading, search, page, pages, onView,
|
||||
</div>
|
||||
) : users.length === 0 ? (
|
||||
/* empty state */
|
||||
<div style={{ textAlign: "center", padding: "4rem 1rem" }}>
|
||||
<p style={{ fontSize: 13, color: "var(--color-text-muted)" }}>
|
||||
{search ? `لا توجد نتائج لـ "${search}"` : "لا يوجد مستخدمون في الأرشيف."}
|
||||
</p>
|
||||
</div>
|
||||
<EmptyState
|
||||
icon="🗄️"
|
||||
title={search ? `لا توجد نتائج لـ "${search}"` : "لا يوجد مستخدمون في الأرشيف."}
|
||||
/>
|
||||
) : (
|
||||
/* data rows */
|
||||
<ul dir="rtl" style={{ listStyle: "none", margin: 0, padding: 0 }}>
|
||||
@@ -117,15 +123,24 @@ export function ArchivedUserTable({ users, loading, search, page, pages, onView,
|
||||
صفحة <strong style={{ color: "var(--color-text-primary)" }}>{page}</strong> من <strong style={{ color: "var(--color-text-primary)" }}>{pages}</strong>
|
||||
</span>
|
||||
<div style={{ display: "flex", gap: "0.5rem" }}>
|
||||
{[
|
||||
{ label: "السابق", action: () => onPageChange(Math.max(1, page - 1)), disabled: page === 1 },
|
||||
{ label: "التالي", action: () => onPageChange(Math.min(pages, page + 1)), disabled: page === pages },
|
||||
].map(btn => (
|
||||
<button key={btn.label} type="button" onClick={btn.action} disabled={btn.disabled}
|
||||
style={{ borderRadius: "var(--radius-lg)", border: "1px solid var(--color-border)", background: "var(--color-surface-muted)", padding: "0.375rem 0.875rem", fontSize: 12, color: "var(--color-text-secondary)", cursor: btn.disabled ? "not-allowed" : "pointer", opacity: btn.disabled ? 0.4 : 1, fontFamily: "var(--font-sans)" }}>
|
||||
{btn.label}
|
||||
</button>
|
||||
))}
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onPageChange(Math.max(1, page - 1))}
|
||||
disabled={page === 1}
|
||||
>
|
||||
السابق
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onPageChange(Math.min(pages, page + 1))}
|
||||
disabled={page === pages}
|
||||
>
|
||||
التالي
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Spinner } from "../UI";
|
||||
import { Alert, Button, Modal, Select, Spinner } from "../UI";
|
||||
import { getStoredToken } from "@/src/lib/auth";
|
||||
import { roleService } from "@/src/services/role.service";
|
||||
import { Permission, Role } from "@/src/types/role";
|
||||
@@ -14,6 +14,7 @@ interface RoleDetailModalProps {
|
||||
onRemove: (roleId: string, permissionId: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
// (No shared-UI equivalents — purpose-built layouts, not generic controls.)
|
||||
function DetailRow({ label, value }: { label: string; value?: string | null }) {
|
||||
return (
|
||||
<div style={{
|
||||
@@ -30,6 +31,8 @@ function DetailRow({ label, value }: { label: string; value?: string | null }) {
|
||||
);
|
||||
}
|
||||
|
||||
// Kept custom rather than swapped for <Badge/>: Badge only renders a label
|
||||
// pill (no dot indicator), and the pulse-dot is the whole point of this chip.
|
||||
function StatusBadge({ active }: { active: boolean }) {
|
||||
return (
|
||||
<span style={{
|
||||
@@ -54,12 +57,6 @@ export function RoleDetailModal({ roleId, permissions, onClose, onAssign, onRemo
|
||||
const [pendingPermId, setPendingPermId] = useState("");
|
||||
const [mutating, setMutating] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [onClose]);
|
||||
|
||||
const loadRole = async () => {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
@@ -115,165 +112,114 @@ export function RoleDetailModal({ roleId, permissions, onClose, onAssign, onRemo
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
role="dialog" aria-modal="true" aria-labelledby="role-detail-title"
|
||||
onClick={e => { if (e.target === e.currentTarget) onClose(); }}
|
||||
style={{
|
||||
position: "fixed", inset: 0, zIndex: 55,
|
||||
background: "rgba(15,23,42,0.55)", backdropFilter: "blur(4px)",
|
||||
display: "flex", alignItems: "center", justifyContent: "center", padding: "1rem",
|
||||
}}
|
||||
<Modal
|
||||
open
|
||||
title={role?.name ?? "عرض الدور"}
|
||||
subtitle="تفاصيل الدور"
|
||||
onClose={onClose}
|
||||
size="md"
|
||||
footer={
|
||||
<Button type="button" variant="secondary" onClick={onClose}>
|
||||
إغلاق
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div onClick={e => e.stopPropagation()} style={{
|
||||
width: "100%", maxWidth: 520,
|
||||
background: "var(--color-surface)",
|
||||
borderRadius: "var(--radius-2xl)",
|
||||
border: "1px solid var(--color-border)",
|
||||
boxShadow: "0 24px 64px rgba(0,0,0,.18)",
|
||||
overflow: "hidden", display: "flex", flexDirection: "column",
|
||||
}}>
|
||||
<div style={{
|
||||
display: "flex", alignItems: "center", justifyContent: "space-between",
|
||||
padding: "1.25rem 1.5rem",
|
||||
borderBottom: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface-muted)",
|
||||
}}>
|
||||
<div>
|
||||
<p style={{ fontSize: 11, letterSpacing: "0.3em", textTransform: "uppercase", color: "#2563EB", fontWeight: 600, margin: 0 }}>
|
||||
تفاصيل الدور
|
||||
</p>
|
||||
<h2 id="role-detail-title" style={{ fontSize: 17, fontWeight: 700, color: "var(--color-text-primary)", margin: "4px 0 0" }}>
|
||||
{role?.name ?? "عرض الدور"}
|
||||
</h2>
|
||||
{loading && (
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, padding: "3rem 0", color: "var(--color-text-muted)" }}>
|
||||
<Spinner size="sm" className="text-blue-600" />
|
||||
<span style={{ fontSize: 13 }}>جارٍ التحميل…</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && error && <Alert type="error" message={error} />}
|
||||
|
||||
{!loading && role && (
|
||||
<div dir="rtl">
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "1rem", paddingBottom: "1.25rem", borderBottom: "1px solid var(--color-border)", marginBottom: "0.25rem" }}>
|
||||
<div style={{
|
||||
width: 56, height: 56, borderRadius: "var(--radius-xl)",
|
||||
background: "linear-gradient(135deg, #2563EB 0%, #7C3AED 100%)",
|
||||
display: "flex", alignItems: "center", justifyContent: "center",
|
||||
fontSize: 22, flexShrink: 0,
|
||||
}}>
|
||||
🛡️
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<p style={{ fontSize: 16, fontWeight: 700, color: "var(--color-text-primary)", margin: 0 }}>{role.name}</p>
|
||||
{role.description && (
|
||||
<p style={{ marginTop: 3, fontSize: 12, color: "var(--color-text-muted)" }}>{role.description}</p>
|
||||
)}
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<StatusBadge active={role.isActive} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" onClick={onClose} aria-label="إغلاق"
|
||||
style={{ width: 34, height: 34, borderRadius: "var(--radius-md)", border: "1px solid var(--color-border)", background: "var(--color-surface)", cursor: "pointer", fontSize: 18, color: "var(--color-text-muted)", display: "flex", alignItems: "center", justifyContent: "center" }}>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div style={{ padding: "1.5rem", overflowY: "auto", maxHeight: "70vh" }}>
|
||||
{loading && (
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, padding: "3rem 0", color: "var(--color-text-muted)" }}>
|
||||
<Spinner size="sm" className="text-blue-600" />
|
||||
<span style={{ fontSize: 13 }}>جارٍ التحميل…</span>
|
||||
</div>
|
||||
)}
|
||||
<DetailRow label="تاريخ الإنشاء" value={fmt(role.createdAt)} />
|
||||
{role.updatedAt && <DetailRow label="آخر تحديث" value={fmt(role.updatedAt)} />}
|
||||
|
||||
{!loading && error && (
|
||||
<div style={{ padding: "1rem 1.25rem", borderRadius: "var(--radius-lg)", background: "#FEF2F2", border: "1px solid #FECACA", fontSize: 13, color: "#991B1B", fontWeight: 500, textAlign: "center" }}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ paddingTop: "0.75rem" }}>
|
||||
<p style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.15em", color: "var(--color-text-muted)", margin: "0 0 10px" }}>
|
||||
الصلاحيات ({role.permissions?.length ?? 0})
|
||||
</p>
|
||||
|
||||
{!loading && role && (
|
||||
<div dir="rtl">
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "1rem", paddingBottom: "1.25rem", borderBottom: "1px solid var(--color-border)", marginBottom: "0.25rem" }}>
|
||||
<div style={{
|
||||
width: 56, height: 56, borderRadius: "var(--radius-xl)",
|
||||
background: "linear-gradient(135deg, #2563EB 0%, #7C3AED 100%)",
|
||||
display: "flex", alignItems: "center", justifyContent: "center",
|
||||
fontSize: 22, flexShrink: 0,
|
||||
}}>
|
||||
🛡️
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<p style={{ fontSize: 16, fontWeight: 700, color: "var(--color-text-primary)", margin: 0 }}>{role.name}</p>
|
||||
{role.description && (
|
||||
<p style={{ marginTop: 3, fontSize: 12, color: "var(--color-text-muted)" }}>{role.description}</p>
|
||||
)}
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<StatusBadge active={role.isActive} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DetailRow label="تاريخ الإنشاء" value={fmt(role.createdAt)} />
|
||||
{role.updatedAt && <DetailRow label="آخر تحديث" value={fmt(role.updatedAt)} />}
|
||||
|
||||
<div style={{ paddingTop: "0.75rem" }}>
|
||||
<p style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.15em", color: "var(--color-text-muted)", margin: "0 0 10px" }}>
|
||||
الصلاحيات ({role.permissions?.length ?? 0})
|
||||
</p>
|
||||
|
||||
{assignablePermissions.length > 0 && (
|
||||
<div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
|
||||
<select
|
||||
value={pendingPermId}
|
||||
onChange={(e) => setPendingPermId(e.target.value)}
|
||||
disabled={mutating}
|
||||
style={{
|
||||
flex: 1, height: 36, borderRadius: "var(--radius-md)",
|
||||
border: "1px solid var(--color-border)", fontSize: 12,
|
||||
padding: "0 0.5rem", fontFamily: "var(--font-sans)",
|
||||
color: "var(--color-text-primary)", background: "var(--color-surface)",
|
||||
}}
|
||||
>
|
||||
<option value="">اختر صلاحية لإضافتها…</option>
|
||||
{assignablePermissions.map((p) => (
|
||||
<option key={p.id} value={p.id}>{p.name}</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button" onClick={handleAssign} disabled={!pendingPermId || mutating}
|
||||
style={{
|
||||
height: 36, padding: "0 0.875rem", borderRadius: "var(--radius-md)",
|
||||
border: "none", background: "var(--color-brand-600)", color: "#FFF",
|
||||
fontSize: 12, fontWeight: 700,
|
||||
cursor: pendingPermId && !mutating ? "pointer" : "not-allowed",
|
||||
opacity: !pendingPermId || mutating ? 0.6 : 1,
|
||||
fontFamily: "var(--font-sans)",
|
||||
display: "flex", alignItems: "center", gap: 6,
|
||||
}}
|
||||
>
|
||||
{mutating && <Spinner size="sm" className="text-white" />}
|
||||
إضافة
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{role.permissions && role.permissions.length > 0 ? (
|
||||
<div style={{ display: "flex", flexWrap: "wrap", gap: "0.4rem" }}>
|
||||
{role.permissions.map(({ permission }) => (
|
||||
<span key={permission.id} style={{
|
||||
display: "inline-flex", alignItems: "center", gap: 6,
|
||||
padding: "0.25rem 0.4rem 0.25rem 0.6rem", borderRadius: "var(--radius-md)",
|
||||
background: "#EFF6FF", border: "1px solid #BFDBFE",
|
||||
fontSize: 11, fontWeight: 600, color: "#1D4ED8",
|
||||
}}>
|
||||
{permission.name}
|
||||
<button
|
||||
type="button" onClick={() => handleRemove(permission.id)} disabled={mutating}
|
||||
aria-label={`إزالة ${permission.name}`}
|
||||
style={{
|
||||
background: "none", border: "none",
|
||||
cursor: mutating ? "not-allowed" : "pointer",
|
||||
color: "#1D4ED8", fontSize: 13, lineHeight: 1, padding: 0,
|
||||
}}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</span>
|
||||
{assignablePermissions.length > 0 && (
|
||||
<div style={{ display: "flex", gap: 8, marginBottom: 12, alignItems: "flex-start" }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<Select
|
||||
value={pendingPermId}
|
||||
onChange={(e) => setPendingPermId(e.target.value)}
|
||||
disabled={mutating}
|
||||
dir="rtl"
|
||||
>
|
||||
<option value="">اختر صلاحية لإضافتها…</option>
|
||||
{assignablePermissions.map((p) => (
|
||||
<option key={p.id} value={p.id}>{p.name}</option>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p style={{ fontSize: 13, color: "var(--color-text-hint)", fontStyle: "italic" }}>لا توجد صلاحيات مسندة لهذا الدور</p>
|
||||
)}
|
||||
</Select>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleAssign}
|
||||
disabled={!pendingPermId}
|
||||
loading={mutating}
|
||||
>
|
||||
إضافة
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{
|
||||
padding: "1rem 1.5rem", borderTop: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface-muted)", display: "flex", justifyContent: "flex-end",
|
||||
}}>
|
||||
<button type="button" onClick={onClose}
|
||||
style={{ height: 40, padding: "0 1.5rem", borderRadius: "var(--radius-md)", border: "1px solid var(--color-border)", background: "var(--color-surface)", fontSize: 13, fontWeight: 600, color: "var(--color-text-secondary)", cursor: "pointer", fontFamily: "var(--font-sans)" }}>
|
||||
إغلاق
|
||||
</button>
|
||||
{role.permissions && role.permissions.length > 0 ? (
|
||||
<div style={{ display: "flex", flexWrap: "wrap", gap: "0.4rem" }}>
|
||||
{role.permissions.map(({ permission }) => (
|
||||
<span key={permission.id} style={{
|
||||
display: "inline-flex", alignItems: "center", gap: 6,
|
||||
padding: "0.25rem 0.4rem 0.25rem 0.6rem", borderRadius: "var(--radius-md)",
|
||||
background: "#EFF6FF", border: "1px solid #BFDBFE",
|
||||
fontSize: 11, fontWeight: 600, color: "#1D4ED8",
|
||||
}}>
|
||||
{permission.name}
|
||||
<button
|
||||
type="button" onClick={() => handleRemove(permission.id)} disabled={mutating}
|
||||
aria-label={`إزالة ${permission.name}`}
|
||||
style={{
|
||||
background: "none", border: "none",
|
||||
cursor: mutating ? "not-allowed" : "pointer",
|
||||
color: "#1D4ED8", fontSize: 13, lineHeight: 1, padding: 0,
|
||||
}}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p style={{ fontSize: 13, color: "var(--color-text-hint)", fontStyle: "italic" }}>لا توجد صلاحيات مسندة لهذا الدور</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,28 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import * as yup from "yup";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { yupResolver } from "@hookform/resolvers/yup";
|
||||
import { Alert, Button, Input, Modal, Textarea } from "../UI";
|
||||
import { createRoleSchema, updateRoleSchema, type RoleFormErrors } from "@/src/validations/role.validator";
|
||||
import { createRoleSchema, updateRoleSchema } from "@/src/validations/role.validator";
|
||||
import { Permission, Role, RoleFormData } from "@/src/types/role";
|
||||
|
||||
// ── Validation ────────────────────────────────────────────────────────────────
|
||||
async function validate(data: RoleFormData, isNew: boolean): Promise<RoleFormErrors> {
|
||||
const schema = isNew ? createRoleSchema : updateRoleSchema;
|
||||
try {
|
||||
await schema.validate(data, { abortEarly: false });
|
||||
return {};
|
||||
} catch (err) {
|
||||
if (err instanceof yup.ValidationError) {
|
||||
return err.inner.reduce<RoleFormErrors>((acc, e) => {
|
||||
const field = e.path as keyof RoleFormErrors;
|
||||
if (field && !acc[field]) acc[field] = e.message;
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
return {};
|
||||
}
|
||||
}
|
||||
const FORM_ID = "role-form";
|
||||
|
||||
// ── Permission checkbox group ─────────────────────────────────────────────────
|
||||
function PermissionGroup({
|
||||
@@ -82,46 +66,32 @@ export function RoleFormModal({ editRole, permissions, onClose, onSubmit }: Role
|
||||
|
||||
const currentPermIds = editRole?.permissions?.map(p => p.permission.id) ?? [];
|
||||
|
||||
const [form, setForm] = useState<RoleFormData>({
|
||||
name: editRole?.name ?? "",
|
||||
description: editRole?.description ?? "",
|
||||
permissionIds: currentPermIds,
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
control,
|
||||
setError,
|
||||
setValue,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<RoleFormData>({
|
||||
// Cast the schema itself and pin the generic explicitly — create/update
|
||||
// schemas differ structurally in which fields are required, so yup can't
|
||||
// unify them into RoleFormData on its own.
|
||||
resolver: yupResolver<RoleFormData>((isNew ? createRoleSchema : updateRoleSchema) as any),
|
||||
defaultValues: {
|
||||
name: editRole?.name ?? "",
|
||||
description: editRole?.description ?? "",
|
||||
permissionIds: currentPermIds,
|
||||
},
|
||||
});
|
||||
const [errors, setErrors] = useState<RoleFormErrors>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [apiError, setApiError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [onClose]);
|
||||
|
||||
const set = (field: keyof Pick<RoleFormData, "name" | "description">) =>
|
||||
(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
setForm(p => ({ ...p, [field]: e.target.value }));
|
||||
if (errors[field]) setErrors(p => ({ ...p, [field]: undefined }));
|
||||
};
|
||||
|
||||
const togglePerm = (id: string) => {
|
||||
setForm(p => ({
|
||||
...p,
|
||||
permissionIds: p.permissionIds.includes(id)
|
||||
? p.permissionIds.filter(x => x !== id)
|
||||
: [...p.permissionIds, id],
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const errs = await validate(form, isNew);
|
||||
if (Object.keys(errs).length) { setErrors(errs); return; }
|
||||
setSaving(true);
|
||||
setApiError("");
|
||||
const ok = await onSubmit(form, isNew);
|
||||
setSaving(false);
|
||||
if (ok) onClose();
|
||||
else setApiError("حدث خطأ غير متوقع. يرجى المحاولة لاحقاً.");
|
||||
const submitHandler = async (data: RoleFormData) => {
|
||||
const ok = await onSubmit(data, isNew);
|
||||
if (ok) {
|
||||
onClose();
|
||||
} else {
|
||||
setError("name", { message: "حدث خطأ غير متوقع. يرجى المحاولة لاحقاً." });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -133,30 +103,31 @@ export function RoleFormModal({ editRole, permissions, onClose, onSubmit }: Role
|
||||
size="md"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="secondary" onClick={onClose} disabled={saving}>
|
||||
<Button type="button" variant="secondary" onClick={onClose} disabled={isSubmitting}>
|
||||
إلغاء
|
||||
</Button>
|
||||
<Button type="submit" form="role-form" loading={saving}>
|
||||
<Button type="submit" form={FORM_ID} loading={isSubmitting}>
|
||||
{isNew ? "إنشاء الدور" : "حفظ التغييرات"}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
id="role-form"
|
||||
onSubmit={handleSubmit}
|
||||
id={FORM_ID}
|
||||
onSubmit={handleSubmit(submitHandler)}
|
||||
noValidate
|
||||
style={{ display: "flex", flexDirection: "column", gap: "1rem" }}
|
||||
>
|
||||
{apiError && <Alert type="error" message={apiError} onClose={() => setApiError("")} />}
|
||||
{errors.name?.type === "manual" && (
|
||||
<Alert type="error" message={errors.name.message ?? ""} onClose={() => {}} />
|
||||
)}
|
||||
|
||||
<div dir="rtl">
|
||||
<Input
|
||||
label="اسم الدور *"
|
||||
value={form.name}
|
||||
onChange={set("name")}
|
||||
{...register("name")}
|
||||
error={errors.name && errors.name.type !== "manual" ? errors.name.message : undefined}
|
||||
placeholder="مثال: مدير الفروع"
|
||||
error={errors.name}
|
||||
dir="rtl"
|
||||
autoFocus
|
||||
/>
|
||||
@@ -165,49 +136,70 @@ export function RoleFormModal({ editRole, permissions, onClose, onSubmit }: Role
|
||||
<div dir="rtl">
|
||||
<Textarea
|
||||
label="الوصف"
|
||||
value={form.description}
|
||||
onChange={set("description")}
|
||||
{...register("description")}
|
||||
placeholder="وصف مختصر لمهام هذا الدور…"
|
||||
error={errors.description}
|
||||
error={errors.description?.message}
|
||||
dir="rtl"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Permissions */}
|
||||
{/* Permissions — bound via Controller since it's a custom checkbox
|
||||
group, not a plain input/select/textarea. */}
|
||||
{permissions.length > 0 && (
|
||||
<div dir="rtl">
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "0.75rem" }}>
|
||||
<span style={{ fontSize: 12, fontWeight: 600, color: "var(--color-text-secondary)" }}>
|
||||
الصلاحيات
|
||||
</span>
|
||||
<div style={{ display: "flex", gap: 8 }}>
|
||||
<Button type="button" onClick={() => setForm(p => ({ ...p, permissionIds: permissions.map(x => x.id) }))}
|
||||
style={{ fontSize: 11, fontWeight: 600, color: "#2563EB", background: "none", border: "none", cursor: "pointer", textDecoration: "underline" }}>
|
||||
تحديد الكل
|
||||
</Button>
|
||||
<Button type="button" onClick={() => setForm(p => ({ ...p, permissionIds: [] }))}
|
||||
style={{ fontSize: 11, fontWeight: 600, color: "#DC2626", background: "none", border: "none", cursor: "pointer", textDecoration: "underline" }}>
|
||||
إلغاء الكل
|
||||
</Button>
|
||||
<Controller
|
||||
name="permissionIds"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<div dir="rtl">
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "0.75rem" }}>
|
||||
<span style={{ fontSize: 12, fontWeight: 600, color: "var(--color-text-secondary)" }}>
|
||||
الصلاحيات
|
||||
</span>
|
||||
<div style={{ display: "flex", gap: 8 }}>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => setValue("permissionIds", permissions.map(x => x.id))}
|
||||
style={{ fontSize: 11, fontWeight: 600, color: "#2563EB", background: "none", border: "none", cursor: "pointer", textDecoration: "underline" }}
|
||||
>
|
||||
تحديد الكل
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => setValue("permissionIds", [])}
|
||||
style={{ fontSize: 11, fontWeight: 600, color: "#DC2626", background: "none", border: "none", cursor: "pointer", textDecoration: "underline" }}
|
||||
>
|
||||
إلغاء الكل
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{
|
||||
border: "1px solid var(--color-border)", borderRadius: "var(--radius-md)",
|
||||
padding: "0.875rem", background: "var(--color-surface-muted)",
|
||||
maxHeight: 280, overflowY: "auto",
|
||||
}}>
|
||||
{Object.entries(grouped).map(([module, perms]) => (
|
||||
<PermissionGroup
|
||||
key={module}
|
||||
module={module}
|
||||
perms={perms}
|
||||
selected={field.value}
|
||||
onToggle={(id) =>
|
||||
field.onChange(
|
||||
field.value.includes(id)
|
||||
? field.value.filter((x) => x !== id)
|
||||
: [...field.value, id],
|
||||
)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<p style={{ fontSize: 11, color: "var(--color-text-muted)", marginTop: 6 }}>
|
||||
{field.value.length} صلاحية محددة من أصل {permissions.length}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{
|
||||
border: "1px solid var(--color-border)", borderRadius: "var(--radius-md)",
|
||||
padding: "0.875rem", background: "var(--color-surface-muted)",
|
||||
maxHeight: 280, overflowY: "auto",
|
||||
}}>
|
||||
{Object.entries(grouped).map(([module, perms]) => (
|
||||
<PermissionGroup
|
||||
key={module} module={module} perms={perms}
|
||||
selected={form.permissionIds} onToggle={togglePerm}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<p style={{ fontSize: 11, color: "var(--color-text-muted)", marginTop: 6 }}>
|
||||
{form.permissionIds.length} صلاحية محددة من أصل {permissions.length}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { Role } from "@/src/types/role";
|
||||
import { Spinner } from "../UI";
|
||||
|
||||
import { Button, EmptyState, Spinner } from "../UI";
|
||||
|
||||
// ── Status badge ──────────────────────────────────────────────────────────────
|
||||
// Kept custom rather than swapped for <Badge/>: Badge only renders a label
|
||||
// pill (no dot indicator), and the pulse-dot is the whole point of this chip.
|
||||
function StatusBadge({ active }: { active: boolean }) {
|
||||
return (
|
||||
<span style={{
|
||||
@@ -23,6 +24,11 @@ function StatusBadge({ active }: { active: boolean }) {
|
||||
}
|
||||
|
||||
// ── Icon button ───────────────────────────────────────────────────────────────
|
||||
// Kept custom rather than swapped for <Button/>: Button's variants only cover
|
||||
// primary/secondary/ghost/danger (one accent color each) and its size scale
|
||||
// (h-8/h-10/h-11 with horizontal padding) isn't built for a fixed 32×32
|
||||
// square icon chip. Forcing it here would misshape the button and collapse
|
||||
// the view/edit/delete green/blue/red color-coding into one variant.
|
||||
function IconBtn({ onClick, title, color, bg, borderColor, children }: {
|
||||
onClick: () => void; title: string; color: string; bg: string; borderColor: string; children: React.ReactNode;
|
||||
}) {
|
||||
@@ -90,21 +96,18 @@ export function RoleTable({
|
||||
</div>
|
||||
) : roles.length === 0 ? (
|
||||
/* Empty state */
|
||||
<div style={{ textAlign: "center", padding: "4rem 1rem" }}>
|
||||
<div style={{ fontSize: 40, marginBottom: 12 }}>🛡️</div>
|
||||
<p style={{ fontSize: 14, fontWeight: 600, color: "var(--color-text-primary)", margin: "0 0 8px" }}>
|
||||
{search ? `لا توجد نتائج لـ "${search}"` : "لا توجد أدوار لعرضها"}
|
||||
</p>
|
||||
<p style={{ fontSize: 13, color: "var(--color-text-muted)", margin: "0 0 16px" }}>
|
||||
{!search && "ابدأ بإنشاء أول دور في النظام"}
|
||||
</p>
|
||||
{!search && (
|
||||
<button type="button" onClick={onAddFirst}
|
||||
style={{ fontSize: 13, fontWeight: 600, color: "var(--color-brand-600)", background: "none", border: "none", cursor: "pointer", textDecoration: "underline" }}>
|
||||
إضافة أول دور
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<EmptyState
|
||||
icon="🛡️"
|
||||
title={search ? `لا توجد نتائج لـ "${search}"` : "لا توجد أدوار لعرضها"}
|
||||
description={!search ? "ابدأ بإنشاء أول دور في النظام" : undefined}
|
||||
action={
|
||||
!search && (
|
||||
<Button type="button" variant="ghost" size="sm" onClick={onAddFirst}>
|
||||
إضافة أول دور
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
/* Data rows */
|
||||
<ul dir="rtl" style={{ listStyle: "none", margin: 0, padding: 0 }}>
|
||||
@@ -166,15 +169,24 @@ export function RoleTable({
|
||||
صفحة <strong style={{ color: "var(--color-text-primary)" }}>{page}</strong> من <strong style={{ color: "var(--color-text-primary)" }}>{pages}</strong>
|
||||
</span>
|
||||
<div style={{ display: "flex", gap: "0.5rem" }}>
|
||||
{[
|
||||
{ label: "السابق", action: () => onPageChange(Math.max(1, page - 1)), disabled: page === 1 },
|
||||
{ label: "التالي", action: () => onPageChange(Math.min(pages, page + 1)), disabled: page === pages },
|
||||
].map(btn => (
|
||||
<button key={btn.label} type="button" onClick={btn.action} disabled={btn.disabled}
|
||||
style={{ borderRadius: "var(--radius-lg)", border: "1px solid var(--color-border)", background: "var(--color-surface-muted)", padding: "0.375rem 0.875rem", fontSize: 12, color: "var(--color-text-secondary)", cursor: btn.disabled ? "not-allowed" : "pointer", opacity: btn.disabled ? 0.4 : 1 }}>
|
||||
{btn.label}
|
||||
</button>
|
||||
))}
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onPageChange(Math.max(1, page - 1))}
|
||||
disabled={page === 1}
|
||||
>
|
||||
السابق
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onPageChange(Math.min(pages, page + 1))}
|
||||
disabled={page === pages}
|
||||
>
|
||||
التالي
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Spinner } from "../../UI";
|
||||
import { Alert, Button, Modal, Spinner } from "../../UI";
|
||||
import { getStoredToken } from "@/src/lib/auth";
|
||||
import { archivedRoleService } from "@/src/services/archive/archivedRole.service";
|
||||
import type { ArchivedRole } from "@/src/types/role";
|
||||
@@ -12,6 +12,8 @@ interface ArchivedRoleDetailModalProps {
|
||||
}
|
||||
|
||||
// ── small helper components ───────────────────────────────────────────────────
|
||||
// (No equivalents in the shared UI kit — purpose-built layouts, not generic
|
||||
// form/action controls, so they stay custom.)
|
||||
function DetailRow({ label, value }: { label: string; value?: string | null }) {
|
||||
return (
|
||||
<div style={{
|
||||
@@ -29,6 +31,8 @@ function DetailRow({ label, value }: { label: string; value?: string | null }) {
|
||||
);
|
||||
}
|
||||
|
||||
// Kept custom rather than swapped for <Badge/>: Badge only renders a label
|
||||
// pill (no dot indicator), and the pulse-dot is the whole point of this chip.
|
||||
function StatusBadge({ active }: { active: boolean }) {
|
||||
return (
|
||||
<span style={{
|
||||
@@ -69,29 +73,22 @@ export function ArchivedRoleDetailModal({ roleId, onClose }: ArchivedRoleDetailM
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// close on Escape
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [onClose]);
|
||||
|
||||
// fetch archived role details on mount
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const data = await archivedRoleService.getByIdUnwrapped(roleId, token);
|
||||
if (!cancelled) setRole(data);
|
||||
} catch {
|
||||
if (!cancelled) setError("تعذّر تحميل بيانات الدور المؤرشف. يرجى المحاولة لاحقاً.");
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [roleId]);
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const token = getStoredToken();
|
||||
const data = await archivedRoleService.getByIdUnwrapped(roleId, token);
|
||||
if (!cancelled) setRole(data);
|
||||
} catch {
|
||||
if (!cancelled) setError("تعذّر تحميل بيانات الدور المؤرشف. يرجى المحاولة لاحقاً.");
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [roleId]);
|
||||
|
||||
// ── helpers ───────────────────────────────────────────────────────────────
|
||||
const fmt = (iso?: string | null) =>
|
||||
@@ -99,135 +96,58 @@ export function ArchivedRoleDetailModal({ roleId, onClose }: ArchivedRoleDetailM
|
||||
|
||||
// ── render ────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div
|
||||
role="dialog" aria-modal="true" aria-labelledby="archived-role-detail-title"
|
||||
onClick={e => { if (e.target === e.currentTarget) onClose(); }}
|
||||
style={{
|
||||
position: "fixed", inset: 0, zIndex: 55,
|
||||
background: "rgba(15,23,42,0.55)", backdropFilter: "blur(4px)",
|
||||
display: "flex", alignItems: "center", justifyContent: "center", padding: "1rem",
|
||||
}}
|
||||
<Modal
|
||||
open
|
||||
title={role?.name ?? "عرض الدور"}
|
||||
subtitle="دور مؤرشف"
|
||||
onClose={onClose}
|
||||
size="md"
|
||||
footer={
|
||||
<Button type="button" variant="secondary" onClick={onClose}>
|
||||
إغلاق
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div
|
||||
onClick={e => e.stopPropagation()}
|
||||
style={{
|
||||
width: "100%", maxWidth: 480,
|
||||
background: "var(--color-surface)",
|
||||
borderRadius: "var(--radius-2xl)",
|
||||
border: "1px solid var(--color-border)",
|
||||
boxShadow: "0 24px 64px rgba(0,0,0,.18)",
|
||||
overflow: "hidden",
|
||||
display: "flex", flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
{/* ── header ── */}
|
||||
<div style={{
|
||||
display: "flex", alignItems: "center", justifyContent: "space-between",
|
||||
padding: "1.25rem 1.5rem",
|
||||
borderBottom: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface-muted)",
|
||||
}}>
|
||||
<div>
|
||||
<p style={{ fontSize: 11, letterSpacing: "0.3em", textTransform: "uppercase", color: "#EA580C", fontWeight: 600, margin: 0 }}>
|
||||
دور مؤرشف
|
||||
</p>
|
||||
<h2 id="archived-role-detail-title" style={{ fontSize: 17, fontWeight: 700, color: "var(--color-text-primary)", margin: "4px 0 0" }}>
|
||||
{role?.name ?? "عرض الدور"}
|
||||
</h2>
|
||||
</div>
|
||||
<button
|
||||
type="button" onClick={onClose} aria-label="إغلاق"
|
||||
style={{
|
||||
width: 34, height: 34, borderRadius: "var(--radius-md)",
|
||||
border: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface)",
|
||||
cursor: "pointer", fontSize: 18,
|
||||
color: "var(--color-text-muted)",
|
||||
display: "flex", alignItems: "center", justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
{/* loading */}
|
||||
{loading && (
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, padding: "3rem 0", color: "var(--color-text-muted)" }}>
|
||||
<Spinner size="sm" className="text-blue-600" />
|
||||
<span style={{ fontSize: 13 }}>جارٍ التحميل…</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── body ── */}
|
||||
<div style={{ padding: "1.5rem", overflowY: "auto", maxHeight: "70vh" }}>
|
||||
{/* error — fallback UI on API failure */}
|
||||
{!loading && error && <Alert type="error" message={error} />}
|
||||
|
||||
{/* loading */}
|
||||
{loading && (
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, padding: "3rem 0", color: "var(--color-text-muted)" }}>
|
||||
<Spinner size="sm" className="text-blue-600" />
|
||||
<span style={{ fontSize: 13 }}>جارٍ التحميل…</span>
|
||||
</div>
|
||||
)}
|
||||
{/* content */}
|
||||
{!loading && role && (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 0 }} dir="rtl">
|
||||
|
||||
{/* error — fallback UI on API failure */}
|
||||
{!loading && error && (
|
||||
<div style={{
|
||||
padding: "1rem 1.25rem",
|
||||
borderRadius: "var(--radius-lg)",
|
||||
background: "#FEF2F2", border: "1px solid #FECACA",
|
||||
fontSize: 13, color: "#991B1B", fontWeight: 500,
|
||||
textAlign: "center",
|
||||
}}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* content */}
|
||||
{!loading && role && (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 0 }} dir="rtl">
|
||||
|
||||
{/* icon + name + status row */}
|
||||
<div style={{
|
||||
display: "flex", alignItems: "center", gap: "1rem",
|
||||
padding: "0 0 1.25rem",
|
||||
borderBottom: "1px solid var(--color-border)",
|
||||
marginBottom: "0.25rem",
|
||||
}}>
|
||||
<RoleIcon />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<p style={{ fontSize: 16, fontWeight: 700, color: "var(--color-text-primary)", margin: 0 }}>{role.name}</p>
|
||||
<p style={{ marginTop: 3, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--color-text-muted)" }}>
|
||||
#{role.id}
|
||||
</p>
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<StatusBadge active={role.isActive} />
|
||||
</div>
|
||||
</div>
|
||||
{/* icon + name + status row */}
|
||||
<div style={{
|
||||
display: "flex", alignItems: "center", gap: "1rem",
|
||||
padding: "0 0 1.25rem",
|
||||
borderBottom: "1px solid var(--color-border)",
|
||||
marginBottom: "0.25rem",
|
||||
}}>
|
||||
<RoleIcon />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<p style={{ fontSize: 16, fontWeight: 700, color: "var(--color-text-primary)", margin: 0 }}>{role.name}</p>
|
||||
<p style={{ marginTop: 3, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--color-text-muted)" }}>
|
||||
#{role.id}
|
||||
</p>
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<StatusBadge active={role.isActive} />
|
||||
</div>
|
||||
|
||||
{/* detail rows */}
|
||||
<DetailRow label="الوصف" value={role.description} />
|
||||
<DetailRow label="تاريخ الإنشاء" value={fmt(role.createdAt)} />
|
||||
<DetailRow label="آخر تحديث" value={fmt(role.updatedAt)} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── footer ── */}
|
||||
<div style={{
|
||||
padding: "1rem 1.5rem",
|
||||
borderTop: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface-muted)",
|
||||
display: "flex", justifyContent: "flex-end",
|
||||
}}>
|
||||
<button
|
||||
type="button" onClick={onClose}
|
||||
style={{
|
||||
height: 40, padding: "0 1.5rem",
|
||||
borderRadius: "var(--radius-md)",
|
||||
border: "1px solid var(--color-border)",
|
||||
background: "var(--color-surface)",
|
||||
fontSize: 13, fontWeight: 600,
|
||||
color: "var(--color-text-secondary)",
|
||||
cursor: "pointer", fontFamily: "var(--font-sans)",
|
||||
}}
|
||||
>
|
||||
إغلاق
|
||||
</button>
|
||||
{/* detail rows */}
|
||||
<DetailRow label="الوصف" value={role.description} />
|
||||
<DetailRow label="تاريخ الإنشاء" value={fmt(role.createdAt)} />
|
||||
<DetailRow label="آخر تحديث" value={fmt(role.updatedAt)} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { Spinner } from "../../UI";
|
||||
import { Button, EmptyState, Spinner } from "../../UI";
|
||||
import type { ArchivedRole } from "@/src/types/role";
|
||||
|
||||
// ── status badge ─────────────────────────────────────────────────────────────
|
||||
// Kept custom rather than swapped for <Badge/>: Badge only renders a label
|
||||
// pill (no dot indicator), and the pulse-dot is the whole point of this chip.
|
||||
function StatusBadge({ active }: { active: boolean }) {
|
||||
return (
|
||||
<span style={{ display: "inline-flex", alignItems: "center", gap: 5, borderRadius: "var(--radius-full)", border: active ? "1px solid #BBF7D0" : "1px solid #FECACA", background: active ? "#DCFCE7" : "#FEF2F2", padding: "0.2rem 0.625rem", fontSize: 11, fontWeight: 600, color: active ? "#166534" : "#991B1B" }}>
|
||||
@@ -14,6 +16,9 @@ function StatusBadge({ active }: { active: boolean }) {
|
||||
}
|
||||
|
||||
// ── icon button ──────────────────────────────────────────────────────────────
|
||||
// Kept custom rather than swapped for <Button/>: Button's variants only cover
|
||||
// primary/secondary/ghost/danger (one accent color each) and its size scale
|
||||
// isn't built for a fixed 32×32 square icon chip.
|
||||
function IconBtn({ onClick, title, color, bg, borderColor, children }: { onClick: () => void; title: string; color: string; bg: string; borderColor: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<button type="button" title={title} aria-label={title} onClick={e => { e.stopPropagation(); onClick(); }}
|
||||
@@ -68,11 +73,10 @@ export function ArchivedRoleTable({ roles, loading, search, page, pages, onView,
|
||||
</div>
|
||||
) : roles.length === 0 ? (
|
||||
/* empty state */
|
||||
<div style={{ textAlign: "center", padding: "4rem 1rem" }}>
|
||||
<p style={{ fontSize: 13, color: "var(--color-text-muted)" }}>
|
||||
{search ? `لا توجد نتائج لـ "${search}"` : "لا توجد أدوار في الأرشيف."}
|
||||
</p>
|
||||
</div>
|
||||
<EmptyState
|
||||
icon="🛡️"
|
||||
title={search ? `لا توجد نتائج لـ "${search}"` : "لا توجد أدوار في الأرشيف."}
|
||||
/>
|
||||
) : (
|
||||
/* data rows */
|
||||
<ul dir="rtl" style={{ listStyle: "none", margin: 0, padding: 0 }}>
|
||||
@@ -114,15 +118,24 @@ export function ArchivedRoleTable({ roles, loading, search, page, pages, onView,
|
||||
صفحة <strong style={{ color: "var(--color-text-primary)" }}>{page}</strong> من <strong style={{ color: "var(--color-text-primary)" }}>{pages}</strong>
|
||||
</span>
|
||||
<div style={{ display: "flex", gap: "0.5rem" }}>
|
||||
{[
|
||||
{ label: "السابق", action: () => onPageChange(Math.max(1, page - 1)), disabled: page === 1 },
|
||||
{ label: "التالي", action: () => onPageChange(Math.min(pages, page + 1)), disabled: page === pages },
|
||||
].map(btn => (
|
||||
<button key={btn.label} type="button" onClick={btn.action} disabled={btn.disabled}
|
||||
style={{ borderRadius: "var(--radius-lg)", border: "1px solid var(--color-border)", background: "var(--color-surface-muted)", padding: "0.375rem 0.875rem", fontSize: 12, color: "var(--color-text-secondary)", cursor: btn.disabled ? "not-allowed" : "pointer", opacity: btn.disabled ? 0.4 : 1, fontFamily: "var(--font-sans)" }}>
|
||||
{btn.label}
|
||||
</button>
|
||||
))}
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onPageChange(Math.max(1, page - 1))}
|
||||
disabled={page === 1}
|
||||
>
|
||||
السابق
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onPageChange(Math.min(pages, page + 1))}
|
||||
disabled={page === pages}
|
||||
>
|
||||
التالي
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user