Files
tbbank-frontend/src/features/branches/components/branchesForm.tsx
T
2026-10-25 00:30:50 +05:00

505 lines
19 KiB
TypeScript

import { useState, useCallback, useMemo, useEffect } 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 { toast } from "sonner";
import { Building2, MapPin, CreditCard } from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { FormInput } from "@/components/formInput";
import { FormActions } from "@/components/formActions";
import { MultiLangInput } from "@/components/multiLangInput";
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
import { Checkbox } from "@/components/ui/checkbox";
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
import { useCreateBranch, useUpdateBranch, useInfiniteProvinces } from "@/features/branches/hooks/useBranches";
import { resolveLocalizedName, type Branch } from "@/features/branches/api/branchesApi";
import { createBranchFormSchema, validateStep, DEFAULT_FORM_VALUES, buildPayload } from "@/features/branches/schemas/branch.schema";
import type { BranchFormData } from "@/features/branches/schemas/branch.schema";
type FlatErrors = Partial<Record<keyof BranchFormData, 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 BranchFormData] = msg;
}
return result;
}
interface StepDef {
id: string;
titleKey: string;
titleFallback: string;
shortLabelKey: string;
shortLabel: string;
icon: LucideIcon;
subtitleKey: string;
subtitleFallback: string;
validate: (form: BranchFormData, mode: "create" | "edit", t: (key: string, fallback?: string) => string) => FlatErrors;
}
const STEPS: StepDef[] = [
{
id: "basic",
titleKey: "branches.steps.basic",
titleFallback: "Esasy maglumatlar",
shortLabelKey: "branches.steps.basic.shortLabel",
shortLabel: "Esasy",
icon: Building2,
subtitleKey: "branches.steps.basic.subtitle",
subtitleFallback: "Ady, unikal belgisi, welaýaty",
validate: (form, mode, t) => validateStep(0, form, mode, t),
},
{
id: "address",
titleKey: "branches.steps.address",
titleFallback: "Salgy we habarlaşmak",
shortLabelKey: "branches.steps.address.shortLabel",
shortLabel: "Salgy",
icon: MapPin,
subtitleKey: "branches.steps.address.subtitle",
subtitleFallback: "Salgy, telefonlar",
validate: (form, mode, t) => validateStep(1, form, mode, t),
},
{
id: "billing",
titleKey: "branches.steps.billing",
titleFallback: "Billing maglumatlary",
shortLabelKey: "branches.steps.billing.shortLabel",
shortLabel: "Billing",
icon: CreditCard,
subtitleKey: "branches.steps.billing.subtitle",
subtitleFallback: "Ulanyjy ady we parollar",
validate: (form, mode, t) => validateStep(2, form, mode, t),
},
];
const STEP_FIELDS: Record<number, (keyof BranchFormData)[]> = {
0: ["nameTk", "nameRu", "nameEn", "uniqueCode", "provinceId", "region", "isActive"],
1: ["addressTk", "addressRu", "addressEn", "phoneNumbers"],
2: [
"billingUsername",
"billingPassword",
"billingSberUsername",
"billingSberPassword",
"billingVisaMasterUsername",
"billingVisaMasterPassword",
"billingSwiftUsername",
"billingSwiftPassword",
],
};
interface StepContentProps {
form: BranchFormData;
errors: FlatErrors;
set: <K extends keyof BranchFormData>(k: K, v: BranchFormData[K]) => void;
t: (key: string, fallback?: string) => string;
lang: "tm" | "ru" | "en";
provinceSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder">;
}
function StepBasic({ form, errors, set, t, provinceSelect }: StepContentProps) {
const nameFields = {
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk", v), error: errors.nameTk },
ru: { value: form.nameRu, onChange: (v: string) => set("nameRu", v), error: errors.nameRu },
en: { value: form.nameEn, onChange: (v: string) => set("nameEn", v), error: errors.nameEn },
};
return (
<div className="flex flex-col gap-6">
<MultiLangInput fields={nameFields} placeholder={t("branches.fields.name", "Şahamçanyň ady")} />
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="text"
label={t("branches.fields.uniqueCode", "Unikal belgisi")}
required
value={form.uniqueCode}
onChange={(v) => set("uniqueCode", v)}
placeholder={t("branches.fields.uniqueCodePlaceholder", "ORG-XXX-XXXX")}
error={errors.uniqueCode}
/>
<FormInput
type="text"
label={t("branches.fields.region", "Welaýat")}
required
value={form.region}
onChange={(v) => set("region", v)}
placeholder={t("branches.fields.regionPlaceholder", "Aşgabat şäheri")}
error={errors.region}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<InfiniteSelect
label={t("branches.fields.district", "Etrap")}
required
placeholder={t("branches.fields.districtPlaceholder", "Etrap saýlaň")}
{...provinceSelect}
error={provinceSelect.error ?? errors.provinceId}
value={form.provinceId}
onChange={(v) => set("provinceId", v)}
/>
<div className="flex items-end pb-2">
<div className="flex items-center gap-2">
<Checkbox id="isActive" checked={form.isActive} onCheckedChange={(checked) => set("isActive", !!checked)} />
<label htmlFor="isActive" className="text-sm text-muted-foreground cursor-pointer select-none">
{t("branches.fields.isActive", "Işjeň")}
</label>
</div>
</div>
</div>
</div>
);
}
function StepAddress({ form, errors, set, t }: StepContentProps) {
const addressFields = {
tk: { value: form.addressTk, onChange: (v: string) => set("addressTk", v), error: errors.addressTk },
ru: { value: form.addressRu, onChange: (v: string) => set("addressRu", v), error: errors.addressRu },
en: { value: form.addressEn, onChange: (v: string) => set("addressEn", v), error: errors.addressEn },
};
return (
<div className="flex flex-col gap-6">
<MultiLangInput fields={addressFields} placeholder={t("branches.fields.address", "Salgy")} />
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="text"
label={t("branches.fields.phoneNumbers", "Telefonlar")}
required
value={form.phoneNumbers}
onChange={(v) => set("phoneNumbers", v)}
placeholder={t("branches.fields.phoneNumbersPlaceholder", "+99312998877, +99365123456")}
error={errors.phoneNumbers}
/>
</div>
</div>
);
}
function StepBilling({ form, errors, set, t }: StepContentProps) {
return (
<div className="flex flex-col gap-6">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="text"
label={t("branches.fields.billingIbr", "Billing ulanyjy ady")}
required
value={form.billingUsername}
onChange={(v) => set("billingUsername", v)}
placeholder="billing_user"
error={errors.billingUsername}
/>
<FormInput
type="password"
label={t("branches.fields.billingPassword", "Billing paroly")}
required
value={form.billingPassword}
onChange={(v) => set("billingPassword", v)}
placeholder="••••••••"
error={errors.billingPassword}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="text"
label={t("branches.fields.billingSber", "Billing ulanyjy ady (SBER)")}
required
value={form.billingSberUsername}
onChange={(v) => set("billingSberUsername", v)}
placeholder="sber_merchant"
error={errors.billingSberUsername}
/>
<FormInput
type="password"
label={t("branches.fields.billingSberPassword", "Parol (SBER)")}
required
value={form.billingSberPassword}
onChange={(v) => set("billingSberPassword", v)}
placeholder="••••••••"
error={errors.billingSberPassword}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="text"
label={t("branches.fields.billingVisa", "Billing ulanyjy ady (VISA)")}
required
value={form.billingVisaMasterUsername}
onChange={(v) => set("billingVisaMasterUsername", v)}
placeholder="visamaster_merchant"
error={errors.billingVisaMasterUsername}
/>
<FormInput
type="password"
label={t("branches.fields.billingVisaPassword", "Parol (VISA)")}
required
value={form.billingVisaMasterPassword}
onChange={(v) => set("billingVisaMasterPassword", v)}
placeholder="••••••••"
error={errors.billingVisaMasterPassword}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="text"
label={t("branches.fields.billingSwift", "Billing ulanyjy ady (SWIFT)")}
required
value={form.billingSwiftUsername}
onChange={(v) => set("billingSwiftUsername", v)}
placeholder="SWIFT_TM_BANK"
error={errors.billingSwiftUsername}
/>
<FormInput
type="password"
label={t("branches.fields.billingSwiftPassword", "Parol (SWIFT)")}
required
value={form.billingSwiftPassword}
onChange={(v) => set("billingSwiftPassword", v)}
placeholder="••••••••"
error={errors.billingSwiftPassword}
/>
</div>
</div>
);
}
export interface BranchFormProps {
mode: "create" | "edit";
initialData?: Branch;
}
function mapInitial(data: Branch): Partial<BranchFormData> {
return {
nameTk: resolveLocalizedName(data.name, "tm"),
nameRu: resolveLocalizedName(data.name, "ru"),
nameEn: resolveLocalizedName(data.name, "en"),
uniqueCode: data.uniqueCode,
provinceId: String(data.provinceId),
region: data.region,
addressTk: resolveLocalizedName(data.address, "tm"),
addressRu: resolveLocalizedName(data.address, "ru"),
addressEn: resolveLocalizedName(data.address, "en"),
phoneNumbers: data.phoneNumbers,
billingUsername: data.billingUsername,
billingPassword: data.billingPassword,
billingSberUsername: data.billingSberUsername,
billingSberPassword: data.billingSberPassword,
billingVisaMasterUsername: data.billingVisaMasterUsername,
billingVisaMasterPassword: data.billingVisaMasterPassword,
billingSwiftUsername: data.billingSwiftUsername,
billingSwiftPassword: data.billingSwiftPassword,
isActive: data.active,
};
}
export function BranchForm({ mode, initialData }: BranchFormProps) {
const { t: _t, i18n } = useTranslation();
const t: (key: string, fallback?: string) => string = useCallback((key, fallback) => _t(key, fallback ?? key) as string, [_t]);
const lang = ((i18n.language?.slice(0, 2) === "tk" ? "tm" : i18n.language?.slice(0, 2)) ?? "tm") as "tm" | "ru" | "en";
const navigate = useNavigate();
const createMutation = useCreateBranch();
const updateMutation = useUpdateBranch();
const isPending = createMutation.isPending || updateMutation.isPending;
const [provinceSearch, setProvinceSearch] = useState("");
const provinceQuery = useInfiniteProvinces(provinceSearch);
const provinceSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
const opts: InfiniteSelectOption[] = (provinceQuery.data?.pages ?? [])
.flatMap((p) => p?.provinces ?? [])
.map((p) => ({ value: String(p.id), label: resolveLocalizedName(p.name, lang) }));
// Ensure the currently-selected province is present (edit mode), even if it
// lives beyond the pages loaded so far.
if (initialData) {
const current = String(initialData.provinceId);
if (!opts.some((o) => o.value === current)) {
opts.unshift({ value: current, label: resolveLocalizedName(initialData.provinceName, lang) || current });
}
}
return {
options: opts,
loading: provinceQuery.isLoading,
isLoadingMore: provinceQuery.isFetchingNextPage,
hasNextPage: !!provinceQuery.hasNextPage,
onLoadMore: () => provinceQuery.fetchNextPage(),
searchValue: provinceSearch,
onSearchChange: setProvinceSearch,
};
}, [provinceQuery, provinceSearch, lang, initialData]);
const schema = useMemo(() => createBranchFormSchema(t), [t, i18n.language]);
const {
watch,
setValue,
getValues,
formState: { errors: rhfErrors },
clearErrors,
trigger,
} = useForm<BranchFormData>({
resolver: zodResolver(schema),
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
});
const form = watch();
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
const [currentStep, setCurrentStep] = useState(0);
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>()));
const [isValidated, setIsValidated] = useState(false);
const stepsWithErrors = useMemo(() => {
const out = new Set<number>();
visited.forEach((i) => {
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) out.add(i);
});
return out;
}, [form, mode, visited, t]);
const set = useCallback(
<K extends keyof BranchFormData>(key: K, value: BranchFormData[K]) => {
(setValue as (name: K, val: BranchFormData[K]) => void)(key, value);
clearErrors(key);
},
[setValue, clearErrors],
);
const stepProps = useMemo(() => ({ form, errors, set, t, lang, provinceSelect }), [form, errors, set, t, lang, provinceSelect]);
const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i]));
// ── Re-validate on language change ──
useEffect(() => {
if (!isValidated) return;
const visitedFields = Array.from(visited).flatMap((stepIdx) => STEP_FIELDS[stepIdx] || []);
if (visitedFields.length > 0) {
trigger(visitedFields);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [i18n.language, isValidated]);
const handleNext = async () => {
setIsValidated(true);
markVisited(currentStep);
const fields = STEP_FIELDS[currentStep] || [];
const isValid = await trigger(fields);
if (!isValid) {
toast.error(t("common.errors.fillRequiredCorrectly", "Dogry maglumat girizmegiňizi haýyş edýäris."));
return;
}
if (currentStep < STEPS.length - 1) {
setCurrentStep(currentStep + 1);
window.scrollTo({ top: 0, behavior: "smooth" });
}
};
const handleBack = () => {
if (currentStep > 0) {
markVisited(currentStep);
setCurrentStep(currentStep - 1);
window.scrollTo({ top: 0, behavior: "smooth" });
}
};
const handleGoTo = (i: number) => {
markVisited(currentStep);
setCurrentStep(i);
window.scrollTo({ top: 0, behavior: "smooth" });
};
const doSubmit = async () => {
setIsValidated(true);
setVisited(new Set(STEPS.map((_, i) => i)));
const isValid = await trigger();
if (!isValid) {
toast.error(t("common.errors.requiredFieldsMissing", "Käbir hökmany meýdanlar doldurylan däldir."));
for (let i = 0; i < STEPS.length; i++) {
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) {
setCurrentStep(i);
break;
}
}
return;
}
const payload = buildPayload(getValues());
if (mode === "create") {
createMutation.mutate(payload, { onSuccess: () => navigate("/settings/location/branches") });
} else if (initialData) {
updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/settings/location/branches") });
}
};
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
const isActive = i === currentStep;
const hasErrors = stepsWithErrors.has(i);
const isDone = visited.has(i) && !hasErrors;
return {
id: s.id,
title: t(s.titleKey, s.titleFallback),
subtitle: t(s.subtitleKey, s.subtitleFallback),
icon: s.icon,
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
};
});
const isLastStep = currentStep === STEPS.length - 1;
return (
<div className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
<h1 className="text-xl font-semibold text-foreground">
{mode === "create" ? t("branches.createTitle", "Şahamça döretmek") : t("branches.editTitle", "Şahamçany üýtgetmek")}
</h1>
<p className="text-sm text-muted-foreground">{t("branches.form.subtitle", "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.")}</p>
</div>
<StepBarCards steps={stepBarItems} onGoTo={handleGoTo} />
<div className="flex flex-col bg-card border border-border rounded-xl overflow-hidden">
<div className="flex items-center gap-2.5 px-5 py-3.5 border-b border-border">
<span className="inline-flex items-center px-2 py-0.5 rounded-full bg-primary/10 text-primary text-[11px] font-semibold tabular-nums">
{currentStep + 1} / {STEPS.length}
</span>
<h2 className="text-sm font-semibold text-foreground">{t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback}</h2>
</div>
<div className="p-5">
{currentStep === 0 && <StepBasic {...stepProps} />}
{currentStep === 1 && <StepAddress {...stepProps} />}
{currentStep === 2 && <StepBilling {...stepProps} />}
</div>
<FormActions
isPending={isPending}
onCancel={currentStep === 0 ? () => navigate(-1) : undefined}
onPrev={currentStep > 0 ? handleBack : undefined}
onNext={!isLastStep ? handleNext : undefined}
showSubmit={isLastStep}
saveOnEveryStep={mode === "edit"}
onSubmit={doSubmit}
submitLabel={mode === "create" ? t("branches.actions.create", "Şahamça döret") : t("branches.actions.update", "Täzelemek")}
className="px-5 py-3.5 border-t border-border bg-muted/30"
/>
</div>
</div>
);
}