Files
tbbank-frontend/src/features/loanOrders/components/loanOrderForm.tsx
T

1360 lines
52 KiB
TypeScript

import { useState, useCallback, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { CircleDot, CreditCard, MapPin, User, Wallet, FileText, Phone, Briefcase, ShieldCheck } from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { FormInput, type SelectOption } from "@/components/formInput";
import { FormActions } from "@/components/formActions";
import { DocumentUpload } from "@/components/documentUpload";
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
import { BentoGrid, BentoCard } from "@/components/bento";
import { useCreateLoanOrder, useUpdateLoanOrder } from "@/features/loanOrders/hooks/useLoanOrders";
import type { LoanOrder } from "@/features/loanOrders/api/loanOrdersApi";
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "@/features/loanOrders/schemas/loanOrder.schema";
import type { LoanOrderFormData } from "@/features/loanOrders/schemas/loanOrder.schema";
import { useInfiniteLoanTypes } from "@/features/loanTypes/hooks/useLoanTypes";
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
import { useInfiniteProvinces } from "@/features/branches/hooks/useBranches";
import type { LocalizedText } from "@/features/branches/api/branchesApi";
import { formatFromApiDateInput, formatFromApiPhone } from "@/lib/utils";
import {
PASSPORT_SERIES_OPTIONS,
getStatusOptions,
getRegionOptions,
EDUCATION_OPTIONS,
MARRIAGE_OPTIONS,
MONTH_OPTIONS,
YEAR_OPTIONS,
} from "@/constants";
import { useGetRequiredDocuments } from "@/features/requiredDocuments/hooks/useRequiredDocuments";
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
// ─── Static options ───────────────────────────────────────────────────────────
function resolveLocalizedName(name: LocalizedText | string | null | undefined, lang = "en"): string {
if (!name) return "";
if (typeof name === "string") return name;
return name[lang as keyof LocalizedText] ?? name.tm ?? name.en ?? name.ru ?? "";
}
// ─── Form errors helper ──────────────────────────────────────────────────────
type FlatErrors = Partial<Record<keyof LoanOrderFormData, 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 LoanOrderFormData] = msg;
}
return result;
}
// ─── Step definitions ─────────────────────────────────────────────────────────
interface StepDef {
id: string;
titleKey: string;
titleFallback: string;
subtitleKey: string;
subtitleFallback: string;
icon: LucideIcon;
validate: (form: LoanOrderFormData, mode: "create" | "edit") => FlatErrors;
}
const STEPS: StepDef[] = [
{
id: "status",
titleKey: "Status",
titleFallback: "Status",
subtitleKey: "loanOrderForm.steps.status.subtitle",
subtitleFallback: "Ýagdaý we bellik",
icon: CircleDot,
validate: (form, mode) => validateStep(0, form, mode),
},
{
id: "loan",
titleKey: "Loan",
titleFallback: "Karz",
subtitleKey: "loanOrderForm.steps.loan.subtitle",
subtitleFallback: "Görnüş we möçber",
icon: Wallet,
validate: (form, mode) => validateStep(1, form, mode),
},
{
id: "location",
titleKey: "Location",
titleFallback: "Lokasiýa",
subtitleKey: "loanOrderForm.steps.location.subtitle",
subtitleFallback: "Welaýat we şahamça",
icon: MapPin,
validate: (form, mode) => validateStep(2, form, mode),
},
{
id: "personal",
titleKey: "Personal data",
titleFallback: "Şahsy maglumatlar",
subtitleKey: "loanOrderForm.steps.personal.subtitle",
subtitleFallback: "At, bilim, maşgala",
icon: User,
validate: (form, mode) => validateStep(3, form, mode),
},
{
id: "card",
titleKey: "Card (Salary)",
titleFallback: "Kart (Zähmet haky)",
subtitleKey: "loanOrderForm.steps.card.subtitle",
subtitleFallback: "Zähmet haky karty",
icon: CreditCard,
validate: (form, mode) => validateStep(4, form, mode),
},
{
id: "passport",
titleKey: "Passport",
titleFallback: "Pasport",
subtitleKey: "loanOrderForm.steps.passport.subtitle",
subtitleFallback: "Seriýa, belgisi, senesi, suratlar",
icon: FileText,
validate: (form, mode) => validateStep(5, form, mode),
},
{
id: "contact",
titleKey: "Contact data",
titleFallback: "Habarlaşmak",
subtitleKey: "loanOrderForm.steps.contact.subtitle",
subtitleFallback: "Telefon we e-poçta",
icon: Phone,
validate: (form, mode) => validateStep(6, form, mode),
},
{
id: "job",
titleKey: "Job",
titleFallback: "Iş",
subtitleKey: "loanOrderForm.steps.job.subtitle",
subtitleFallback: "Kärhana we wezipe",
icon: Briefcase,
validate: (form, mode) => validateStep(7, form, mode),
},
{
id: "guarantor",
titleKey: "1. Guarantor",
titleFallback: "1. Zamun",
subtitleKey: "loanOrderForm.steps.guarantor.subtitle",
subtitleFallback: "Zamun maglumatlary",
icon: ShieldCheck,
validate: (form, mode) => validateStep(8, form, mode),
},
{
id: "guarantor2",
titleKey: "2. Guarantor",
titleFallback: "2. Zamun",
subtitleKey: "loanOrderForm.steps.guarantor2.subtitle",
subtitleFallback: "2. Zamun maglumatlary",
icon: ShieldCheck,
validate: (form, mode) => validateStep(9, form, mode),
},
];
// ─── Shared step content props ────────────────────────────────────────────────
interface StepContentProps {
form: LoanOrderFormData;
errors: FlatErrors;
set: <K extends keyof LoanOrderFormData>(k: K, v: LoanOrderFormData[K]) => void;
t: TFunction;
}
// ─── Step panels ──────────────────────────────────────────────────────────────
function StepStatus({ form, errors, set, t }: StepContentProps) {
const statusOptions = useMemo(() => getStatusOptions(t, "loanOrderStatus"), [t]);
return (
<BentoGrid cols={2}>
<BentoCard>
<FormInput
type="select"
label={t("loanOrderForm.labels.status") || "Status"}
required
value={form.status}
onChange={(v) => set("status", v)}
options={statusOptions}
error={errors.status}
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
/>
</BentoCard>
<BentoCard>
<FormInput
type="textarea"
label={t("Note") || "Bellik"}
value={form.notes}
onChange={(v) => set("notes", v)}
placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."}
rows={3}
/>
</BentoCard>
</BentoGrid>
);
}
function StepLoan({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrder }) {
const { i18n } = useTranslation();
const { data: requiredDocsData } = useGetRequiredDocuments({ page: 1, limit: 25 });
const [loanTypeSearch, setLoanTypeSearch] = useState("");
const loanTypesQuery = useInfiniteLoanTypes(loanTypeSearch);
const loanTypeOptions: InfiniteSelectOption[] = useMemo(() => {
const lang = i18n.language ?? "en";
const opts: InfiniteSelectOption[] = (loanTypesQuery.data?.pages ?? [])
.flatMap((p) => p?.loanTypes ?? [])
.map((lt) => ({ value: String(lt.id), label: resolveLocalizedName(lt.title, lang) || String(lt.id) }));
if (initialData?.loanTypeId && !opts.some((o) => o.value === String(initialData.loanTypeId))) {
opts.unshift({ value: String(initialData.loanTypeId), label: initialData.loanType || String(initialData.loanTypeId) });
}
return opts;
}, [loanTypesQuery, i18n.language, initialData]);
const docOptions = useMemo<SelectOption[]>(
() =>
(requiredDocsData?.loansDocuments ?? []).map((doc) => ({
value: String(doc.id),
label: doc.name,
})),
[requiredDocsData],
);
return (
<div className="space-y-4">
<BentoGrid cols={3}>
<BentoCard>
<InfiniteSelect
label={t("Loan type") || "Karz görnüşi"}
required
value={form.loanType}
onChange={(v) => set("loanType", v)}
options={loanTypeOptions}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.loanType}
loading={loanTypesQuery.isLoading}
isLoadingMore={loanTypesQuery.isFetchingNextPage}
hasNextPage={!!loanTypesQuery.hasNextPage}
onLoadMore={() => loanTypesQuery.fetchNextPage()}
searchValue={loanTypeSearch}
onSearchChange={setLoanTypeSearch}
/>
</BentoCard>
<BentoCard>
<FormInput
type="number"
label={t("loanOrderForm.labels.loanAmount") || "Karz möçberi"}
required
value={form.loanAmount}
onChange={(v) => set("loanAmount", v)}
placeholder={t("loanOrderForm.placeholders.amount") || "0.00"}
error={errors.loanAmount}
/>
</BentoCard>
<BentoCard>
<FormInput
type="select"
label={t("loanOrderForm.labels.requiredDoc") || "Gerekli resminat"}
value={form.loanOrderRequiredDocId}
onChange={(v) => set("loanOrderRequiredDocId", v)}
options={docOptions}
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
/>
</BentoCard>
</BentoGrid>
<BentoGrid cols={2}>
<BentoCard title={t("loanOrderForm.titles.loanCardInfo") || "Karz karty maglumatlary"}>
<FormInput
type="card-number"
label={t("Loan card number") || "Karz kart belgisi"}
value={form.loanCardNumber}
onChange={(v) => set("loanCardNumber", v)}
placeholder="9999 9999 9999 9999"
/>
<FormInput
type="card-name"
label={t("Loan card name") || "Karz kartdaky ady"}
value={form.loanCardName}
onChange={(v) => set("loanCardName", v)}
placeholder={t("Loan card name") || "Karz kartdaky ady"}
/>
</BentoCard>
<BentoCard title={t("loanOrderForm.titles.loanCardExpiry") || "Karz kart möhleti"}>
<FormInput
type="searchable-select"
label={t("loanOrderForm.labels.cardExpMonth") || "Aý"}
value={form.loanCardMonth}
onChange={(v) => set("loanCardMonth", v)}
options={MONTH_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
/>
<FormInput
type="searchable-select"
label={t("loanOrderForm.labels.cardExpYear") || "Ýyl"}
value={form.loanCardYear}
onChange={(v) => set("loanCardYear", v)}
options={YEAR_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
/>
</BentoCard>
</BentoGrid>
</div>
);
}
function StepLocation({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrder }) {
const { i18n } = useTranslation();
const [branchSearch, setBranchSearch] = useState("");
const branchQuery = useInfiniteBranches(branchSearch);
const regionOptions = useMemo(() => getRegionOptions(t), [t]);
const branchOptions: InfiniteSelectOption[] = useMemo(() => {
const lang = i18n.language ?? "en";
const opts: InfiniteSelectOption[] = (branchQuery.data?.pages ?? [])
.flatMap((p) => p?.branches ?? [])
.map((b) => ({
value: String(b.id),
label: resolveLocalizedName(b.name, lang) || b.uniqueCode || String(b.id),
}));
if (initialData?.branchId && !opts.some((o) => o.value === String(initialData.branchId))) {
opts.unshift({ value: String(initialData.branchId), label: initialData.branch || String(initialData.branchId) });
}
return opts;
}, [branchQuery, i18n.language, initialData]);
return (
<BentoGrid cols={2}>
<BentoCard>
<FormInput
type="searchable-select"
label={t("Region") || "Welaýat"}
required
value={form.region}
onChange={(v) => {
set("region", v);
set("branchId", "");
}}
options={regionOptions}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.region}
/>
</BentoCard>
<BentoCard>
<InfiniteSelect
label={t("Branch") || "Şahamça"}
required
value={form.branchId}
onChange={(v) => set("branchId", v)}
options={branchOptions}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
disabled={!form.region}
error={errors.branchId}
loading={branchQuery.isLoading}
isLoadingMore={branchQuery.isFetchingNextPage}
hasNextPage={!!branchQuery.hasNextPage}
onLoadMore={() => branchQuery.fetchNextPage()}
searchValue={branchSearch}
onSearchChange={setBranchSearch}
/>
</BentoCard>
</BentoGrid>
);
}
function StepPersonal({
form,
errors,
set,
t,
initialData,
userLocked,
selfUserId,
userName,
}: StepContentProps & { initialData?: LoanOrder; userLocked?: boolean; selfUserId?: string; userName?: string }) {
const [clientSearch, setClientSearch] = useState("");
const clientsQuery = useInfiniteClients(clientSearch, !userLocked);
const clientOptions: InfiniteSelectOption[] = useMemo(() => {
const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? [])
.flatMap((p) => p?.users ?? [])
.map((u) => ({
value: String(u.id),
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id),
}))
.filter((o) => !userLocked || o.value === selfUserId);
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
opts.unshift({ value: selfUserId, label: userName || selfUserId });
}
if (initialData?.createdById && !opts.some((o) => o.value === String(initialData.createdById))) {
opts.unshift({
value: String(initialData.createdById),
label: initialData.createdBy || String(initialData.createdById),
});
}
return opts;
}, [clientsQuery.data, initialData, userLocked, selfUserId, userName]);
return (
<div className="space-y-4">
<BentoGrid cols={1}>
<BentoCard title={t("loanOrderForm.titles.personalName") || "Şahsy maglumatlar"}>
<InfiniteSelect
label={t("loanOrderForm.labels.client") || "Müşderi"}
required
value={form.userId}
onChange={(v) => set("userId", v)}
options={clientOptions}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.userId}
loading={clientsQuery.isLoading}
isLoadingMore={clientsQuery.isFetchingNextPage}
hasNextPage={!!clientsQuery.hasNextPage}
onLoadMore={() => clientsQuery.fetchNextPage()}
searchValue={clientSearch}
onSearchChange={setClientSearch}
disabled={userLocked}
/>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<FormInput
type="text"
label={t("Name") || "Ady"}
required
value={form.customerName}
onChange={(v) => set("customerName", v)}
placeholder={t("Name") || "Ady"}
error={errors.customerName}
/>
<FormInput
type="text"
label={t("Surname") || "Familiýasy"}
required
value={form.customerSurname}
onChange={(v) => set("customerSurname", v)}
placeholder={t("Surname") || "Familiýasy"}
error={errors.customerSurname}
/>
<FormInput
type="text"
label={t("Patronic name") || "Atasynyň ady"}
value={form.customerPatronicName}
onChange={(v) => set("customerPatronicName", v)}
placeholder={t("Patronic name") || "Atasynyň ady"}
/>
</div>
</BentoCard>
</BentoGrid>
<BentoGrid cols={1}>
<BentoCard title={t("loanOrderForm.titles.personalDetails") || "Bilim we maşgala ýagdaýy"}>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<FormInput
type="select"
label={t("Education") || "Bilimi"}
required
value={form.education}
onChange={(v) => set("education", v)}
options={EDUCATION_OPTIONS}
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
error={errors.education}
/>
<FormInput
type="select"
label={t("Marriage status") || "Maşgala ýagdaýy"}
required
value={form.marriageStatus}
onChange={(v) => set("marriageStatus", v)}
options={MARRIAGE_OPTIONS}
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
error={errors.marriageStatus}
/>
<FormInput
type="date"
label={t("Date of birth") || "Doglan güni"}
required
value={form.bornAt}
onChange={(v) => set("bornAt", v)}
error={errors.bornAt}
/>
</div>
</BentoCard>
</BentoGrid>
<BentoGrid cols={2}>
<BentoCard title={t("loanOrderForm.titles.residence") || "Ýaşaýyş salgysy"}>
<FormInput
type="text"
label={t("Residence (passport)") || "Ýazgy edilen salgyňyz"}
required
value={form.passportAddress}
onChange={(v) => set("passportAddress", v)}
placeholder={t("loanOrderForm.placeholders.residence") || "Ýazgy edilen salgy"}
error={errors.passportAddress}
/>
<FormInput
type="text"
label={t("Current Residence") || "Häzirki ýaşaýyş ýeri"}
value={form.realAddress}
onChange={(v) => set("realAddress", v)}
placeholder={t("loanOrderForm.placeholders.currentResidence") || "Häzirki ýaşaýyş ýeri"}
/>
</BentoCard>
<BentoCard title={t("loanOrderForm.titles.bornPlace") || "Doglan ýeri"}>
<FormInput
type="text"
label={t("Born place (passport)") || "Doglan ýeri (pasport)"}
value={form.bornPlace}
onChange={(v) => set("bornPlace", v)}
placeholder={t("Born place (passport)") || "Doglan ýeri (pasport)"}
/>
</BentoCard>
</BentoGrid>
</div>
);
}
function StepCard({ form, errors, set, t }: StepContentProps) {
return (
<BentoGrid cols={2}>
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Kart maglumatlary"}>
<FormInput
type="card-number"
label={t("Card number") || "Kart belgisi"}
required
value={form.cardNumber}
onChange={(v) => set("cardNumber", v)}
placeholder="9999 9999 9999 9999"
error={errors.cardNumber}
/>
<FormInput
type="card-name"
label={t("Name on card") || "Kartdaky ady"}
required
value={form.cardName}
onChange={(v) => set("cardName", v)}
placeholder={t("Name on card") || "Kartdaky ady"}
error={errors.cardName}
/>
</BentoCard>
<BentoCard title={t("loanOrderForm.titles.cardExpiry") || "Kart möhleti"}>
<FormInput
type="searchable-select"
label={t("loanOrderForm.labels.cardExpMonth") || "Aý"}
required
value={form.cardMonth}
onChange={(v) => set("cardMonth", v)}
options={MONTH_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.cardMonth}
/>
<FormInput
type="searchable-select"
label={t("loanOrderForm.labels.cardExpYear") || "Ýyl"}
required
value={form.cardYear}
onChange={(v) => set("cardYear", v)}
options={YEAR_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.cardYear}
/>
</BentoCard>
</BentoGrid>
);
}
function StepPassport({ form, errors, set, t, mode }: StepContentProps & { mode: "create" | "edit" }) {
return (
<div className="space-y-4">
<BentoGrid cols={3}>
<BentoCard>
<FormInput
type="searchable-select"
label={t("Passport serie") || "Pasport seriýasy"}
required
value={form.passportSerie}
onChange={(v) => set("passportSerie", v)}
options={PASSPORT_SERIES_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.passportSerie}
/>
</BentoCard>
<BentoCard>
<FormInput
type="passport-id"
label={t("Passport id") || "Pasport belgisi"}
required
value={form.passportId}
onChange={(v) => set("passportId", v)}
placeholder="999999"
error={errors.passportId}
/>
</BentoCard>
<BentoCard>
<FormInput
type="date"
label={t("Passport date of issue") || "Pasport berlen senesi"}
required
value={form.passportGivenAt}
onChange={(v) => set("passportGivenAt", v)}
error={errors.passportGivenAt}
/>
</BentoCard>
</BentoGrid>
<BentoGrid cols={1}>
<BentoCard>
<FormInput
type="text"
label={t("Passport given by") || "Kim tarapyndan berildi"}
required
value={form.passportGivenBy}
onChange={(v) => set("passportGivenBy", v)}
placeholder={t("Passport given by") || "Kim tarapyndan berildi"}
error={errors.passportGivenBy}
/>
</BentoCard>
</BentoGrid>
<BentoGrid cols={2}>
<BentoCard>
<DocumentUpload
label={
mode === "edit"
? t("loanOrderForm.fileLabels.replacePage1") || "Pasport (sahypa 1) (çalyşmak)"
: t("Passport (page 1)") || "Pasport (sahypa 1)"
}
value={form.passportOne}
onChange={(v) => set("passportOne", v)}
error={errors.passportOne}
required={mode === "create"}
accept="image/*"
/>
</BentoCard>
<BentoCard>
<DocumentUpload
label={
mode === "edit"
? t("loanOrderForm.fileLabels.replacePage23") || "Pasport (2-3-nji sahypa) (çalyşmak)"
: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)"
}
value={form.passportTwo}
onChange={(v) => set("passportTwo", v)}
error={errors.passportTwo}
required={mode === "create"}
accept="image/*"
/>
</BentoCard>
<BentoCard>
<DocumentUpload
label={t("Passport (page 8-9)") || "Pasport (8-9 sahypa)"}
value={form.passportThree}
onChange={(v) => set("passportThree", v)}
accept="image/*"
/>
</BentoCard>
<BentoCard>
<DocumentUpload
label={t("Passport (page 32)") || "Pasport (32-nji sahypa)"}
value={form.passportFour}
onChange={(v) => set("passportFour", v)}
accept="image/*"
/>
</BentoCard>
</BentoGrid>
</div>
);
}
function StepContact({ form, errors, set, t }: StepContentProps) {
return (
<BentoGrid cols={2}>
<BentoCard title={t("loanOrderForm.titles.contactMain") || "Esasy"}>
<FormInput
type="phone"
label={t("Phone") || "Telefon"}
required
value={form.phone}
onChange={(v) => set("phone", v)}
placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"}
error={errors.phone}
/>
<FormInput
type="email"
label={t("Email") || "E-poçta"}
value={form.email}
onChange={(v) => set("email", v)}
placeholder={t("Email") || "E-poçta"}
/>
</BentoCard>
<BentoCard title={t("loanOrderForm.titles.contactAdditional") || "Goşmaça"}>
<FormInput
type="phone"
label={t("Phone Additional") || "Telefon goşmaça"}
value={form.phoneAdditional}
onChange={(v) => set("phoneAdditional", v)}
placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"}
error={errors.phoneAdditional}
/>
<FormInput
type="digits"
label={t("Home phone") || "Öý telefony"}
value={form.phoneHome}
onChange={(v) => set("phoneHome", v)}
placeholder={t("Home phone") || "Öý telefony"}
error={errors.phoneHome}
/>
</BentoCard>
</BentoGrid>
);
}
function StepJob({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrder }) {
const { i18n } = useTranslation();
const [provinceSearch, setProvinceSearch] = useState("");
const provinceQuery = useInfiniteProvinces(provinceSearch);
const regionOptions = useMemo(() => getRegionOptions(t), [t]);
const provinceOptions: InfiniteSelectOption[] = useMemo(() => {
const lang = i18n.language ?? "en";
const opts: InfiniteSelectOption[] = (provinceQuery.data?.pages ?? [])
.flatMap((p) => p?.provinces ?? [])
.map((prov) => ({ value: String(prov.id), label: resolveLocalizedName(prov.name, lang) || String(prov.id) }));
if (initialData?.workProvinceId && !opts.some((o) => o.value === String(initialData.workProvinceId))) {
opts.unshift({ value: String(initialData.workProvinceId), label: initialData.workProvince || String(initialData.workProvinceId) });
}
return opts;
}, [provinceQuery, i18n.language, initialData]);
return (
<div className="space-y-4">
<BentoGrid cols={2}>
<BentoCard>
<FormInput
type="text"
label={t("Work company name") || "Işleýän edaranyň/kärhananyň ady"}
required
value={form.workCompany}
onChange={(v) => set("workCompany", v)}
placeholder={t("loanOrderForm.placeholders.companyName") || "Kärhananyň ady"}
error={errors.workCompany}
/>
<FormInput
type="phone"
label={t("HR department work number") || "Işgärler bölüminiň iş belgisi"}
value={form.workCompanyAccountantNumber}
onChange={(v) => set("workCompanyAccountantNumber", v)}
placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"}
error={errors.workCompanyAccountantNumber}
/>
</BentoCard>
<BentoCard>
<FormInput
type="searchable-select"
label={t("Work region") || "Işleýän welaýatyňyz"}
value={form.workRegion}
onChange={(v) => set("workRegion", v)}
options={regionOptions}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
/>
<InfiniteSelect
label={t("Work province") || "Işleýän etrabyňyz"}
value={form.workProvinceId}
onChange={(v) => set("workProvinceId", v)}
options={provinceOptions}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
loading={provinceQuery.isLoading}
isLoadingMore={provinceQuery.isFetchingNextPage}
hasNextPage={!!provinceQuery.hasNextPage}
onLoadMore={() => provinceQuery.fetchNextPage()}
searchValue={provinceSearch}
onSearchChange={setProvinceSearch}
/>
</BentoCard>
</BentoGrid>
<BentoGrid cols={3}>
<BentoCard>
<FormInput
type="text"
label={t("Position") || "Wezipe"}
required
value={form.workPosition}
onChange={(v) => set("workPosition", v)}
placeholder={t("Position") || "Wezipe"}
error={errors.workPosition}
/>
</BentoCard>
<BentoCard>
<FormInput
type="number"
label={t("Salary") || "Zähmet haky"}
required
value={form.workSalary}
onChange={(v) => set("workSalary", v)}
placeholder={t("Salary") || "Zähmet haky"}
error={errors.workSalary}
/>
</BentoCard>
<BentoCard>
<FormInput
type="date"
label={t("Work started at") || "Işe başlan wagtyňyz"}
required
value={form.workStartedAt}
onChange={(v) => set("workStartedAt", v)}
error={errors.workStartedAt}
/>
</BentoCard>
</BentoGrid>
</div>
);
}
function StepGuarantor({ form, errors, set, t }: StepContentProps) {
return (
<div className="space-y-4">
<BentoGrid cols={3}>
<BentoCard>
<FormInput
type="text"
label={t("Guarantor name") || "Zamunyň ady"}
required
value={form.guarantorName}
onChange={(v) => set("guarantorName", v)}
placeholder={t("Guarantor name") || "Zamunyň ady"}
error={errors.guarantorName}
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("Guarantor Surname") || "Zamunyň familiýasy"}
required
value={form.guarantorSurname}
onChange={(v) => set("guarantorSurname", v)}
placeholder={t("Guarantor Surname") || "Zamunyň familiýasy"}
error={errors.guarantorSurname}
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("Guarantor Patronic name") || "Zamunyň atasynyň ady"}
value={form.guarantorPatronicName}
onChange={(v) => set("guarantorPatronicName", v)}
placeholder={t("Guarantor Patronic name") || "Zamunyň atasynyň ady"}
/>
</BentoCard>
</BentoGrid>
<BentoGrid cols={2}>
<BentoCard>
<FormInput
type="searchable-select"
label={t("Passport serie") || "Pasport seriýasy"}
required
value={form.guarantorPassportSerie}
onChange={(v) => set("guarantorPassportSerie", v)}
options={PASSPORT_SERIES_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.guarantorPassportSerie}
/>
</BentoCard>
<BentoCard>
<FormInput
type="passport-id"
label={t("Passport id") || "Pasport belgisi"}
required
value={form.guarantorPassportId}
onChange={(v) => set("guarantorPassportId", v)}
placeholder="999999"
error={errors.guarantorPassportId}
/>
</BentoCard>
</BentoGrid>
<BentoGrid cols={2}>
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Kart maglumatlary"}>
<FormInput
type="card-number"
label={t("Card number") || "Kart belgisi"}
required
value={form.guarantorCardNumber}
onChange={(v) => set("guarantorCardNumber", v)}
placeholder="9999 9999 9999 9999"
error={errors.guarantorCardNumber}
/>
<FormInput
type="card-name"
label={t("Name on card") || "Kartdaky ady"}
required
value={form.guarantorCardName}
onChange={(v) => set("guarantorCardName", v)}
placeholder={t("Name on card") || "Kartdaky ady"}
error={errors.guarantorCardName}
/>
</BentoCard>
<BentoCard title={t("loanOrderForm.titles.cardExpiry") || "Kart möhleti we bellik"}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t("Expiration month") || "Möhleti (aý)"}
required
value={form.guarantorCardMonth}
onChange={(v) => set("guarantorCardMonth", v)}
options={MONTH_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.guarantorCardMonth}
/>
<FormInput
type="searchable-select"
label={t("Expiration year") || "Möhleti (ýyl)"}
required
value={form.guarantorCardYear}
onChange={(v) => set("guarantorCardYear", v)}
options={YEAR_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.guarantorCardYear}
/>
</div>
<FormInput
type="textarea"
label={t("Guarantor Note") || "Zamun belligi"}
value={form.guarantorNote}
onChange={(v) => set("guarantorNote", v)}
placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."}
rows={2}
/>
</BentoCard>
</BentoGrid>
</div>
);
}
function StepGuarantor2({ form, errors, set, t }: StepContentProps) {
return (
<div className="space-y-4">
<BentoGrid cols={3}>
<BentoCard>
<FormInput
type="text"
label={t("Guarantor 2 name") || "2. Zamunyň ady"}
value={form.guarantor2Name}
onChange={(v) => set("guarantor2Name", v)}
placeholder={t("Guarantor 2 name") || "2. Zamunyň ady"}
error={errors.guarantor2Name}
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("Guarantor 2 Surname") || "2. Zamunyň familiýasy"}
value={form.guarantor2Surname}
onChange={(v) => set("guarantor2Surname", v)}
placeholder={t("Guarantor 2 Surname") || "2. Zamunyň familiýasy"}
error={errors.guarantor2Surname}
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("Guarantor 2 Patronic name") || "2. Zamunyň atasynyň ady"}
value={form.guarantor2PatronicName}
onChange={(v) => set("guarantor2PatronicName", v)}
placeholder={t("Guarantor 2 Patronic name") || "2. Zamunyň atasynyň ady"}
/>
</BentoCard>
</BentoGrid>
<BentoGrid cols={2}>
<BentoCard>
<FormInput
type="searchable-select"
label={t("Passport serie") || "Pasport seriýasy"}
value={form.guarantor2PassportSerie}
onChange={(v) => set("guarantor2PassportSerie", v)}
options={PASSPORT_SERIES_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.guarantor2PassportSerie}
/>
</BentoCard>
<BentoCard>
<FormInput
type="passport-id"
label={t("Passport id") || "Pasport belgisi"}
value={form.guarantor2PassportId}
onChange={(v) => set("guarantor2PassportId", v)}
placeholder="999999"
error={errors.guarantor2PassportId}
/>
</BentoCard>
</BentoGrid>
<BentoGrid cols={2}>
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Kart maglumatlary"}>
<FormInput
type="card-number"
label={t("Card number") || "Kart belgisi"}
value={form.guarantor2CardNumber}
onChange={(v) => set("guarantor2CardNumber", v)}
placeholder="9999 9999 9999 9999"
error={errors.guarantor2CardNumber}
/>
<FormInput
type="card-name"
label={t("Name on card") || "Kartdaky ady"}
value={form.guarantor2CardName}
onChange={(v) => set("guarantor2CardName", v)}
placeholder={t("Name on card") || "Kartdaky ady"}
error={errors.guarantor2CardName}
/>
</BentoCard>
<BentoCard title={t("loanOrderForm.titles.cardExpiry") || "Kart möhleti we bellik"}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t("Expiration month") || "Möhleti (aý)"}
value={form.guarantor2CardMonth}
onChange={(v) => set("guarantor2CardMonth", v)}
options={MONTH_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.guarantor2CardMonth}
/>
<FormInput
type="searchable-select"
label={t("Expiration year") || "Möhleti (ýyl)"}
value={form.guarantor2CardYear}
onChange={(v) => set("guarantor2CardYear", v)}
options={YEAR_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.guarantor2CardYear}
/>
</div>
<FormInput
type="textarea"
label={t("Guarantor Note") || "Zamun belligi"}
value={form.guarantor2Note}
onChange={(v) => set("guarantor2Note", v)}
placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."}
rows={2}
/>
</BentoCard>
</BentoGrid>
</div>
);
}
// ─── Props ────────────────────────────────────────────────────────────────────
interface LoanOrderFormProps {
mode: "create" | "edit";
initialData?: LoanOrder;
}
// ─── Main Component ───────────────────────────────────────────────────────────
export function LoanOrderForm({ mode, initialData }: LoanOrderFormProps) {
const { t, i18n } = useTranslation();
const navigate = useNavigate();
const createMutation = useCreateLoanOrder();
const updateMutation = useUpdateLoanOrder();
const isPending = createMutation.isPending || updateMutation.isPending;
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
const {
watch,
setValue,
getValues,
formState: { errors: rhfErrors },
clearErrors,
setError,
} = useForm<LoanOrderFormData>({
defaultValues: initialData
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData), ...(userLocked ? { userId: selfUserId } : {}) }
: { ...DEFAULT_FORM_VALUES, userId: selfUserId },
});
const form = watch();
const [currentStep, setCurrentStep] = useState(0);
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>()));
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(new Set());
const stepsWithErrors = useMemo(() => {
const out = new Set<number>();
visited.forEach((i) => {
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i);
});
return out;
}, [form, mode, visited, i18n.language]);
const set = useCallback(
<K extends keyof LoanOrderFormData>(key: K, value: LoanOrderFormData[K]) => {
(setValue as (name: K, val: LoanOrderFormData[K]) => void)(key, value);
clearErrors(key);
},
[setValue, clearErrors],
);
const allSubmittedErrors = useMemo(() => {
const result: FlatErrors = {};
for (const stepIdx of submittedSteps) {
Object.assign(result, STEPS[stepIdx].validate(form, mode));
}
return result;
}, [form, mode, submittedSteps, i18n.language]);
const errors = useMemo(() => {
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>);
return { ...fromRHF, ...allSubmittedErrors };
}, [rhfErrors, allSubmittedErrors]);
const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t]);
// ── Navigation ──────────────────────────────────────────────────────────────
const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i]));
const markSubmitted = (i: number) => setSubmittedSteps((prev) => new Set([...prev, i]));
const handleNext = () => {
markVisited(currentStep);
markSubmitted(currentStep);
const errs = STEPS[currentStep].validate(form, mode);
if (Object.keys(errs).length > 0) {
Object.entries(errs).forEach(([key, msg]) => {
setError(key as keyof LoanOrderFormData, { type: "manual", message: msg });
});
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" });
};
// ── Submit ──────────────────────────────────────────────────────────────────
const doSubmit = () => {
setVisited(new Set(STEPS.map((_, i) => i)));
setSubmittedSteps(new Set(STEPS.map((_, i) => i)));
const allErrors: FlatErrors = {};
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode));
if (Object.keys(allErrors).length > 0) {
Object.entries(allErrors).forEach(([key, msg]) => {
setError(key as keyof LoanOrderFormData, { type: "manual", message: msg });
});
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)).length > 0) {
setCurrentStep(i);
break;
}
}
return;
}
const payload = buildPayload(getValues());
if (mode === "create") {
createMutation.mutate(payload, { onSuccess: () => navigate("/loan-orders") });
} else if (initialData) {
updateMutation.mutate({ id: initialData.id, payload }, { onSuccess: () => navigate("/loan-orders") });
}
};
// ── StepBar items ───────────────────────────────────────────────────────────
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;
// ── Render ──────────────────────────────────────────────────────────────────
return (
<div className="flex flex-col gap-5">
{/* Page header */}
<div>
<h1 className="text-xl font-semibold text-foreground">
{mode === "create" ? t("loanOrders.create") || "Karz sargyt dörediň" : t("loanOrders.edit") || "Karz sargydy üýtget"}
</h1>
<p className="text-sm text-muted-foreground mt-1">
{mode === "create"
? t("loanOrders.createDescription") || "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň."
: t("loanOrders.editDescription") || "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň."}
</p>
</div>
{/* Step bar */}
<div className="bg-card border border-border rounded-xl p-3 overflow-x-auto">
<StepBarCards steps={stepBarItems} onGoTo={handleGoTo} />
</div>
{/* Step content */}
{currentStep === 0 && <StepStatus {...stepProps} />}
{currentStep === 1 && <StepLoan {...stepProps} initialData={initialData} />}
{currentStep === 2 && <StepLocation {...stepProps} initialData={initialData} />}
{currentStep === 3 && (
<StepPersonal {...stepProps} initialData={initialData} userLocked={userLocked} selfUserId={selfUserId} userName={userName} />
)}
{currentStep === 4 && <StepCard {...stepProps} />}
{currentStep === 5 && <StepPassport {...stepProps} mode={mode} />}
{currentStep === 6 && <StepContact {...stepProps} />}
{currentStep === 7 && <StepJob {...stepProps} initialData={initialData} />}
{currentStep === 8 && <StepGuarantor {...stepProps} />}
{currentStep === 9 && <StepGuarantor2 {...stepProps} />}
{/* Actions */}
<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("loanOrders.create") || "Karz sargyt döredüň" : t("common.save") || "Ýatda sakla"}
loadingLabel={t("common.loading") || "Ýüklenilýär..."}
cancelLabel={t("common.cancel") || "Ýatyr"}
prevLabel={t("common.back") || "Yza"}
nextLabel={t("common.next") || "Indiki"}
/>
</div>
);
}
function mapInitial(order: LoanOrder): Partial<LoanOrderFormData> {
return {
status: order.status ?? "pending",
notes: order.notes ?? order.note ?? "",
source: order.source ?? "web",
satisfiable: order.satisfiable ?? "yes",
loanType: order.loanTypeId != null ? String(order.loanTypeId) : "",
loanAmount: order.loanAmount != null ? String(order.loanAmount) : "",
loanOrderRequiredDocId:
order.loanOrderRequiredDocId != null
? String(order.loanOrderRequiredDocId)
: order.loanOrderRequiredDoc?.id != null
? String(order.loanOrderRequiredDoc.id)
: (order.loanHistory ?? ""),
loanCardNumber: order.loanCardNumber ?? "",
loanCardName: order.loanCardName ?? "",
loanCardMonth: order.loanCardMonth ?? "",
loanCardYear: order.loanCardYear ?? "",
region: order.region ?? "AG",
branchId: order.branchId != null ? String(order.branchId) : "",
userId: order.createdById != null ? String(order.createdById) : order.user?.id != null ? String(order.user.id) : "",
customerName: order.customerName ?? order.firstName ?? "",
customerSurname: order.customerSurname ?? order.lastName ?? "",
customerPatronicName: order.customerPatronicName ?? order.patronicName ?? "",
education: order.education ?? "",
marriageStatus: order.marriageStatus ?? "",
bornAt: formatFromApiDateInput(order.bornAt ?? order.dateOfBirth),
bornPlace: order.bornPlace ?? "",
passportAddress: order.passportAddress ?? order.residence ?? "",
realAddress: order.realAddress ?? order.currentResidence ?? "",
cardNumber: order.cardNumber ?? "",
cardName: order.cardName ?? "",
cardMonth: order.cardMonth ?? order.cardExpMonth ?? "",
cardYear: order.cardYear ?? order.cardExpYear ?? "",
passportSerie: order.passportSerie ?? "",
passportId: order.passportId ?? order.passportNumber ?? "",
passportGivenAt: formatFromApiDateInput(order.passportGivenAt ?? order.passportDateOfIssue),
passportGivenBy: order.passportGivenBy ?? "",
passportOne: order.passportOne ?? order.passportPage1Url ?? "",
passportTwo: order.passportTwo ?? order.passportPage23Url ?? "",
passportThree: order.passportThree ?? order.passportPage89Url ?? "",
passportFour: order.passportFour ?? order.passportPage32Url ?? "",
phone: formatFromApiPhone(order.phone),
phoneAdditional: formatFromApiPhone(order.phoneAdditional),
phoneHome: (order.phoneHome ?? order.homePhone ?? "").replace(/\D/g, ""),
email: order.email ?? "",
workCompany: order.workCompany ?? "",
workCompanyAccountantNumber: formatFromApiPhone(order.workCompanyAccountantNumber ?? order.workHrPhone),
workRegion: order.workRegion ?? "AG",
workProvinceId: order.workProvinceId != null ? String(order.workProvinceId) : order.workCityId != null ? String(order.workCityId) : "",
workPosition: order.workPosition ?? order.position ?? "",
workSalary: order.workSalary != null ? String(order.workSalary) : order.salary != null ? String(order.salary) : "",
workStartedAt: formatFromApiDateInput(order.workStartedAt),
guarantorName: order.guarantorName ?? order.guarantor1Name ?? "",
guarantorSurname: order.guarantorSurname ?? order.guarantor1Surname ?? "",
guarantorPatronicName: order.guarantorPatronicName ?? order.guarantor1Patronic ?? "",
guarantorPassportSerie: order.guarantorPassportSerie ?? order.guarantor1PassportSerie ?? "",
guarantorPassportId: order.guarantorPassportId ?? order.guarantor1PassportNumber ?? "",
guarantorCardNumber: order.guarantorCardNumber ?? order.guarantor1CardNumber ?? "",
guarantorCardName: order.guarantorCardName ?? order.guarantor1CardName ?? "",
guarantorCardMonth: order.guarantorCardMonth ?? order.guarantor1CardExpMonth ?? "",
guarantorCardYear: order.guarantorCardYear ?? order.guarantor1CardExpYear ?? "",
guarantorNote: order.guarantorNote ?? order.guarantor1Note ?? "",
guarantor2Name: order.guarantor2Name ?? "",
guarantor2Surname: order.guarantor2Surname ?? "",
guarantor2PatronicName: order.guarantor2PatronicName ?? order.guarantor2Patronic ?? "",
guarantor2PassportSerie: order.guarantor2PassportSerie ?? "",
guarantor2PassportId: order.guarantor2PassportId ?? order.guarantor2PassportNumber ?? "",
guarantor2CardNumber: order.guarantor2CardNumber ?? "",
guarantor2CardName: order.guarantor2CardName ?? "",
guarantor2CardMonth: order.guarantor2CardMonth ?? order.guarantor2CardExpMonth ?? "",
guarantor2CardYear: order.guarantor2CardYear ?? order.guarantor2CardExpYear ?? "",
guarantor2Note: order.guarantor2Note ?? "",
};
}