started connect with api
This commit is contained in:
1 parent
0ca218505d
commit
6da59f42d9
112 files changed
+7091
-6989
No files matched your search
@@ -1,124 +1,103 @@
|
||||
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 { CreditCard, User, FileText } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
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 { CreditCard, User, FileText } 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 { CardPinItem, CardPinCreatePayload } from '@/features/cardPins/api/cardPinApi'
|
||||
import { useCreateCardPin, useUpdateCardPin } from '@/features/cardPins/hooks/useCardPins'
|
||||
import { validateStep, DEFAULT_FORM_VALUES } from '@/features/cardPins/schemas/cardPin.schema'
|
||||
import type { CardPinFormData } from '@/features/cardPins/schemas/cardPin.schema'
|
||||
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 { CardPinOrder, CreateCardPinPayload } from "@/features/cardPins/api/cardPinApi";
|
||||
import { useCreateCardPin, useUpdateCardPin } from "@/features/cardPins/hooks/useCardPins";
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "@/features/cardPins/schemas/cardPin.schema";
|
||||
import type { CardPinFormData } from "@/features/cardPins/schemas/cardPin.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface CardPinFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardPinItem
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardPinOrder;
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const CARD_TYPE_OPTIONS = [
|
||||
{ value: 'altyn_asyr', label: 'Altyn Asyr' },
|
||||
{ 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' },
|
||||
]
|
||||
|
||||
const PROVINCE_OPTIONS = [
|
||||
{ value: 'ashgabat', label: 'Aşgabat' },
|
||||
{ value: 'mary', label: 'Mary' },
|
||||
{ value: 'dasoguz', label: 'Daşoguz' },
|
||||
{ value: 'lebap', label: 'Lebap' },
|
||||
{ value: 'balkan', label: 'Balkan' },
|
||||
{ value: 'ahal', label: 'Ahal' },
|
||||
]
|
||||
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
|
||||
type FlatErrors = Partial<Record<keyof CardPinFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof CardPinFormData, string>>;
|
||||
|
||||
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 CardPinFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof CardPinFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
|
||||
interface StepDef {
|
||||
id: string
|
||||
titleKey: string
|
||||
titleFallback: string
|
||||
subtitleKey: string
|
||||
subtitleFallback: string
|
||||
icon: LucideIcon
|
||||
validate: (form: CardPinFormData, mode: 'create' | 'edit') => FlatErrors
|
||||
id: string;
|
||||
titleKey: string;
|
||||
titleFallback: string;
|
||||
subtitleKey: string;
|
||||
subtitleFallback: string;
|
||||
icon: LucideIcon;
|
||||
validate: (form: CardPinFormData) => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
{
|
||||
id: 'card',
|
||||
titleKey: 'cardPin.step.card',
|
||||
titleFallback: 'Kart',
|
||||
subtitleKey: 'cardPinForm.steps.card.subtitle',
|
||||
subtitleFallback: 'Görnüş & lokasiýa',
|
||||
id: "card",
|
||||
titleKey: "cardPin.step.card",
|
||||
titleFallback: "Kart",
|
||||
subtitleKey: "cardPinForm.steps.card.subtitle",
|
||||
subtitleFallback: "Görnüş & lokasiýa",
|
||||
icon: CreditCard,
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
validate: (form) => validateStep(0, form),
|
||||
},
|
||||
{
|
||||
id: 'personal',
|
||||
titleKey: 'cardPin.step.personal',
|
||||
titleFallback: 'Şahsy',
|
||||
subtitleKey: 'cardPinForm.steps.personal.subtitle',
|
||||
subtitleFallback: 'Maglumatlar',
|
||||
id: "personal",
|
||||
titleKey: "cardPin.step.personal",
|
||||
titleFallback: "Şahsy",
|
||||
subtitleKey: "cardPinForm.steps.personal.subtitle",
|
||||
subtitleFallback: "Maglumatlar",
|
||||
icon: User,
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
validate: (form) => validateStep(1, form),
|
||||
},
|
||||
{
|
||||
id: 'passport',
|
||||
titleKey: 'cardPin.step.passport',
|
||||
titleFallback: 'Pasport',
|
||||
subtitleKey: 'cardPinForm.steps.passport.subtitle',
|
||||
subtitleFallback: 'Resminamalar',
|
||||
id: "passport",
|
||||
titleKey: "cardPin.step.passport",
|
||||
titleFallback: "Pasport",
|
||||
subtitleKey: "cardPinForm.steps.passport.subtitle",
|
||||
subtitleFallback: "Resminamalar",
|
||||
icon: FileText,
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
validate: (form) => validateStep(2, form),
|
||||
},
|
||||
]
|
||||
];
|
||||
|
||||
// ─── Shared step content props ────────────────────────────────────────────────
|
||||
|
||||
interface StepContentProps {
|
||||
form: CardPinFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof CardPinFormData>(k: K, v: CardPinFormData[K]) => void
|
||||
t: TFunction
|
||||
form: CardPinFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof CardPinFormData>(k: K, v: CardPinFormData[K]) => void;
|
||||
t: TFunction;
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
|
||||
function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
const STATUS_OPTIONS = useMemo(() => [
|
||||
{ value: 'pending', label: t('cardPin.status.pending', 'Garaşylýar') },
|
||||
{ value: 'approved', label: t('cardPin.status.approved', 'Tassyklandy') },
|
||||
{ value: 'rejected', label: t('cardPin.status.rejected', 'Ret edildi') },
|
||||
], [t])
|
||||
const STATUS_OPTIONS = useMemo(
|
||||
() => [
|
||||
{ value: "pending", label: t("cardPin.status.pending", "Garaşylýar") },
|
||||
{ value: "approved", label: t("cardPin.status.approved", "Tassyklandy") },
|
||||
{ value: "rejected", label: t("cardPin.status.rejected", "Ýatyryldy") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -126,75 +105,86 @@ function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('loanOrderForm.labels.status') || 'Status'}
|
||||
label={t("cardPin.field.status", "Statusy")}
|
||||
required
|
||||
value={form.status}
|
||||
onChange={(v) => set('status', v)}
|
||||
onChange={(v) => set("status", v)}
|
||||
options={STATUS_OPTIONS}
|
||||
error={errors.status}
|
||||
placeholder={t('loanOrderForm.placeholders.select') || 'Saýlaň'}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Note') || 'Bellik'}
|
||||
value={form.note}
|
||||
onChange={(v) => set('note', v)}
|
||||
placeholder={t('loanOrderForm.placeholders.note') || 'Bellik...'}
|
||||
label={t("cardPin.field.uniqueId", "Sargyt belgisi")}
|
||||
required
|
||||
value={form.uniqueId}
|
||||
onChange={(v) => set("uniqueId", v)}
|
||||
placeholder={t("cardPin.field.uniqueId", "Sargyt belgisi")}
|
||||
error={errors.uniqueId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('loanOrderForm.titles.cardInfo') || 'Kart maglumatlary'}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Loan type') || 'Kart görnüşi'}
|
||||
required
|
||||
value={form.card_type}
|
||||
onChange={(v) => set('card_type', v)}
|
||||
options={CARD_TYPE_OPTIONS}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
error={errors.card_type}
|
||||
/>
|
||||
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Kart maglumatlary"}>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Card number') || 'Kart belgisi'}
|
||||
label={t("cardPin.field.cardNumber", "Kart belgisi")}
|
||||
required
|
||||
value={form.card_number}
|
||||
onChange={(v) => set('card_number', v)}
|
||||
placeholder={t('Card number') || 'Kart belgisi'}
|
||||
error={errors.card_number}
|
||||
value={form.cardNumber}
|
||||
onChange={(v) => set("cardNumber", v)}
|
||||
placeholder={t("cardPin.field.cardNumber", "Kart belgisi")}
|
||||
error={errors.cardNumber}
|
||||
/>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("cardPin.field.cardTypeId", "Kart görnüşi ID")}
|
||||
required
|
||||
value={form.cardTypeId}
|
||||
onChange={(v) => set("cardTypeId", v)}
|
||||
placeholder={t("cardPin.field.cardTypeId", "Kart görnüşi ID")}
|
||||
error={errors.cardTypeId}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('cardPinForm.titles.location') || 'Lokasiýa'}>
|
||||
<BentoCard title={t("cardPinForm.titles.location") || "Lokasiýa"}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Region') || 'Welaýat'}
|
||||
type="text"
|
||||
label={t("cardPin.field.region", "Sebit")}
|
||||
required
|
||||
value={form.province}
|
||||
onChange={(v) => { set('province', v); set('branch', '') }}
|
||||
options={PROVINCE_OPTIONS}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
error={errors.province}
|
||||
value={form.region}
|
||||
onChange={(v) => set("region", v)}
|
||||
placeholder={t("cardPin.field.region", "Sebit")}
|
||||
error={errors.region}
|
||||
/>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Branch') || 'Şahamça'}
|
||||
type="number"
|
||||
label={t("cardPin.field.branchId", "Şahamça ID")}
|
||||
required
|
||||
value={form.branch}
|
||||
onChange={(v) => set('branch', v)}
|
||||
options={[]}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
disabled={!form.province}
|
||||
error={errors.branch}
|
||||
value={form.branchId}
|
||||
onChange={(v) => set("branchId", v)}
|
||||
placeholder={t("cardPin.field.branchId", "Şahamça ID")}
|
||||
error={errors.branchId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t("cardPin.field.notes", "Bellikler")}
|
||||
value={form.notes}
|
||||
onChange={(v) => set("notes", v)}
|
||||
placeholder={t("cardPin.field.notes", "Bellikler")}
|
||||
error={errors.notes}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
@@ -203,313 +193,285 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text" label={t('Name') || 'Ady'} required
|
||||
value={form.first_name} onChange={(v) => set('first_name', v)}
|
||||
placeholder={t('Name') || 'Ady'} error={errors.first_name}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text" label={t('Surname') || 'Familiýasy'} required
|
||||
value={form.last_name} onChange={(v) => set('last_name', v)}
|
||||
placeholder={t('Surname') || 'Familiýasy'} error={errors.last_name}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text" label={t('Patronic name') || 'Atasynyň ady'}
|
||||
value={form.father_name} onChange={(v) => set('father_name', v)}
|
||||
placeholder={t('Patronic name') || 'Atasynyň ady'}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date" label={t('Date of birth') || 'Doglan güni'} required
|
||||
value={form.birth_date} onChange={(v) => set('birth_date', v)}
|
||||
error={errors.birth_date}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone" label={t('Phone') || 'Telefon'} required
|
||||
value={form.phone} onChange={(v) => set('phone', v)}
|
||||
error={errors.phone}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function StepPassport({ form, errors, set, t, mode, initialData }: StepContentProps & {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardPinItem
|
||||
}) {
|
||||
const existingFiles =
|
||||
mode === 'edit' && initialData
|
||||
? [
|
||||
{ url: initialData.passport_file_1, label: t('Passport (page 1)') || 'Pasport (sahypa 1)' },
|
||||
{ url: initialData.passport_file_2, label: t('Passport (page 2-3)') || 'Pasport (2-3-nji sahypa)' },
|
||||
{ url: initialData.passport_file_3, label: t('Passport (page 8-9)') || 'Pasport (8-9 sahypa)' },
|
||||
{ url: initialData.passport_file_4, label: t('Passport (page 32)') || 'Pasport (32-nji sahypa)' },
|
||||
].filter((f): f is { url: string; label: string } => !!f.url)
|
||||
: []
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Passport serie') || 'Pasport seriýasy'}
|
||||
type="text"
|
||||
label={t("cardPin.field.customerName", "Ady")}
|
||||
required
|
||||
value={form.passport_series}
|
||||
onChange={(v) => set('passport_series', v)}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
error={errors.passport_series}
|
||||
value={form.customerName}
|
||||
onChange={(v) => set("customerName", v)}
|
||||
placeholder={t("cardPin.field.customerName", "Ady")}
|
||||
error={errors.customerName}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Passport id') || 'Pasport belgisi'}
|
||||
label={t("cardPin.field.customerSurname", "Familiýasy")}
|
||||
required
|
||||
value={form.passport_number}
|
||||
onChange={(v) => set('passport_number', v)}
|
||||
placeholder={t('Passport id') || 'Pasport belgisi'}
|
||||
error={errors.passport_number}
|
||||
value={form.customerSurname}
|
||||
onChange={(v) => set("customerSurname", v)}
|
||||
placeholder={t("cardPin.field.customerSurname", "Familiýasy")}
|
||||
error={errors.customerSurname}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.customerPatronicName", "Atasynyň ady")}
|
||||
value={form.customerPatronicName}
|
||||
onChange={(v) => set("customerPatronicName", v)}
|
||||
placeholder={t("cardPin.field.customerPatronicName", "Atasynyň ady")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{existingFiles.length > 0 && (
|
||||
<BentoGrid cols={4}>
|
||||
{existingFiles.map(({ url, label }) => (
|
||||
<BentoCard key={label} title={label}>
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-primary underline truncate block"
|
||||
>
|
||||
{t('loanOrderForm.fileLabels.viewFile') || 'Faýly gör'}
|
||||
</a>
|
||||
</BentoCard>
|
||||
))}
|
||||
</BentoGrid>
|
||||
)}
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={mode === 'edit' ? (t('loanOrderForm.fileLabels.replacePage1') || 'Pasport (sahypa 1) (çalyşmak)') : (t('Passport (page 1)') || 'Pasport (sahypa 1)')}
|
||||
required={mode === 'create'}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_file_1}
|
||||
onFileChange={(f) => set('passport_file_1', f)}
|
||||
error={errors.passport_file_1}
|
||||
type="date"
|
||||
label={t("cardPin.field.bornAt", "Doglan güni")}
|
||||
value={form.bornAt}
|
||||
onChange={(v) => set("bornAt", v)}
|
||||
error={errors.bornAt}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={mode === 'edit' ? (t('loanOrderForm.fileLabels.replacePage23') || 'Pasport (2-3-nji sahypa) (çalyşmak)') : (t('Passport (page 2-3)') || 'Pasport (2-3-nji sahypa)')}
|
||||
required={mode === 'create'}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_file_2}
|
||||
onFileChange={(f) => set('passport_file_2', f)}
|
||||
error={errors.passport_file_2}
|
||||
type="text"
|
||||
label={t("cardPin.field.phone", "Telefon")}
|
||||
required
|
||||
value={form.phone}
|
||||
onChange={(v) => set("phone", v)}
|
||||
placeholder={t("cardPin.field.phone", "Telefon")}
|
||||
error={errors.phone}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={t('Passport (page 8-9)') || 'Pasport (8-9 sahypa)'}
|
||||
required={mode === 'create'}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_file_3}
|
||||
onFileChange={(f) => set('passport_file_3', f)}
|
||||
error={errors.passport_file_3}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={t('Passport (page 32)') || 'Pasport (32-nji sahypa)'}
|
||||
required={mode === 'create'}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_file_4}
|
||||
onFileChange={(f) => set('passport_file_4', f)}
|
||||
error={errors.passport_file_4}
|
||||
type="number"
|
||||
label={t("cardPin.field.userId", "Ulanyjy ID")}
|
||||
required
|
||||
value={form.userId}
|
||||
onChange={(v) => set("userId", v)}
|
||||
placeholder={t("cardPin.field.userId", "Ulanyjy ID")}
|
||||
error={errors.userId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportSerie", "Pasport seriýasy")}
|
||||
required
|
||||
value={form.passportSerie}
|
||||
onChange={(v) => set("passportSerie", v)}
|
||||
placeholder={t("cardPin.field.passportSerie", "Pasport seriýasy")}
|
||||
error={errors.passportSerie}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||
required
|
||||
value={form.passportId}
|
||||
onChange={(v) => set("passportId", v)}
|
||||
placeholder={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||
error={errors.passportId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={4}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportOne", "Pasport 1")}
|
||||
value={form.passportOne}
|
||||
onChange={(v) => set("passportOne", v)}
|
||||
placeholder={t("cardPin.field.passportOne", "Pasport 1")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportTwo", "Pasport 2")}
|
||||
value={form.passportTwo}
|
||||
onChange={(v) => set("passportTwo", v)}
|
||||
placeholder={t("cardPin.field.passportTwo", "Pasport 2")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportThree", "Pasport 3")}
|
||||
value={form.passportThree}
|
||||
onChange={(v) => set("passportThree", v)}
|
||||
placeholder={t("cardPin.field.passportThree", "Pasport 3")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportFour", "Pasport 4")}
|
||||
value={form.passportFour}
|
||||
onChange={(v) => set("passportFour", v)}
|
||||
placeholder={t("cardPin.field.passportFour", "Pasport 4")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const createMutation = useCreateCardPin()
|
||||
const updateMutation = useUpdateCardPin(initialData?.id ?? '')
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const createMutation = useCreateCardPin();
|
||||
const updateMutation = useUpdateCardPin(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, setError,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<CardPinFormData>({
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
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());
|
||||
|
||||
// ── Computed step errors ───────────────────────────────────────────────────
|
||||
|
||||
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)).length > 0) out.add(i);
|
||||
});
|
||||
return out;
|
||||
}, [form, mode, visited, i18n.language]);
|
||||
|
||||
// ── set helper ─────────────────────────────────────────────────────────────
|
||||
|
||||
const set = useCallback(<K extends keyof CardPinFormData>(key: K, value: CardPinFormData[K]) => {
|
||||
(setValue as (name: K, val: CardPinFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
const set = useCallback(
|
||||
<K extends keyof CardPinFormData>(key: K, value: CardPinFormData[K]) => {
|
||||
(setValue as (name: K, val: CardPinFormData[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));
|
||||
}
|
||||
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);
|
||||
if (Object.keys(errs).length > 0) {
|
||||
Object.entries(errs).forEach(([key, msg]) => {
|
||||
setError(key as keyof CardPinFormData, { type: 'manual', message: msg })
|
||||
})
|
||||
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||
return
|
||||
setError(key as keyof CardPinFormData, { type: "manual", message: msg });
|
||||
});
|
||||
toast.error(t("common.errors.fillRequiredCorrectly", "Dogry maglumat girizmegiňizi haýyş edýäris."));
|
||||
return;
|
||||
}
|
||||
setCurrentStep(currentStep + 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
setCurrentStep(currentStep + 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
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 handleSubmit = () => {
|
||||
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 values = getValues()
|
||||
const allErrors: FlatErrors = {}
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(values, mode))
|
||||
const values = getValues();
|
||||
const allErrors: FlatErrors = {};
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(values));
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
Object.entries(allErrors).forEach(([key, msg]) => {
|
||||
setError(key as keyof CardPinFormData, { type: 'manual', message: msg })
|
||||
})
|
||||
toast.error(t('common.errors.requiredFieldsMissing', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
||||
setError(key as keyof CardPinFormData, { 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(values, mode)).length > 0) {
|
||||
setCurrentStep(i)
|
||||
break
|
||||
if (Object.keys(STEPS[i].validate(values)).length > 0) {
|
||||
setCurrentStep(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: CardPinCreatePayload = {
|
||||
status: values.status as CardPinCreatePayload['status'],
|
||||
note: values.note ?? '',
|
||||
card_type: values.card_type,
|
||||
card_number: values.card_number,
|
||||
province: values.province,
|
||||
branch: values.branch,
|
||||
first_name: values.first_name,
|
||||
last_name: values.last_name,
|
||||
father_name: values.father_name ?? '',
|
||||
birth_date: values.birth_date,
|
||||
phone: values.phone,
|
||||
passport_series: values.passport_series,
|
||||
passport_number: values.passport_number,
|
||||
passport_file_1: values.passport_file_1,
|
||||
passport_file_2: values.passport_file_2,
|
||||
passport_file_3: values.passport_file_3,
|
||||
passport_file_4: values.passport_file_4,
|
||||
}
|
||||
const payload: CreateCardPinPayload = buildPayload(values);
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, { onSuccess: (data) => navigate(`/card-pins/${data.id}`) })
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, { onSuccess: (data) => navigate(`/card-pins/${data.id}`) });
|
||||
} else {
|
||||
updateMutation.mutate(payload, { onSuccess: () => navigate('/card-pins') })
|
||||
updateMutation.mutate(payload, { onSuccess: () => navigate("/card-pins") });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── 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 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -518,13 +480,9 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
{/* Page header */}
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('cardPin.createTitle', 'Kart pin bukja dörediň')
|
||||
: t('cardPin.editTitle', 'Kart pin bukja redaktirläň')}
|
||||
{mode === "create" ? t("cardPin.createTitle", "Kart pin bukja dörediň") : t("cardPin.editTitle", "Kart pin bukja redaktirläň")}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{t('common.form.subtitle', 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">{t("common.form.subtitle", "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.")}</p>
|
||||
</div>
|
||||
|
||||
{/* Step bar */}
|
||||
@@ -533,46 +491,48 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
</div>
|
||||
|
||||
{/* Step content */}
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
||||
{currentStep === 2 && (
|
||||
<StepPassport {...stepProps} mode={mode} initialData={initialData} />
|
||||
)}
|
||||
{currentStep === 2 && <StepPassport {...stepProps} />}
|
||||
|
||||
{/* Actions */}
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onCancel={currentStep === 0 ? () => navigate('/card-pins') : undefined}
|
||||
onCancel={currentStep === 0 ? () => navigate("/card-pins") : undefined}
|
||||
onPrev={currentStep > 0 ? handleBack : undefined}
|
||||
prevLabel={t('common.prev', 'Yza')}
|
||||
prevLabel={t("common.prev", "Yza")}
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
nextLabel={t('common.next', 'Indiki')}
|
||||
nextLabel={t("common.next", "Indiki")}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? handleSubmit : undefined}
|
||||
submitLabel={
|
||||
mode === 'create'
|
||||
? t('cardPin.createBtn', 'Kart pin bukja dörediň')
|
||||
: t('cardPin.editBtn', 'Kart pin bukja redaktirläň')
|
||||
mode === "create" ? t("cardPin.createBtn", "Kart pin bukja dörediň") : t("cardPin.editBtn", "Kart pin bukja redaktirläň")
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function mapInitial(data: CardPinItem): Partial<CardPinFormData> {
|
||||
function mapInitial(data: CardPinOrder): Partial<CardPinFormData> {
|
||||
return {
|
||||
status: data.status ?? 'pending',
|
||||
note: data.note ?? '',
|
||||
card_type: data.card_type ?? '',
|
||||
card_number: data.card_number ?? '',
|
||||
province: data.province ?? '',
|
||||
branch: data.branch ?? '',
|
||||
first_name: data.first_name ?? '',
|
||||
last_name: data.last_name ?? '',
|
||||
father_name: data.father_name ?? '',
|
||||
birth_date: data.birth_date ?? '',
|
||||
phone: data.phone ?? '',
|
||||
passport_series: data.passport_series ?? '',
|
||||
passport_number: data.passport_number ?? '',
|
||||
}
|
||||
uniqueId: data.uniqueId ?? "",
|
||||
status: data.status ?? "",
|
||||
cardNumber: data.cardNumber ?? "",
|
||||
cardTypeId: String(data.cardTypeId ?? ""),
|
||||
region: data.region ?? "",
|
||||
branchId: String(data.branchId ?? ""),
|
||||
customerName: data.customerName ?? "",
|
||||
customerSurname: data.customerSurname ?? "",
|
||||
customerPatronicName: data.customerPatronicName ?? "",
|
||||
bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "",
|
||||
phone: data.phone ?? "",
|
||||
passportSerie: data.passportSerie ?? "",
|
||||
passportId: data.passportId ?? "",
|
||||
passportOne: data.passportOne ?? "",
|
||||
passportTwo: data.passportTwo ?? "",
|
||||
passportThree: data.passportThree ?? "",
|
||||
passportFour: data.passportFour ?? "",
|
||||
userId: String(data.userId ?? ""),
|
||||
notes: data.notes ?? "",
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user