Files
tbbank-frontend/src/features/allUsers/components/allUsersForm.tsx

303 lines
11 KiB
TypeScript

import { useMemo, useEffect, useCallback, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { FormInput } from "@/components/formInput";
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { FormActions } from "@/components/formActions";
import { AvatarUpload } from "@/components/avatarUpload";
import { BentoGrid, BentoCard } from "@/components/bento";
import { useCreateUser, useUpdateUser } from "../hooks/useAllUsers";
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
import type { User } from "../api/allUsersApi";
import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload, buildUpdatePayload } from "../schemas/allUser.schema";
import type { AllUserFormData } from "../schemas/allUser.schema";
// ─── Types ────────────────────────────────────────────────────────────────────
interface UserFormProps {
mode: "create" | "edit";
initialData?: User;
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
type FlatErrors = Partial<Record<keyof AllUserFormData, string>>;
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
const result: FlatErrors = {};
for (const key of Object.keys(errors)) {
const msg = errors[key]?.message;
if (msg) result[key as keyof AllUserFormData] = msg;
}
return result;
}
// ─── UserForm ─────────────────────────────────────────────────────────────────
export function UserForm({ mode, initialData }: UserFormProps) {
const { t: _t, i18n } = useTranslation();
const t: (key: string, fallback?: string) => string = useCallback(
(key, fallback) => _t(key, fallback ?? key) as string,
[_t, i18n.language],
);
const navigate = useNavigate();
const createUser = useCreateUser();
const updateUser = useUpdateUser(initialData?.id ?? 0);
const isPending = createUser.isPending || updateUser.isPending;
const schema = useMemo(() => allUserFormSchema(mode, t), [mode, t, i18n.language]);
// ── Role infinite-scroll select ──
const [roleSearch, setRoleSearch] = useState("");
const roleQuery = useInfiniteRoles(roleSearch);
const roleSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
const opts: InfiniteSelectOption[] = (roleQuery.data?.pages ?? [])
.flatMap((p) => p.roles)
.map((r) => ({ value: r.code, label: r.name }));
// Ensure the currently-selected role is present (edit mode), even if it
// lives beyond the pages loaded so far.
if (initialData) {
const current = initialData.role;
if (current && !opts.some((o) => o.value === current)) {
opts.unshift({ value: current, label: current });
}
}
return {
options: opts,
loading: roleQuery.isLoading,
isLoadingMore: roleQuery.isFetchingNextPage,
hasNextPage: !!roleQuery.hasNextPage,
onLoadMore: () => roleQuery.fetchNextPage(),
searchValue: roleSearch,
onSearchChange: setRoleSearch,
};
}, [roleQuery, roleSearch, initialData]);
const {
watch,
setValue,
getValues,
formState: { errors: rhfErrors },
clearErrors,
trigger,
} = useForm<AllUserFormData>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
resolver: zodResolver(schema as any),
defaultValues: initialData
? {
...DEFAULT_FORM_VALUES,
username: initialData.username,
name: initialData.name,
firstName: initialData.firstName ?? "",
lastName: initialData.lastName ?? "",
phone: initialData.phone.replace(/\D/g, "").slice(-8),
email: initialData.email ?? "",
avatar: initialData.avatar ?? "",
role: initialData.role ?? "",
socialFacebook: initialData.socialMedia?.facebook ?? "",
socialInstagram: initialData.socialMedia?.instagram ?? "",
socialTelegram: initialData.socialMedia?.telegram ?? "",
lightMode: !!initialData.lightMode,
password: "",
active: !!initialData.active,
}
: DEFAULT_FORM_VALUES,
});
const form = watch();
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
const setField = <K extends keyof AllUserFormData>(key: K, value: AllUserFormData[K]) => {
(setValue as (name: K, val: AllUserFormData[K]) => void)(key, value);
clearErrors(key);
};
// ── Re-validate on language change ──
useEffect(() => {
if (Object.keys(rhfErrors).length > 0) {
trigger();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [i18n.language]);
const handleSubmit = async () => {
const isValid = await trigger();
if (!isValid) return;
const data = getValues();
if (mode === "create") {
const payload = buildPayload(data);
await createUser.mutateAsync(payload);
navigate("/all-users");
} else {
const payload = buildUpdatePayload(data);
await updateUser.mutateAsync(payload);
navigate(`/all-users/${initialData!.id}`);
}
};
return (
<div className="flex flex-col gap-5">
<h1 className="text-xl font-semibold text-foreground">
{mode === "create" ? t("users.createTitle", "Ulanyjy dörediň") : t("users.editTitle", "Ulanyjy üýtgetmek")}
</h1>
<BentoGrid cols={2}>
{/* ── Identity ── */}
<BentoCard title={t("users.sections.identity", "Şahsy maglumat")}>
<div className="grid grid-cols-2 gap-3">
<FormInput
type="text"
label={t("users.fields.username", "Ulanyjy ady")}
value={form.username}
onChange={(v) => setField("username", v)}
placeholder={t("users.fields.username", "Ulanyjy ady")}
error={errors.username}
disabled={isPending}
required
/>
<FormInput
type="text"
label={t("users.fields.name", "Ady")}
value={form.name}
onChange={(v) => setField("name", v)}
placeholder={t("users.fields.name", "Ady")}
error={errors.name}
disabled={isPending}
required
/>
<FormInput
type="text"
label={t("users.fields.firstName", "Ady (at)")}
value={form.firstName}
onChange={(v) => setField("firstName", v)}
placeholder={t("users.fields.firstName", "Ady (at)")}
error={errors.firstName}
disabled={isPending}
/>
<FormInput
type="text"
label={t("users.fields.lastName", "Familiýasy")}
value={form.lastName}
onChange={(v) => setField("lastName", v)}
placeholder={t("users.fields.lastName", "Familiýasy")}
error={errors.lastName}
disabled={isPending}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<FormInput
type="phone"
label={t("users.fields.phone", "Telefon")}
value={form.phone}
onChange={(v) => setField("phone", v)}
placeholder="62-38-49-56"
error={errors.phone}
disabled={isPending}
required
/>
<FormInput
type="email"
label={t("users.fields.email", "E-poçta")}
value={form.email}
onChange={(v) => setField("email", v)}
placeholder={t("users.fields.email", "E-poçta")}
error={errors.email}
disabled={isPending}
/>
<InfiniteSelect
label={t("users.fields.role", "Roly")}
value={form.role}
onChange={(v) => setField("role", v)}
placeholder={t("users.fields.role", "Roly")}
error={errors.role}
disabled={isPending}
required
{...roleSelect}
/>
{mode === "create" && (
<FormInput
type="password"
label={t("users.fields.password", "Açar sözi")}
value={form.password}
onChange={(v) => setField("password", v)}
placeholder={t("users.fields.password", "Açar sözi")}
error={errors.password}
disabled={isPending}
required
/>
)}
<div className="flex items-center gap-2 pt-1">
<Checkbox id="active" checked={form.active} onCheckedChange={(v) => setField("active", !!v)} disabled={isPending} />
<Label htmlFor="active" className="text-sm text-muted-foreground cursor-pointer">
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
</Label>
</div>
</div>
</BentoCard>
{/* ── Avatar ── */}
<BentoCard>
<AvatarUpload
label={t("users.fields.avatar", "Awatar")}
value={form.avatar}
onChange={(v) => setField("avatar", v)}
error={errors.avatar}
disabled={isPending}
/>
</BentoCard>
{/* ── Social media ── */}
<BentoCard title={t("users.fields.socialMedia", "Sosial media")} span="full">
<div className="grid grid-cols-3 gap-3">
<FormInput
type="text"
label={t("users.fields.facebook", "Facebook")}
value={form.socialFacebook}
onChange={(v) => setField("socialFacebook", v)}
placeholder="facebook.com/..."
error={errors.socialFacebook}
disabled={isPending}
/>
<FormInput
type="text"
label={t("users.fields.instagram", "Instagram")}
value={form.socialInstagram}
onChange={(v) => setField("socialInstagram", v)}
placeholder="instagram.com/..."
error={errors.socialInstagram}
disabled={isPending}
/>
<FormInput
type="text"
label={t("users.fields.telegram", "Telegram")}
value={form.socialTelegram}
onChange={(v) => setField("socialTelegram", v)}
placeholder="t.me/..."
error={errors.socialTelegram}
disabled={isPending}
/>
</div>
</BentoCard>
</BentoGrid>
<FormActions
isPending={isPending}
onSubmit={handleSubmit}
onCancel={() => navigate(-1)}
submitLabel={mode === "create" ? t("users.actions.create", "Ulanyjy dörediň") : t("users.actions.save", "Ýatda sakla")}
/>
</div>
);
}