refactored some code
This commit is contained in:
@@ -1,314 +1,349 @@
|
||||
import { useState, useMemo, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { User, MapPin, IdCard, CreditCard, Files } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { User, MapPin, IdCard, CreditCard, Files } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
||||
import { BentoGrid, BentoCard } from '@/components/bento'
|
||||
import {
|
||||
useCreateSberPayment,
|
||||
useUpdateSberPayment,
|
||||
} from '@/features/sberPayments/hooks/useSberPayments'
|
||||
import {
|
||||
WELAYATLAR,
|
||||
SAHAMCALAR,
|
||||
STATUSES,
|
||||
type SberPaymentOrder,
|
||||
type PaymentStatus,
|
||||
} from '@/features/sberPayments/api/sberPaymentsApi'
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { useCreateSberPayment, useUpdateSberPayment } from "@/features/sberPayments/hooks/useSberPayments";
|
||||
import { WELAYATLAR, SAHAMCALAR, STATUSES, type SberPaymentOrder, type PaymentStatus } from "@/features/sberPayments/api/sberPaymentsApi";
|
||||
import {
|
||||
validateStep,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
type SberPaymentFormData,
|
||||
} from '@/features/sberPayments/schemas/sberPayment.schema'
|
||||
} from "@/features/sberPayments/schemas/sberPayment.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface SberPaymentFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: SberPaymentOrder | null
|
||||
mode: "create" | "edit";
|
||||
initialData?: SberPaymentOrder | null;
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof SberPaymentFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof SberPaymentFormData, string>>;
|
||||
|
||||
// ─── Flatten RHF errors ──────────────────────────────────────────────────────
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof SberPaymentFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof SberPaymentFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Document lists ───────────────────────────────────────────────────────────
|
||||
|
||||
type AcceptedDocKey =
|
||||
| 'acc_sberbank_card' | 'acc_enrollment' | 'acc_summons'
|
||||
| 'acc_passport_tm' | 'acc_zagran_passport' | 'acc_visa_page'
|
||||
| 'acc_entry_stamp' | 'acc_school_letter'
|
||||
| "acc_sberbank_card"
|
||||
| "acc_enrollment"
|
||||
| "acc_summons"
|
||||
| "acc_passport_tm"
|
||||
| "acc_zagran_passport"
|
||||
| "acc_visa_page"
|
||||
| "acc_entry_stamp"
|
||||
| "acc_school_letter";
|
||||
|
||||
type SentDocKey =
|
||||
| 'snt_passport_tm' | 'snt_zagran_passport' | 'snt_entry_stamp'
|
||||
| 'snt_relation_doc' | 'snt_new_passport_series' | 'snt_old_passport_series'
|
||||
| "snt_passport_tm"
|
||||
| "snt_zagran_passport"
|
||||
| "snt_entry_stamp"
|
||||
| "snt_relation_doc"
|
||||
| "snt_new_passport_series"
|
||||
| "snt_old_passport_series";
|
||||
|
||||
const ACCEPTED_DOCS = (t: (key: string, fallback?: string) => string): { key: AcceptedDocKey; label: string }[] => [
|
||||
{ key: 'acc_sberbank_card', label: t('sberPayments.documents.sberbankCard', 'Talýba degişli SBERBANK kartynyň rekwizitleri') },
|
||||
{ key: 'acc_enrollment', label: t('sberPayments.documents.enrollment', 'Daşary ýurt ÝOM-da okaýandygy baradaky güwänamasy') },
|
||||
{ key: 'acc_summons', label: t('sberPayments.documents.summons', 'Çagyrylma hatynyn göçürmesi') },
|
||||
{ key: 'acc_passport_tm', label: t('sberPayments.documents.passportTm', 'TM içki pasportynyň asyl görnüşi we göçürmesi') },
|
||||
{ key: 'acc_zagran_passport', label: t('sberPayments.documents.zagranPassport', 'Daşary ýurt (zagran) pasportynyň göçürmesi') },
|
||||
{ key: 'acc_visa_page', label: t('sberPayments.documents.visaPage', 'Daşary ýurda rugsat (wizasy) bellenen sahypasynyň göçürmesi') },
|
||||
{ key: 'acc_entry_stamp', label: t('sberPayments.documents.entryStamp', 'Daşary ýurt döwletine girenliği baradaky ştamply sahypasynyň göçürmesi') },
|
||||
{ key: 'acc_school_letter', label: t('sberPayments.documents.schoolLetter', 'ÝOM-dan hat (daşary ýurt dilinde maglumatly)') },
|
||||
]
|
||||
{ key: "acc_sberbank_card", label: t("sberPayments.documents.sberbankCard", "Talýba degişli SBERBANK kartynyň rekwizitleri") },
|
||||
{ key: "acc_enrollment", label: t("sberPayments.documents.enrollment", "Daşary ýurt ÝOM-da okaýandygy baradaky güwänamasy") },
|
||||
{ key: "acc_summons", label: t("sberPayments.documents.summons", "Çagyrylma hatynyn göçürmesi") },
|
||||
{ key: "acc_passport_tm", label: t("sberPayments.documents.passportTm", "TM içki pasportynyň asyl görnüşi we göçürmesi") },
|
||||
{ key: "acc_zagran_passport", label: t("sberPayments.documents.zagranPassport", "Daşary ýurt (zagran) pasportynyň göçürmesi") },
|
||||
{ key: "acc_visa_page", label: t("sberPayments.documents.visaPage", "Daşary ýurda rugsat (wizasy) bellenen sahypasynyň göçürmesi") },
|
||||
{
|
||||
key: "acc_entry_stamp",
|
||||
label: t("sberPayments.documents.entryStamp", "Daşary ýurt döwletine girenliği baradaky ştamply sahypasynyň göçürmesi"),
|
||||
},
|
||||
{ key: "acc_school_letter", label: t("sberPayments.documents.schoolLetter", "ÝOM-dan hat (daşary ýurt dilinde maglumatly)") },
|
||||
];
|
||||
|
||||
const SENT_DOCS = (t: (key: string, fallback?: string) => string): { key: SentDocKey; label: string }[] => [
|
||||
{ key: 'snt_passport_tm', label: t('sberPayments.documents.sentPassportTm', 'Ugradyjynyň TM içki pasportynyň asyl görnüşi we göçürmesi') },
|
||||
{ key: 'snt_zagran_passport', label: t('sberPayments.documents.sentZagranPassport', 'Ugradyjynyň daşary ýurt pasportynyň asyl görnüşi we göçürmesi') },
|
||||
{ key: 'snt_entry_stamp', label: t('sberPayments.documents.sentEntryStamp', 'Ugradyjynyň daşary döwletine girenliği ştamply sahypasynyň göçürmesi') },
|
||||
{ key: 'snt_relation_doc', label: t('sberPayments.documents.sentRelationDoc', 'Ugradyjy we kabul edijiniň garyndaşlyk tassyklaýjy resminamasynyn göçürmesi') },
|
||||
{ key: 'snt_new_passport_series', label: t('sberPayments.documents.sentNewPassportSeries', 'Ugradyjy/kabul ediji täze (2015+) pasport seriýasy maglumaty') },
|
||||
{ key: 'snt_old_passport_series', label: t('sberPayments.documents.sentOldPassportSeries', 'Ugradyjy/kabul ediji köne pasport seriýasy baradaky güwänamasy') },
|
||||
]
|
||||
{
|
||||
key: "snt_passport_tm",
|
||||
label: t("sberPayments.documents.sentPassportTm", "Ugradyjynyň TM içki pasportynyň asyl görnüşi we göçürmesi"),
|
||||
},
|
||||
{
|
||||
key: "snt_zagran_passport",
|
||||
label: t("sberPayments.documents.sentZagranPassport", "Ugradyjynyň daşary ýurt pasportynyň asyl görnüşi we göçürmesi"),
|
||||
},
|
||||
{
|
||||
key: "snt_entry_stamp",
|
||||
label: t("sberPayments.documents.sentEntryStamp", "Ugradyjynyň daşary döwletine girenliği ştamply sahypasynyň göçürmesi"),
|
||||
},
|
||||
{
|
||||
key: "snt_relation_doc",
|
||||
label: t("sberPayments.documents.sentRelationDoc", "Ugradyjy we kabul edijiniň garyndaşlyk tassyklaýjy resminamasynyn göçürmesi"),
|
||||
},
|
||||
{
|
||||
key: "snt_new_passport_series",
|
||||
label: t("sberPayments.documents.sentNewPassportSeries", "Ugradyjy/kabul ediji täze (2015+) pasport seriýasy maglumaty"),
|
||||
},
|
||||
{
|
||||
key: "snt_old_passport_series",
|
||||
label: t("sberPayments.documents.sentOldPassportSeries", "Ugradyjy/kabul ediji köne pasport seriýasy baradaky güwänamasy"),
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
|
||||
function StepGeneral({
|
||||
form, errors, set, t,
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
}: {
|
||||
form: SberPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
t: (key: string, fallback?: string) => string
|
||||
form: SberPaymentFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('sberPayments.cards.musteri', 'Müşderi')}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('sberPayments.fields.client_id', 'Ulanyjy')}
|
||||
label={t("sberPayments.fields.client_id", "Ulanyjy")}
|
||||
value={form.client_id}
|
||||
onChange={(v) => set('client_id', v)}
|
||||
onChange={(v) => set("client_id", v)}
|
||||
options={[]}
|
||||
placeholder={t('sberPayments.placeholders.select', 'Saýlamak üçin basyň')}
|
||||
placeholder={t("sberPayments.placeholders.select", "Saýlamak üçin basyň")}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('sberPayments.cards.status', 'Status')}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('sberPayments.fields.status', 'Status')}
|
||||
label={t("sberPayments.fields.status", "Status")}
|
||||
value={form.status}
|
||||
onChange={(v) => set('status', v as PaymentStatus)}
|
||||
onChange={(v) => set("status", v as PaymentStatus)}
|
||||
options={STATUSES}
|
||||
error={errors.status}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('sberPayments.cards.bellik', 'Bellik')} span="full">
|
||||
<BentoCard span="full">
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t('sberPayments.fields.bellik', 'Bellik')}
|
||||
label={t("sberPayments.fields.bellik", "Bellik")}
|
||||
value={form.bellik}
|
||||
onChange={(v) => set('bellik', v)}
|
||||
placeholder={t('sberPayments.placeholders.bellik', 'Bellik...')}
|
||||
onChange={(v) => set("bellik", v)}
|
||||
placeholder={t("sberPayments.placeholders.bellik", "Bellik...")}
|
||||
rows={2}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepLocation({
|
||||
form, errors, set, t,
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
}: {
|
||||
form: SberPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
t: (key: string, fallback?: string) => string
|
||||
form: SberPaymentFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
}) {
|
||||
const branches = form.welayat ? (SAHAMCALAR[form.welayat] ?? []) : []
|
||||
const branches = form.welayat ? (SAHAMCALAR[form.welayat] ?? []) : [];
|
||||
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('sberPayments.cards.welayat', 'Welaýat')}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('sberPayments.fields.welayat', 'Welaýat')}
|
||||
label={t("sberPayments.fields.welayat", "Welaýat")}
|
||||
value={form.welayat}
|
||||
onChange={(v) => { set('welayat', v); set('sahamca', '') }}
|
||||
onChange={(v) => {
|
||||
set("welayat", v);
|
||||
set("sahamca", "");
|
||||
}}
|
||||
options={WELAYATLAR.map((w) => ({ value: w, label: w }))}
|
||||
placeholder={t('sberPayments.placeholders.welayat', 'Aşgabat')}
|
||||
placeholder={t("sberPayments.placeholders.welayat", "Aşgabat")}
|
||||
error={errors.welayat}
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('sberPayments.hints.selectRegion', 'Welaýaty saýlasaňyz şahamçalar güncellenar.')}
|
||||
</p>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('sberPayments.cards.sahamca', 'Şahamça')}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('sberPayments.fields.sahamca', 'Şahamça')}
|
||||
label={t("sberPayments.fields.sahamca", "Şahamça")}
|
||||
value={form.sahamca}
|
||||
onChange={(v) => set('sahamca', v)}
|
||||
onChange={(v) => set("sahamca", v)}
|
||||
options={branches.map((b) => ({ value: b, label: b }))}
|
||||
placeholder={t('sberPayments.placeholders.select', 'Saýlamak üçin basyň')}
|
||||
placeholder={t("sberPayments.placeholders.select", "Saýlamak üçin basyň")}
|
||||
disabled={!form.welayat}
|
||||
error={errors.sahamca}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({
|
||||
form, errors, set, t,
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
}: {
|
||||
form: SberPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
t: (key: string, fallback?: string) => string
|
||||
form: SberPaymentFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('sberPayments.cards.atFamilia', 'At-familýa')}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('sberPayments.fields.lastName', 'Pasportdaky familiýa')}
|
||||
label={t("sberPayments.fields.lastName", "Pasportdaky familiýa")}
|
||||
value={form.lastName}
|
||||
onChange={(v) => set('lastName', v)}
|
||||
placeholder={t('sberPayments.placeholders.lastName', 'NURYYEW')}
|
||||
onChange={(v) => set("lastName", v)}
|
||||
placeholder={t("sberPayments.placeholders.lastName", "NURYYEW")}
|
||||
error={errors.lastName}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('sberPayments.fields.firstName', 'Pasportdaky ady')}
|
||||
label={t("sberPayments.fields.firstName", "Pasportdaky ady")}
|
||||
value={form.firstName}
|
||||
onChange={(v) => set('firstName', v)}
|
||||
placeholder={t('sberPayments.placeholders.firstName', 'HAÝDAR')}
|
||||
onChange={(v) => set("firstName", v)}
|
||||
placeholder={t("sberPayments.placeholders.firstName", "HAÝDAR")}
|
||||
error={errors.firstName}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('sberPayments.cards.kontakt', 'Kontakt')}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone"
|
||||
label={t('sberPayments.fields.phone', 'Telefon')}
|
||||
label={t("sberPayments.fields.phone", "Telefon")}
|
||||
value={form.phone}
|
||||
onChange={(v) => set('phone', v)}
|
||||
onChange={(v) => set("phone", v)}
|
||||
error={errors.phone}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="email"
|
||||
label={t('sberPayments.fields.email', 'E-poçta')}
|
||||
label={t("sberPayments.fields.email", "E-poçta")}
|
||||
value={form.email}
|
||||
onChange={(v) => set('email', v)}
|
||||
placeholder={t('sberPayments.placeholders.email', 'email@example.com')}
|
||||
onChange={(v) => set("email", v)}
|
||||
placeholder={t("sberPayments.placeholders.email", "email@example.com")}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('sberPayments.cards.yasysYeri', 'Häzirki ýaşyş ýeri')} span="full">
|
||||
<BentoCard span="full">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('sberPayments.fields.address', 'Salgy')}
|
||||
label={t("sberPayments.fields.address", "Salgy")}
|
||||
value={form.address}
|
||||
onChange={(v) => set('address', v)}
|
||||
placeholder={t('sberPayments.placeholders.address', 'Köçe, jaý belgisi...')}
|
||||
onChange={(v) => set("address", v)}
|
||||
placeholder={t("sberPayments.placeholders.address", "Köçe, jaý belgisi...")}
|
||||
error={errors.address}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepPayment({
|
||||
form, errors, set, t,
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
}: {
|
||||
form: SberPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
t: (key: string, fallback?: string) => string
|
||||
form: SberPaymentFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('sberPayments.cards.pasportMaglumatlary', 'Pasport maglumatlary')}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('sberPayments.fields.passportSeries', 'Pasport seriýasy')}
|
||||
label={t("sberPayments.fields.passportSeries", "Pasport seriýasy")}
|
||||
value={form.passportSeries}
|
||||
onChange={(v) => set('passportSeries', v)}
|
||||
onChange={(v) => set("passportSeries", v)}
|
||||
options={[
|
||||
{ value: 'II-MA', label: 'II-MA' },
|
||||
{ value: 'II-MB', label: 'II-MB' },
|
||||
{ value: 'II-MC', label: 'II-MC' },
|
||||
{ value: 'II-MD', label: 'II-MD' },
|
||||
{ value: "II-MA", label: "II-MA" },
|
||||
{ value: "II-MB", label: "II-MB" },
|
||||
{ value: "II-MC", label: "II-MC" },
|
||||
{ value: "II-MD", label: "II-MD" },
|
||||
]}
|
||||
placeholder={t('sberPayments.placeholders.select', 'Saýlamak üçin basyň')}
|
||||
placeholder={t("sberPayments.placeholders.select", "Saýlamak üçin basyň")}
|
||||
error={errors.passportSeries}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('sberPayments.fields.passportNumber', 'Pasport nomeri')}
|
||||
label={t("sberPayments.fields.passportNumber", "Pasport nomeri")}
|
||||
value={form.passportNumber}
|
||||
onChange={(v) => set('passportNumber', v)}
|
||||
placeholder={t('sberPayments.placeholders.passportNumber', 'A123456')}
|
||||
onChange={(v) => set("passportNumber", v)}
|
||||
placeholder={t("sberPayments.placeholders.passportNumber", "A123456")}
|
||||
error={errors.passportNumber}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('sberPayments.cards.ugradyjy', 'Ugradyjy')}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('sberPayments.fields.fullName', 'Ady Familiýasy Atasynyň ady')}
|
||||
label={t("sberPayments.fields.fullName", "Ady Familiýasy Atasynyň ady")}
|
||||
value={form.fullName}
|
||||
onChange={(v) => set('fullName', v)}
|
||||
placeholder={t('sberPayments.placeholders.fullName', 'Doly ady...')}
|
||||
onChange={(v) => set("fullName", v)}
|
||||
placeholder={t("sberPayments.placeholders.fullName", "Doly ady...")}
|
||||
error={errors.fullName}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('sberPayments.fields.accountNumber', 'Goýum hasaby')}
|
||||
label={t("sberPayments.fields.accountNumber", "Goýum hasaby")}
|
||||
value={form.accountNumber}
|
||||
onChange={(v) => set('accountNumber', v)}
|
||||
placeholder={t('sberPayments.placeholders.accountNumber', '1234 5678 ...')}
|
||||
onChange={(v) => set("accountNumber", v)}
|
||||
placeholder={t("sberPayments.placeholders.accountNumber", "1234 5678 ...")}
|
||||
error={errors.accountNumber}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepDocs({
|
||||
form, set, t,
|
||||
form,
|
||||
set,
|
||||
t,
|
||||
}: {
|
||||
form: SberPaymentFormData
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void
|
||||
t: (key: string, fallback?: string) => string
|
||||
form: SberPaymentFormData;
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('sberPayments.cards.documentsAccepted', 'Kabul ediji talyp — 8 resminama')}>
|
||||
<BentoCard>
|
||||
<div className="space-y-3">
|
||||
{ACCEPTED_DOCS(t).map(({ key, label }) => (
|
||||
<FormInput
|
||||
@@ -323,7 +358,7 @@ function StepDocs({
|
||||
</div>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('sberPayments.cards.documentsSent', 'Ugradyjy — 6 resminama')}>
|
||||
<BentoCard>
|
||||
<div className="space-y-3">
|
||||
{SENT_DOCS(t).map(({ key, label }) => (
|
||||
<FormInput
|
||||
@@ -338,196 +373,236 @@ function StepDocs({
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
|
||||
interface StepDef {
|
||||
id: string
|
||||
titleKey: string
|
||||
titleFallback: string
|
||||
subtitleKey: string
|
||||
subtitleFallback: string
|
||||
icon: LucideIcon
|
||||
validate: (form: SberPaymentFormData, mode: 'create' | 'edit', t: (key: string, fallback?: string) => string) => FlatErrors
|
||||
id: string;
|
||||
titleKey: string;
|
||||
titleFallback: string;
|
||||
subtitleKey: string;
|
||||
subtitleFallback: string;
|
||||
icon: LucideIcon;
|
||||
validate: (form: SberPaymentFormData, mode: "create" | "edit", t: (key: string, fallback?: string) => string) => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
{ id: 'general', titleKey: 'sberPayments.steps.general.title', titleFallback: 'Esasy', subtitleKey: 'sberPayments.steps.general.subtitle', subtitleFallback: 'Status, müşderi', icon: User, validate: (f, m, t) => validateStep(0, f, m, t) },
|
||||
{ id: 'location', titleKey: 'sberPayments.steps.location.title', titleFallback: 'Lokasiýa', subtitleKey: 'sberPayments.steps.location.subtitle', subtitleFallback: 'Welaýat, şahamça', icon: MapPin, validate: (f, m, t) => validateStep(1, f, m, t) },
|
||||
{ id: 'personal', titleKey: 'sberPayments.steps.personal.title', titleFallback: 'Şahsy', subtitleKey: 'sberPayments.steps.personal.subtitle', subtitleFallback: 'Pasport, kontakt', icon: IdCard, validate: (f, m, t) => validateStep(2, f, m, t) },
|
||||
{ id: 'payment', titleKey: 'sberPayments.steps.payment.title', titleFallback: 'Töleg', subtitleKey: 'sberPayments.steps.payment.subtitle', subtitleFallback: 'Hasap, ugradyjy', icon: CreditCard, validate: (f, m, t) => validateStep(3, f, m, t) },
|
||||
{ id: 'docs', titleKey: 'sberPayments.steps.docs.title', titleFallback: 'Resminamalar', subtitleKey: 'sberPayments.steps.docs.subtitle', subtitleFallback: '14 resminama', icon: Files, validate: () => ({}) },
|
||||
]
|
||||
{
|
||||
id: "general",
|
||||
titleKey: "sberPayments.steps.general.title",
|
||||
titleFallback: "Esasy",
|
||||
subtitleKey: "sberPayments.steps.general.subtitle",
|
||||
subtitleFallback: "Status, müşderi",
|
||||
icon: User,
|
||||
validate: (f, m, t) => validateStep(0, f, m, t),
|
||||
},
|
||||
{
|
||||
id: "location",
|
||||
titleKey: "sberPayments.steps.location.title",
|
||||
titleFallback: "Lokasiýa",
|
||||
subtitleKey: "sberPayments.steps.location.subtitle",
|
||||
subtitleFallback: "Welaýat, şahamça",
|
||||
icon: MapPin,
|
||||
validate: (f, m, t) => validateStep(1, f, m, t),
|
||||
},
|
||||
{
|
||||
id: "personal",
|
||||
titleKey: "sberPayments.steps.personal.title",
|
||||
titleFallback: "Şahsy",
|
||||
subtitleKey: "sberPayments.steps.personal.subtitle",
|
||||
subtitleFallback: "Pasport, kontakt",
|
||||
icon: IdCard,
|
||||
validate: (f, m, t) => validateStep(2, f, m, t),
|
||||
},
|
||||
{
|
||||
id: "payment",
|
||||
titleKey: "sberPayments.steps.payment.title",
|
||||
titleFallback: "Töleg",
|
||||
subtitleKey: "sberPayments.steps.payment.subtitle",
|
||||
subtitleFallback: "Hasap, ugradyjy",
|
||||
icon: CreditCard,
|
||||
validate: (f, m, t) => validateStep(3, f, m, t),
|
||||
},
|
||||
{
|
||||
id: "docs",
|
||||
titleKey: "sberPayments.steps.docs.title",
|
||||
titleFallback: "Resminamalar",
|
||||
subtitleKey: "sberPayments.steps.docs.subtitle",
|
||||
subtitleFallback: "14 resminama",
|
||||
icon: Files,
|
||||
validate: () => ({}),
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Initial data mapper ──────────────────────────────────────────────────────
|
||||
|
||||
function mapInitialData(data: SberPaymentOrder): Partial<SberPaymentFormData> {
|
||||
return {
|
||||
welayat: data.welayat,
|
||||
sahamca: data.sahamca,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
address: data.address,
|
||||
status: data.status,
|
||||
bellik: data.bellik,
|
||||
accountNumber: data.accountNumber,
|
||||
welayat: data.welayat,
|
||||
sahamca: data.sahamca,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
address: data.address,
|
||||
status: data.status,
|
||||
bellik: data.bellik,
|
||||
accountNumber: data.accountNumber,
|
||||
passportSeries: data.passportSeries,
|
||||
passportNumber: data.passportNumber,
|
||||
fullName: data.fullName,
|
||||
}
|
||||
fullName: data.fullName,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Main component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function SberPaymentForm({ mode, initialData }: SberPaymentFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const navigate = useNavigate()
|
||||
const createMutation = useCreateSberPayment()
|
||||
const updateMutation = useUpdateSberPayment()
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback((key, fallback) => _t(key, fallback ?? key) as string, [_t]);
|
||||
const navigate = useNavigate();
|
||||
const createMutation = useCreateSberPayment();
|
||||
const updateMutation = useUpdateSberPayment();
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, setError,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<SberPaymentFormData>({
|
||||
defaultValues: mode === 'edit' && initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitialData(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
defaultValues: mode === "edit" && initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitialData(initialData) } : DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
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 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>()
|
||||
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, i18n.language, t])
|
||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) out.add(i);
|
||||
});
|
||||
return out;
|
||||
}, [form, mode, visited, i18n.language, t]);
|
||||
|
||||
const set = useCallback(<K extends keyof SberPaymentFormData>(key: K, value: SberPaymentFormData[K]) => {
|
||||
(setValue as (name: K, val: SberPaymentFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
const set = useCallback(
|
||||
<K extends keyof SberPaymentFormData>(key: K, value: SberPaymentFormData[K]) => {
|
||||
(setValue as (name: K, val: SberPaymentFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const allSubmittedErrors = useMemo(() => {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const stepIdx of submittedSteps) {
|
||||
Object.assign(result, STEPS[stepIdx].validate(form, mode, t))
|
||||
Object.assign(result, STEPS[stepIdx].validate(form, mode, t));
|
||||
}
|
||||
return result
|
||||
}, [form, mode, submittedSteps, i18n.language, t])
|
||||
return result;
|
||||
}, [form, mode, submittedSteps, i18n.language, t]);
|
||||
|
||||
const errors = useMemo(() => {
|
||||
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>)
|
||||
return { ...fromRHF, ...allSubmittedErrors }
|
||||
}, [rhfErrors, allSubmittedErrors])
|
||||
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>);
|
||||
return { ...fromRHF, ...allSubmittedErrors };
|
||||
}, [rhfErrors, allSubmittedErrors]);
|
||||
|
||||
// ── Navigation ──────────────────────────────────────────────────────────────
|
||||
|
||||
const markVisited = (i: number) =>
|
||||
setVisited((prev) => new Set([...prev, i]))
|
||||
const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i]));
|
||||
|
||||
const markSubmitted = (i: number) =>
|
||||
setSubmittedSteps((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, t)
|
||||
markVisited(currentStep);
|
||||
markSubmitted(currentStep);
|
||||
const errs = STEPS[currentStep].validate(form, mode, t);
|
||||
if (Object.keys(errs).length > 0) {
|
||||
Object.entries(errs).forEach(([key, msg]) => {
|
||||
setError(key as keyof SberPaymentFormData, { type: 'manual', message: msg })
|
||||
})
|
||||
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||
return
|
||||
setError(key as keyof SberPaymentFormData, { 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' })
|
||||
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' })
|
||||
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' })
|
||||
}
|
||||
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)))
|
||||
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, t))
|
||||
const allErrors: FlatErrors = {};
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode, t));
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
Object.entries(allErrors).forEach(([key, msg]) => {
|
||||
setError(key as keyof SberPaymentFormData, { type: 'manual', message: msg })
|
||||
})
|
||||
toast.error(t('common.errors.requiredFieldsMissing', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
||||
setError(key as keyof SberPaymentFormData, { 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, t)).length > 0) {
|
||||
setCurrentStep(i); break
|
||||
setCurrentStep(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, { onSuccess: () => navigate('/sber-payments') })
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, { onSuccess: () => navigate("/sber-payments") });
|
||||
} else if (initialData) {
|
||||
updateMutation.mutate({ ...payload, id: initialData.id }, { onSuccess: () => navigate('/sber-payments') })
|
||||
updateMutation.mutate({ ...payload, id: initialData.id }, { onSuccess: () => navigate("/sber-payments") });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── StepBarCards data ──
|
||||
|
||||
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
|
||||
const isActive = i === currentStep
|
||||
const hasErrors = stepsWithErrors.has(i)
|
||||
const isDone = visited.has(i) && !hasErrors
|
||||
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,
|
||||
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',
|
||||
}
|
||||
})
|
||||
icon: s.icon,
|
||||
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||
};
|
||||
});
|
||||
|
||||
const isLastStep = currentStep === STEPS.length - 1
|
||||
const isLastStep = currentStep === STEPS.length - 1;
|
||||
|
||||
return (
|
||||
<div className="mx-auto space-y-6 pb-8">
|
||||
<h1 className="text-2xl font-bold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('sberPayments.formTitle.create', 'Sber töleg dörediň')
|
||||
: t('sberPayments.formTitle.edit', 'Sber töleg redaktirläň')}
|
||||
{mode === "create"
|
||||
? t("sberPayments.formTitle.create", "Sber töleg dörediň")
|
||||
: t("sberPayments.formTitle.edit", "Sber töleg redaktirläň")}
|
||||
</h1>
|
||||
|
||||
{/* Step bar */}
|
||||
@@ -536,27 +611,27 @@ export function SberPaymentForm({ mode, initialData }: SberPaymentFormProps) {
|
||||
</div>
|
||||
|
||||
{/* Step content */}
|
||||
{STEPS[currentStep].id === 'general' && <StepGeneral form={form} errors={errors} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === 'location' && <StepLocation form={form} errors={errors} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === 'personal' && <StepPersonal form={form} errors={errors} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === 'payment' && <StepPayment form={form} errors={errors} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === 'docs' && <StepDocs form={form} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === "general" && <StepGeneral form={form} errors={errors} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === "location" && <StepLocation form={form} errors={errors} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === "personal" && <StepPersonal form={form} errors={errors} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === "payment" && <StepPayment form={form} errors={errors} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === "docs" && <StepDocs form={form} set={set} t={t} />}
|
||||
|
||||
{/* Actions */}
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onCancel={() => navigate('/sber-payments')}
|
||||
onCancel={() => navigate("/sber-payments")}
|
||||
onPrev={currentStep > 0 ? handleBack : undefined}
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? doSubmit : undefined}
|
||||
submitLabel={
|
||||
mode === 'create'
|
||||
? t('sberPayments.buttons.create', 'Sber töleg (talyplar üçin) dörediň')
|
||||
: t('sberPayments.buttons.update', 'Ýatda sakla')
|
||||
mode === "create"
|
||||
? t("sberPayments.buttons.create", "Sber töleg (talyplar üçin) dörediň")
|
||||
: t("sberPayments.buttons.update", "Ýatda sakla")
|
||||
}
|
||||
loadingLabel={t('sberPayments.buttons.loading', 'Ýüklenýär...')}
|
||||
loadingLabel={t("sberPayments.buttons.loading", "Ýüklenýär...")}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,331 +1,369 @@
|
||||
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 {
|
||||
User, MapPin, IdCard, CreditCard, Files,
|
||||
} from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
||||
import { BentoGrid, BentoCard } from '@/components/bento'
|
||||
import type { IntlPaymentItem, IntlPaymentCreatePayload } from '../api/visaMasterPaymentsApi'
|
||||
import { useCreateIntlPayment, useUpdateIntlPayment } from '../hooks/useVisaMasterPayments'
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/visaMasterPayment.schema'
|
||||
import type { IntlPaymentFormData } from '../schemas/visaMasterPayment.schema'
|
||||
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 { User, MapPin, IdCard, CreditCard, Files } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { IntlPaymentItem, IntlPaymentCreatePayload } from "../api/visaMasterPaymentsApi";
|
||||
import { useCreateIntlPayment, useUpdateIntlPayment } from "../hooks/useVisaMasterPayments";
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/visaMasterPayment.schema";
|
||||
import type { IntlPaymentFormData } from "../schemas/visaMasterPayment.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface IntlPaymentFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: IntlPaymentItem
|
||||
mode: "create" | "edit";
|
||||
initialData?: IntlPaymentItem;
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof IntlPaymentFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof IntlPaymentFormData, string>>;
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: 'pending', label: 'Garaşylýar' },
|
||||
{ value: 'approved', label: 'Tassyklandy' },
|
||||
{ value: 'rejected', label: 'Ret edildi' },
|
||||
]
|
||||
{ value: "pending", label: "Garaşylýar" },
|
||||
{ value: "approved", label: "Tassyklandy" },
|
||||
{ value: "rejected", label: "Ret edildi" },
|
||||
];
|
||||
|
||||
const CURRENCY_OPTIONS = [
|
||||
{ value: 'visa', label: 'Visa' },
|
||||
{ value: 'mastercard', label: 'MasterCard' },
|
||||
]
|
||||
{ value: "visa", label: "Visa" },
|
||||
{ value: "mastercard", label: "MasterCard" },
|
||||
];
|
||||
|
||||
const PASSPORT_SERIES_OPTIONS = [
|
||||
{ value: 'I', label: 'I' },
|
||||
{ value: 'II', label: 'II' },
|
||||
{ value: 'I-MR', label: 'I-MR' },
|
||||
{ value: 'II-MR', label: 'II-MR' },
|
||||
]
|
||||
{ value: "I", label: "I" },
|
||||
{ value: "II", label: "II" },
|
||||
{ value: "I-MR", label: "I-MR" },
|
||||
{ value: "II-MR", label: "II-MR" },
|
||||
];
|
||||
|
||||
const PROVINCE_OPTIONS = [
|
||||
{ value: 'ashgabat', label: 'Aşgabat' },
|
||||
{ value: 'ahal', label: 'Ahal' },
|
||||
{ value: 'mary', label: 'Mary' },
|
||||
{ value: 'dasoguz', label: 'Daşoguz' },
|
||||
{ value: 'lebap', label: 'Lebap' },
|
||||
{ value: 'balkan', label: 'Balkan' },
|
||||
]
|
||||
{ value: "ashgabat", label: "Aşgabat" },
|
||||
{ value: "ahal", label: "Ahal" },
|
||||
{ value: "mary", label: "Mary" },
|
||||
{ value: "dasoguz", label: "Daşoguz" },
|
||||
{ value: "lebap", label: "Lebap" },
|
||||
{ value: "balkan", label: "Balkan" },
|
||||
];
|
||||
|
||||
const KABUL_DOCS: { key: keyof IntlPaymentFormData; label: string }[] = [
|
||||
{ key: 'doc_sberbank_account', label: 'Talypyň SBERBANK kartynyň rekwizitleri' },
|
||||
{ key: 'doc_school_enrollment', label: 'Daşary ýurt ÝOM-da okaýandygy barada güwänamasy' },
|
||||
{ key: 'doc_summons', label: 'Çagyrylma hatynyn göçürmesi' },
|
||||
{ key: 'doc_passport_tm', label: 'TM içki pasportynyň asyl görnüşi we göçürmesi' },
|
||||
{ key: 'doc_foreign_passport', label: 'Daşary ýurt pasportynyň göçürmesi' },
|
||||
{ key: 'doc_foreign_passport_copy', label: 'Bakýan döwlet sahypasynyň göçürmesi' },
|
||||
{ key: 'doc_exit_permission', label: 'Çykyş-giriş rugsat bellikli sahypa göçürmesi' },
|
||||
{ key: 'doc_school_foreign_info', label: 'ÝOM-dan hat (okuw dilinde)' },
|
||||
{ key: 'doc_school_departure_info', label: 'ÝOM-dan hat (döwlet dilinde)' },
|
||||
]
|
||||
{ key: "doc_sberbank_account", label: "Talypyň SBERBANK kartynyň rekwizitleri" },
|
||||
{ key: "doc_school_enrollment", label: "Daşary ýurt ÝOM-da okaýandygy barada güwänamasy" },
|
||||
{ key: "doc_summons", label: "Çagyrylma hatynyn göçürmesi" },
|
||||
{ key: "doc_passport_tm", label: "TM içki pasportynyň asyl görnüşi we göçürmesi" },
|
||||
{ key: "doc_foreign_passport", label: "Daşary ýurt pasportynyň göçürmesi" },
|
||||
{ key: "doc_foreign_passport_copy", label: "Bakýan döwlet sahypasynyň göçürmesi" },
|
||||
{ key: "doc_exit_permission", label: "Çykyş-giriş rugsat bellikli sahypa göçürmesi" },
|
||||
{ key: "doc_school_foreign_info", label: "ÝOM-dan hat (okuw dilinde)" },
|
||||
{ key: "doc_school_departure_info", label: "ÝOM-dan hat (döwlet dilinde)" },
|
||||
];
|
||||
|
||||
const UPGRAD_DOCS: { key: keyof IntlPaymentFormData; label: string }[] = [
|
||||
{ key: 'upd_doc_passport_tm', label: 'TM içki pasportynyň asyl görnüşi (upd)' },
|
||||
{ key: 'upd_doc_foreign_passport', label: 'Daşary ýurt pasportynyň göçürmesi (upd)' },
|
||||
{ key: 'upd_doc_visa', label: 'Wiza bellenen sahypasynyň göçürmesi' },
|
||||
{ key: 'upd_doc_acceptance_letter', label: 'Kabul haty we beýleki resminamalar' },
|
||||
{ key: 'upd_doc_passport_biometric', label: 'Täze (2015+) pasport seriýasy maglumatlary' },
|
||||
{ key: 'upd_doc_passport_old', label: 'Könelräk pasport seriýasy maglumatlary' },
|
||||
]
|
||||
{ key: "upd_doc_passport_tm", label: "TM içki pasportynyň asyl görnüşi (upd)" },
|
||||
{ key: "upd_doc_foreign_passport", label: "Daşary ýurt pasportynyň göçürmesi (upd)" },
|
||||
{ key: "upd_doc_visa", label: "Wiza bellenen sahypasynyň göçürmesi" },
|
||||
{ key: "upd_doc_acceptance_letter", label: "Kabul haty we beýleki resminamalar" },
|
||||
{ key: "upd_doc_passport_biometric", label: "Täze (2015+) pasport seriýasy maglumatlary" },
|
||||
{ key: "upd_doc_passport_old", label: "Könelräk pasport seriýasy maglumatlary" },
|
||||
];
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
|
||||
type StepId = 'general' | 'location' | 'personal' | 'payment' | 'docs'
|
||||
type StepId = "general" | "location" | "personal" | "payment" | "docs";
|
||||
|
||||
interface StepDef {
|
||||
id: StepId
|
||||
titleKey: string
|
||||
titleFallback: string
|
||||
subtitleKey: string
|
||||
subtitleFallback: string
|
||||
icon: LucideIcon
|
||||
validate: (form: IntlPaymentFormData, mode: 'create' | 'edit') => FlatErrors
|
||||
id: StepId;
|
||||
titleKey: string;
|
||||
titleFallback: string;
|
||||
subtitleKey: string;
|
||||
subtitleFallback: string;
|
||||
icon: LucideIcon;
|
||||
validate: (form: IntlPaymentFormData, mode: "create" | "edit") => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
{ id: 'general', titleKey: 'intlPaymentForm.steps.general.title', titleFallback: 'Esasy', subtitleKey: 'intlPaymentForm.steps.general.subtitle', subtitleFallback: 'Status, müşderi', icon: User, validate: (f, m) => validateStep(0, f, m) },
|
||||
{ id: 'location', titleKey: 'intlPaymentForm.steps.location.title', titleFallback: 'Lokasiýa', subtitleKey: 'intlPaymentForm.steps.location.subtitle', subtitleFallback: 'Welaýat, şahamça', icon: MapPin, validate: (f, m) => validateStep(1, f, m) },
|
||||
{ id: 'personal', titleKey: 'intlPaymentForm.steps.personal.title', titleFallback: 'Şahsy', subtitleKey: 'intlPaymentForm.steps.personal.subtitle', subtitleFallback: 'Pasport, kontakt', icon: IdCard, validate: (f, m) => validateStep(2, f, m) },
|
||||
{ id: 'payment', titleKey: 'intlPaymentForm.steps.payment.title', titleFallback: 'Töleg', subtitleKey: 'intlPaymentForm.steps.payment.subtitle', subtitleFallback: 'Töleýji, kabul ediji', icon: CreditCard, validate: (f, m) => validateStep(3, f, m) },
|
||||
{ id: 'docs', titleKey: 'intlPaymentForm.steps.docs.title', titleFallback: 'Resminamalar', subtitleKey: 'intlPaymentForm.steps.docs.subtitle', subtitleFallback: '15 resminama', icon: Files, validate: () => ({}) },
|
||||
]
|
||||
{
|
||||
id: "general",
|
||||
titleKey: "intlPaymentForm.steps.general.title",
|
||||
titleFallback: "Esasy",
|
||||
subtitleKey: "intlPaymentForm.steps.general.subtitle",
|
||||
subtitleFallback: "Status, müşderi",
|
||||
icon: User,
|
||||
validate: (f, m) => validateStep(0, f, m),
|
||||
},
|
||||
{
|
||||
id: "location",
|
||||
titleKey: "intlPaymentForm.steps.location.title",
|
||||
titleFallback: "Lokasiýa",
|
||||
subtitleKey: "intlPaymentForm.steps.location.subtitle",
|
||||
subtitleFallback: "Welaýat, şahamça",
|
||||
icon: MapPin,
|
||||
validate: (f, m) => validateStep(1, f, m),
|
||||
},
|
||||
{
|
||||
id: "personal",
|
||||
titleKey: "intlPaymentForm.steps.personal.title",
|
||||
titleFallback: "Şahsy",
|
||||
subtitleKey: "intlPaymentForm.steps.personal.subtitle",
|
||||
subtitleFallback: "Pasport, kontakt",
|
||||
icon: IdCard,
|
||||
validate: (f, m) => validateStep(2, f, m),
|
||||
},
|
||||
{
|
||||
id: "payment",
|
||||
titleKey: "intlPaymentForm.steps.payment.title",
|
||||
titleFallback: "Töleg",
|
||||
subtitleKey: "intlPaymentForm.steps.payment.subtitle",
|
||||
subtitleFallback: "Töleýji, kabul ediji",
|
||||
icon: CreditCard,
|
||||
validate: (f, m) => validateStep(3, f, m),
|
||||
},
|
||||
{
|
||||
id: "docs",
|
||||
titleKey: "intlPaymentForm.steps.docs.title",
|
||||
titleFallback: "Resminamalar",
|
||||
subtitleKey: "intlPaymentForm.steps.docs.subtitle",
|
||||
subtitleFallback: "15 resminama",
|
||||
icon: Files,
|
||||
validate: () => ({}),
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof IntlPaymentFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof IntlPaymentFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Step content components ──────────────────────────────────────────────────
|
||||
|
||||
interface StepContentProps {
|
||||
form: IntlPaymentFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof IntlPaymentFormData>(k: K, v: IntlPaymentFormData[K]) => void
|
||||
t: TFunction
|
||||
form: IntlPaymentFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof IntlPaymentFormData>(k: K, v: IntlPaymentFormData[K]) => void;
|
||||
t: TFunction;
|
||||
}
|
||||
|
||||
function StepGeneral({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('intlPaymentForm.titles.general.client') || 'Müşderi'}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('User') || 'Ulanyjy'}
|
||||
label={t("User") || "Ulanyjy"}
|
||||
value={form.client_id}
|
||||
onChange={(v) => set('client_id', v)}
|
||||
onChange={(v) => set("client_id", v)}
|
||||
options={[]}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.client_id}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('loanOrderForm.labels.status') || 'Status'}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('loanOrderForm.labels.status') || 'Status'}
|
||||
label={t("loanOrderForm.labels.status") || "Status"}
|
||||
value={form.status}
|
||||
onChange={(v) => set('status', v)}
|
||||
onChange={(v) => set("status", v)}
|
||||
options={STATUS_OPTIONS}
|
||||
error={errors.status}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('Card type') || 'Kart görnüşi'} span="full">
|
||||
<BentoCard span="full">
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('Application type') || 'Ýüztumanyň görnüşi'}
|
||||
label={t("Application type") || "Ýüztumanyň görnüşi"}
|
||||
value={form.currency_type}
|
||||
onChange={(v) => set('currency_type', v)}
|
||||
onChange={(v) => set("currency_type", v)}
|
||||
options={CURRENCY_OPTIONS}
|
||||
error={errors.currency_type}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('Note') || 'Bellik'} span="full">
|
||||
<BentoCard span="full">
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t('Note') || 'Bellik'}
|
||||
label={t("Note") || "Bellik"}
|
||||
value={form.note}
|
||||
onChange={(v) => set('note', v)}
|
||||
placeholder={t('loanOrderForm.placeholders.note') || 'Bellik...'}
|
||||
onChange={(v) => set("note", v)}
|
||||
placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."}
|
||||
rows={2}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepLocation({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('Region') || 'Welaýat'}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Region') || 'Welaýat'}
|
||||
label={t("Region") || "Welaýat"}
|
||||
value={form.province}
|
||||
onChange={(v) => { set('province', v); set('branch', '') }}
|
||||
onChange={(v) => {
|
||||
set("province", v);
|
||||
set("branch", "");
|
||||
}}
|
||||
options={PROVINCE_OPTIONS}
|
||||
error={errors.province}
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('intlPaymentForm.hints.selectRegion') || 'Welaýaty saýlasaňyz şahamçalar güncellenar.'}
|
||||
</p>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('Branch') || 'Şahamça'}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Branch') || 'Şahamça'}
|
||||
label={t("Branch") || "Şahamça"}
|
||||
value={form.branch}
|
||||
onChange={(v) => set('branch', v)}
|
||||
onChange={(v) => set("branch", v)}
|
||||
options={[]}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.branch}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('intlPaymentForm.titles.personal.name') || 'At-familýa'}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Passport surname') || 'Pasportdaky familiýa'}
|
||||
label={t("Passport surname") || "Pasportdaky familiýa"}
|
||||
value={form.passport_last_name}
|
||||
onChange={(v) => set('passport_last_name', v)}
|
||||
onChange={(v) => set("passport_last_name", v)}
|
||||
placeholder="NURYYEW"
|
||||
error={errors.passport_last_name}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Passport name') || 'Pasportdaky ady'}
|
||||
label={t("Passport name") || "Pasportdaky ady"}
|
||||
value={form.passport_first_name}
|
||||
onChange={(v) => set('passport_first_name', v)}
|
||||
onChange={(v) => set("passport_first_name", v)}
|
||||
placeholder="HAÝDAR"
|
||||
error={errors.passport_first_name}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('Contact data') || 'Kontakt'}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone"
|
||||
label={t('Phone') || 'Telefon'}
|
||||
label={t("Phone") || "Telefon"}
|
||||
value={form.phone}
|
||||
onChange={(v) => set('phone', v)}
|
||||
onChange={(v) => set("phone", v)}
|
||||
error={errors.phone}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="email"
|
||||
label={t('Email') || 'E-poçta'}
|
||||
label={t("Email") || "E-poçta"}
|
||||
value={form.email}
|
||||
onChange={(v) => set('email', v)}
|
||||
onChange={(v) => set("email", v)}
|
||||
placeholder="email@example.com"
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('Current Residence') || 'Häzirki ýaşaýyş ýeri'} span="full">
|
||||
<BentoCard span="full">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Current Residence') || 'Häzirki ýaşaýyş ýeri'}
|
||||
label={t("Current Residence") || "Häzirki ýaşaýyş ýeri"}
|
||||
value={form.home_address}
|
||||
onChange={(v) => set('home_address', v)}
|
||||
placeholder={t('intlPaymentForm.placeholders.address') || 'Köçe, jaý belgisi...'}
|
||||
onChange={(v) => set("home_address", v)}
|
||||
placeholder={t("intlPaymentForm.placeholders.address") || "Köçe, jaý belgisi..."}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepPayment({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('Passport') || 'Pasport maglumatlary'}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('Passport serie') || 'Pasport seriýasy'}
|
||||
label={t("Passport serie") || "Pasport seriýasy"}
|
||||
value={form.passport_series}
|
||||
onChange={(v) => set('passport_series', v)}
|
||||
onChange={(v) => set("passport_series", v)}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
error={errors.passport_series}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Passport id') || 'Pasport belgisi'}
|
||||
label={t("Passport id") || "Pasport belgisi"}
|
||||
value={form.passport_number}
|
||||
onChange={(v) => set('passport_number', v)}
|
||||
onChange={(v) => set("passport_number", v)}
|
||||
placeholder="A123456"
|
||||
error={errors.passport_number}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('intlPaymentForm.titles.payment.payer') || 'Töleýji'}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('intlPaymentForm.labels.payerFullName') || 'Ady Familiýasy Atasynyň ady'}
|
||||
label={t("intlPaymentForm.labels.payerFullName") || "Ady Familiýasy Atasynyň ady"}
|
||||
value={form.payer_full_name}
|
||||
onChange={(v) => set('payer_full_name', v)}
|
||||
placeholder={t('intlPaymentForm.placeholders.payerFullName') || 'Doly ady...'}
|
||||
onChange={(v) => set("payer_full_name", v)}
|
||||
placeholder={t("intlPaymentForm.placeholders.payerFullName") || "Doly ady..."}
|
||||
error={errors.payer_full_name}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('intlPaymentForm.labels.payerAccount') || 'Goşun hasaby'}
|
||||
label={t("intlPaymentForm.labels.payerAccount") || "Goşun hasaby"}
|
||||
value={form.payer_account_number}
|
||||
onChange={(v) => set('payer_account_number', v)}
|
||||
placeholder={t('intlPaymentForm.placeholders.payerAccount') || '1234 5678 ...'}
|
||||
onChange={(v) => set("payer_account_number", v)}
|
||||
placeholder={t("intlPaymentForm.placeholders.payerAccount") || "1234 5678 ..."}
|
||||
error={errors.payer_account_number}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('Payee information') || 'Kabul edijiniň maglumatlary'} span="full">
|
||||
<BentoCard span="full">
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t('intlPaymentForm.labels.receiverInfo') || 'Töleg kabul edijiniň maglumatlary'}
|
||||
label={t("intlPaymentForm.labels.receiverInfo") || "Töleg kabul edijiniň maglumatlary"}
|
||||
value={form.receiver_info}
|
||||
onChange={(v) => set('receiver_info', v)}
|
||||
placeholder={t('intlPaymentForm.placeholders.receiverInfo') || 'Kabul ediji bank, hasap, Swift...'}
|
||||
onChange={(v) => set("receiver_info", v)}
|
||||
placeholder={t("intlPaymentForm.placeholders.receiverInfo") || "Kabul ediji bank, hasap, Swift..."}
|
||||
rows={3}
|
||||
error={errors.receiver_info}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepDocs({ form, set, t }: StepContentProps) {
|
||||
function StepDocs({ form, set }: StepContentProps) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('intlPaymentForm.titles.docs.kabul') || 'Kabul ediji talyp — 9 resminama'}>
|
||||
<BentoCard>
|
||||
<div className="space-y-3">
|
||||
{KABUL_DOCS.map(({ key, label }) => (
|
||||
<FormInput
|
||||
@@ -340,7 +378,7 @@ function StepDocs({ form, set, t }: StepContentProps) {
|
||||
</div>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('intlPaymentForm.titles.docs.upgrad') || 'Upgradyý — 6 resminama'}>
|
||||
<BentoCard>
|
||||
<div className="space-y-3">
|
||||
{UPGRAD_DOCS.map(({ key, label }) => (
|
||||
<FormInput
|
||||
@@ -355,181 +393,186 @@ function StepDocs({ form, set, t }: StepContentProps) {
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Initial data mapper ──────────────────────────────────────────────────────
|
||||
|
||||
function mapInitial(data: IntlPaymentItem): Partial<IntlPaymentFormData> {
|
||||
return {
|
||||
client_id: data.client_id,
|
||||
status: data.status,
|
||||
note: data.note ?? '',
|
||||
currency_type: data.currency_type,
|
||||
province: data.province,
|
||||
branch: data.branch,
|
||||
passport_first_name: data.passport_first_name,
|
||||
passport_last_name: data.passport_last_name,
|
||||
phone: data.phone,
|
||||
email: data.email ?? '',
|
||||
home_address: data.home_address ?? '',
|
||||
passport_series: data.passport_series,
|
||||
passport_number: data.passport_number,
|
||||
payer_full_name: data.payer_full_name,
|
||||
client_id: data.client_id,
|
||||
status: data.status,
|
||||
note: data.note ?? "",
|
||||
currency_type: data.currency_type,
|
||||
province: data.province,
|
||||
branch: data.branch,
|
||||
passport_first_name: data.passport_first_name,
|
||||
passport_last_name: data.passport_last_name,
|
||||
phone: data.phone,
|
||||
email: data.email ?? "",
|
||||
home_address: data.home_address ?? "",
|
||||
passport_series: data.passport_series,
|
||||
passport_number: data.passport_number,
|
||||
payer_full_name: data.payer_full_name,
|
||||
payer_account_number: data.payer_account_number,
|
||||
receiver_info: data.receiver_info,
|
||||
}
|
||||
receiver_info: data.receiver_info,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function IntlPaymentForm({ mode, initialData }: IntlPaymentFormProps) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const createMutation = useCreateIntlPayment()
|
||||
const updateMutation = useUpdateIntlPayment(initialData?.id ?? '')
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const createMutation = useCreateIntlPayment();
|
||||
const updateMutation = useUpdateIntlPayment(initialData?.id ?? "");
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, setError,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<IntlPaymentFormData>({
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
});
|
||||
|
||||
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 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>()
|
||||
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])
|
||||
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 IntlPaymentFormData>(key: K, value: IntlPaymentFormData[K]) => {
|
||||
(setValue as (name: K, val: IntlPaymentFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
const set = useCallback(
|
||||
<K extends keyof IntlPaymentFormData>(key: K, value: IntlPaymentFormData[K]) => {
|
||||
(setValue as (name: K, val: IntlPaymentFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const allSubmittedErrors = useMemo(() => {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const stepIdx of submittedSteps) {
|
||||
Object.assign(result, STEPS[stepIdx].validate(form, mode))
|
||||
Object.assign(result, STEPS[stepIdx].validate(form, mode));
|
||||
}
|
||||
return result
|
||||
}, [form, mode, submittedSteps, i18n.language])
|
||||
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 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])
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t]);
|
||||
|
||||
// ── Navigation ──────────────────────────────────────────────────────────────
|
||||
|
||||
const markVisited = (i: number) =>
|
||||
setVisited((prev) => new Set([...prev, i]))
|
||||
const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i]));
|
||||
|
||||
const markSubmitted = (i: number) =>
|
||||
setSubmittedSteps((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)
|
||||
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 IntlPaymentFormData, { type: 'manual', message: msg })
|
||||
})
|
||||
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||
return
|
||||
setError(key as keyof IntlPaymentFormData, { 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' })
|
||||
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' })
|
||||
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' })
|
||||
}
|
||||
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)))
|
||||
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))
|
||||
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 IntlPaymentFormData, { type: 'manual', message: msg })
|
||||
})
|
||||
toast.error(t('common.errors.requiredFieldsMissing', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
||||
setError(key as keyof IntlPaymentFormData, { 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
|
||||
setCurrentStep(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === 'create') {
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload as IntlPaymentCreatePayload, {
|
||||
onSuccess: (data) => navigate(`/intl-payments/visa-master/${data.id}`),
|
||||
})
|
||||
});
|
||||
} else if (initialData) {
|
||||
updateMutation.mutate(payload as IntlPaymentCreatePayload, {
|
||||
onSuccess: () => navigate(`/intl-payments/visa-master/${initialData.id}`),
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── StepBar items ──────────────────────────────────────────────────────────
|
||||
|
||||
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
|
||||
const isActive = i === currentStep
|
||||
const hasErrors = stepsWithErrors.has(i)
|
||||
const isDone = visited.has(i) && !hasErrors
|
||||
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,
|
||||
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',
|
||||
}
|
||||
})
|
||||
icon: s.icon,
|
||||
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||
};
|
||||
});
|
||||
|
||||
const isLastStep = currentStep === STEPS.length - 1
|
||||
const isLastStep = currentStep === STEPS.length - 1;
|
||||
|
||||
// ── Render ──────────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="mx-auto space-y-6">
|
||||
<h1 className="text-2xl font-bold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('intlPayment.createTitle', 'Visa/Master tölegler (talyplar üçin) dörediň')
|
||||
: t('intlPayment.editTitle', 'Visa/Master tölegler (talyplar üçin) redaktirläň')}
|
||||
{mode === "create"
|
||||
? t("intlPayment.createTitle", "Visa/Master tölegler (talyplar üçin) dörediň")
|
||||
: t("intlPayment.editTitle", "Visa/Master tölegler (talyplar üçin) redaktirläň")}
|
||||
</h1>
|
||||
|
||||
{/* Step bar */}
|
||||
@@ -538,26 +581,22 @@ export function IntlPaymentForm({ mode, initialData }: IntlPaymentFormProps) {
|
||||
</div>
|
||||
|
||||
{/* Step content */}
|
||||
{STEPS[currentStep].id === 'general' && <StepGeneral {...stepProps} />}
|
||||
{STEPS[currentStep].id === 'location' && <StepLocation {...stepProps} />}
|
||||
{STEPS[currentStep].id === 'personal' && <StepPersonal {...stepProps} />}
|
||||
{STEPS[currentStep].id === 'payment' && <StepPayment {...stepProps} />}
|
||||
{STEPS[currentStep].id === 'docs' && <StepDocs {...stepProps} />}
|
||||
{STEPS[currentStep].id === "general" && <StepGeneral {...stepProps} />}
|
||||
{STEPS[currentStep].id === "location" && <StepLocation {...stepProps} />}
|
||||
{STEPS[currentStep].id === "personal" && <StepPersonal {...stepProps} />}
|
||||
{STEPS[currentStep].id === "payment" && <StepPayment {...stepProps} />}
|
||||
{STEPS[currentStep].id === "docs" && <StepDocs {...stepProps} />}
|
||||
|
||||
{/* Actions */}
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onCancel={() => navigate('/intl-payments/visa-master')}
|
||||
onCancel={() => navigate("/intl-payments/visa-master")}
|
||||
onPrev={currentStep > 0 ? handleBack : undefined}
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? doSubmit : undefined}
|
||||
submitLabel={
|
||||
mode === 'create'
|
||||
? t('intlPayment.createBtn', 'Dörediň')
|
||||
: t('intlPayment.editBtn', 'Redaktirläň')
|
||||
}
|
||||
submitLabel={mode === "create" ? t("intlPayment.createBtn", "Dörediň") : t("intlPayment.editBtn", "Redaktirläň")}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user