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>; function flattenErrors(errors: Record): 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: K, v: LoanOrderFormData[K]) => void; t: TFunction; } // ─── Step panels ────────────────────────────────────────────────────────────── function StepStatus({ form, errors, set, t }: StepContentProps) { const statusOptions = useMemo(() => getStatusOptions(t, "loanOrderStatus"), [t]); return ( set("status", v)} options={statusOptions} error={errors.status} placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} /> set("notes", v)} placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."} rows={3} /> ); } 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( () => (requiredDocsData?.loansDocuments ?? []).map((doc) => ({ value: String(doc.id), label: doc.name, })), [requiredDocsData], ); return (
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} /> set("loanAmount", v)} placeholder={t("loanOrderForm.placeholders.amount") || "0.00"} error={errors.loanAmount} /> set("loanOrderRequiredDocId", v)} options={docOptions} placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} /> set("loanCardNumber", v)} placeholder="9999 9999 9999 9999" /> set("loanCardName", v)} placeholder={t("Loan card name") || "Karz kartdaky ady"} /> set("loanCardMonth", v)} options={MONTH_OPTIONS} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} /> set("loanCardYear", v)} options={YEAR_OPTIONS} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} />
); } 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 ( { set("region", v); set("branchId", ""); }} options={regionOptions} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.region} /> 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} /> ); } 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 (
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} />
set("customerName", v)} placeholder={t("Name") || "Ady"} error={errors.customerName} /> set("customerSurname", v)} placeholder={t("Surname") || "Familiýasy"} error={errors.customerSurname} /> set("customerPatronicName", v)} placeholder={t("Patronic name") || "Atasynyň ady"} />
set("education", v)} options={EDUCATION_OPTIONS} placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} error={errors.education} /> set("marriageStatus", v)} options={MARRIAGE_OPTIONS} placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} error={errors.marriageStatus} /> set("bornAt", v)} error={errors.bornAt} />
set("passportAddress", v)} placeholder={t("loanOrderForm.placeholders.residence") || "Ýazgy edilen salgy"} error={errors.passportAddress} /> set("realAddress", v)} placeholder={t("loanOrderForm.placeholders.currentResidence") || "Häzirki ýaşaýyş ýeri"} /> set("bornPlace", v)} placeholder={t("Born place (passport)") || "Doglan ýeri (pasport)"} />
); } function StepCard({ form, errors, set, t }: StepContentProps) { return ( set("cardNumber", v)} placeholder="9999 9999 9999 9999" error={errors.cardNumber} /> set("cardName", v)} placeholder={t("Name on card") || "Kartdaky ady"} error={errors.cardName} /> set("cardMonth", v)} options={MONTH_OPTIONS} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.cardMonth} /> set("cardYear", v)} options={YEAR_OPTIONS} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.cardYear} /> ); } function StepPassport({ form, errors, set, t, mode }: StepContentProps & { mode: "create" | "edit" }) { return (
set("passportSerie", v)} options={PASSPORT_SERIES_OPTIONS} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.passportSerie} /> set("passportId", v)} placeholder="999999" error={errors.passportId} /> set("passportGivenAt", v)} error={errors.passportGivenAt} /> set("passportGivenBy", v)} placeholder={t("Passport given by") || "Kim tarapyndan berildi"} error={errors.passportGivenBy} /> set("passportOne", v)} error={errors.passportOne} required={mode === "create"} accept="image/*" /> set("passportTwo", v)} error={errors.passportTwo} required={mode === "create"} accept="image/*" /> set("passportThree", v)} accept="image/*" /> set("passportFour", v)} accept="image/*" />
); } function StepContact({ form, errors, set, t }: StepContentProps) { return ( set("phone", v)} placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"} error={errors.phone} /> set("email", v)} placeholder={t("Email") || "E-poçta"} /> set("phoneAdditional", v)} placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"} error={errors.phoneAdditional} /> set("phoneHome", v)} placeholder={t("Home phone") || "Öý telefony"} error={errors.phoneHome} /> ); } 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 (
set("workCompany", v)} placeholder={t("loanOrderForm.placeholders.companyName") || "Kärhananyň ady"} error={errors.workCompany} /> set("workCompanyAccountantNumber", v)} placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"} error={errors.workCompanyAccountantNumber} /> set("workRegion", v)} options={regionOptions} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} /> 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} /> set("workPosition", v)} placeholder={t("Position") || "Wezipe"} error={errors.workPosition} /> set("workSalary", v)} placeholder={t("Salary") || "Zähmet haky"} error={errors.workSalary} /> set("workStartedAt", v)} error={errors.workStartedAt} />
); } function StepGuarantor({ form, errors, set, t }: StepContentProps) { return (
set("guarantorName", v)} placeholder={t("Guarantor name") || "Zamunyň ady"} error={errors.guarantorName} /> set("guarantorSurname", v)} placeholder={t("Guarantor Surname") || "Zamunyň familiýasy"} error={errors.guarantorSurname} /> set("guarantorPatronicName", v)} placeholder={t("Guarantor Patronic name") || "Zamunyň atasynyň ady"} /> set("guarantorPassportSerie", v)} options={PASSPORT_SERIES_OPTIONS} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.guarantorPassportSerie} /> set("guarantorPassportId", v)} placeholder="999999" error={errors.guarantorPassportId} /> set("guarantorCardNumber", v)} placeholder="9999 9999 9999 9999" error={errors.guarantorCardNumber} /> set("guarantorCardName", v)} placeholder={t("Name on card") || "Kartdaky ady"} error={errors.guarantorCardName} />
set("guarantorCardMonth", v)} options={MONTH_OPTIONS} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.guarantorCardMonth} /> set("guarantorCardYear", v)} options={YEAR_OPTIONS} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.guarantorCardYear} />
set("guarantorNote", v)} placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."} rows={2} />
); } function StepGuarantor2({ form, errors, set, t }: StepContentProps) { return (
set("guarantor2Name", v)} placeholder={t("Guarantor 2 name") || "2. Zamunyň ady"} error={errors.guarantor2Name} /> set("guarantor2Surname", v)} placeholder={t("Guarantor 2 Surname") || "2. Zamunyň familiýasy"} error={errors.guarantor2Surname} /> set("guarantor2PatronicName", v)} placeholder={t("Guarantor 2 Patronic name") || "2. Zamunyň atasynyň ady"} /> set("guarantor2PassportSerie", v)} options={PASSPORT_SERIES_OPTIONS} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.guarantor2PassportSerie} /> set("guarantor2PassportId", v)} placeholder="999999" error={errors.guarantor2PassportId} /> set("guarantor2CardNumber", v)} placeholder="9999 9999 9999 9999" error={errors.guarantor2CardNumber} /> set("guarantor2CardName", v)} placeholder={t("Name on card") || "Kartdaky ady"} error={errors.guarantor2CardName} />
set("guarantor2CardMonth", v)} options={MONTH_OPTIONS} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.guarantor2CardMonth} /> set("guarantor2CardYear", v)} options={YEAR_OPTIONS} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.guarantor2CardYear} />
set("guarantor2Note", v)} placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."} rows={2} />
); } // ─── 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({ 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>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set())); const [submittedSteps, setSubmittedSteps] = useState>(new Set()); const stepsWithErrors = useMemo(() => { const out = new Set(); 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( (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); 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 (
{/* Page header */}

{mode === "create" ? t("loanOrders.create") || "Karz sargyt dörediň" : t("loanOrders.edit") || "Karz sargydy üýtget"}

{mode === "create" ? t("loanOrders.createDescription") || "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň." : t("loanOrders.editDescription") || "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň."}

{/* Step bar */}
{/* Step content */} {currentStep === 0 && } {currentStep === 1 && } {currentStep === 2 && } {currentStep === 3 && ( )} {currentStep === 4 && } {currentStep === 5 && } {currentStep === 6 && } {currentStep === 7 && } {currentStep === 8 && } {currentStep === 9 && } {/* Actions */} 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"} />
); } function mapInitial(order: LoanOrder): Partial { 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 ?? "", }; }