From ad9a93b61e16c97168c34c854c16738eecaaecfe Mon Sep 17 00:00:00 2001 From: Jelaletdin12 Date: Thu, 14 May 2026 11:28:04 +0500 Subject: [PATCH] started refactor and bento grid layout --- scratch/rewrite.cjs | 79 + src/components/formActions.tsx | 76 + src/components/stepBar.tsx | 1 - src/components/ui/sidebar.tsx | 1 - src/components/ui/tooltip.tsx | 1 - .../allUsers/components/allUsersForm.tsx | 32 +- .../components/cardBalanceForm.tsx | 27 +- .../cardPins/components/cardPinForm.tsx | 644 +++-- .../cardReasons/components/reasonForm.tsx | 35 +- .../components/cardRequisiteForm.tsx | 677 +++-- .../components/cardTransactionForm.tsx | 27 +- .../cardTypes/components/cardTypesForm.tsx | 35 +- .../clients/components/clientForm.tsx | 35 +- .../components/currencyRatesForm.tsx | 35 +- .../districts/components/districtsForm.tsx | 34 +- .../components/loanOrderMobileForm.tsx | 2302 +++++++++-------- .../loanOrders/components/loanOrderForm.tsx | 855 +++--- .../components/LoanRemainingForm.tsx | 31 +- .../loanTypes/components/loanTypesForm.tsx | 34 +- .../operators/components/operatorForms.tsx | 35 +- .../components/orderNewCardForm.tsx | 1016 +++++--- .../components/permissionsForm.tsx | 33 +- .../components/requiredDocumentsForm.tsx | 29 +- src/features/roles/components/roleForm.tsx | 34 +- .../components/sberPaymentsForm.tsx | 977 ++++--- .../sberPayments/hooks/useSberPayments.ts | 1 - .../components/intlPaymentForm.tsx | 752 ++++-- .../components/visaMasterSberSettingsForm.tsx | 35 +- .../sberPaymentsCreate/index.tsx | 1 - 29 files changed, 4565 insertions(+), 3309 deletions(-) create mode 100644 scratch/rewrite.cjs create mode 100644 src/components/formActions.tsx diff --git a/scratch/rewrite.cjs b/scratch/rewrite.cjs new file mode 100644 index 0000000..f2bb8ef --- /dev/null +++ b/scratch/rewrite.cjs @@ -0,0 +1,79 @@ +const fs = require('fs'); + +const content = fs.readFileSync('src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx', 'utf8'); + +let newContent = content.replace( + /{[\s\S]*?\/\* ── Status ──[\s\S]*?}/, + `
+

+ {mode === 'create' + ? (t('Loan order create') || 'Karz sargyt döredüň') + : (t('Loan order edit') || 'Karz sargydy üýtget')} +

+
+ +
+ +
+ +
+ {/* ── Status ──` +); + +newContent = newContent.replace( + /{\/\* ── Personal Data ──/, + `
+
+ {/* ── Personal Data ──` +); + +newContent = newContent.replace( + /{\/\* ── Job ──/, + `
+
+ {/* ── Job ──` +); + +newContent = newContent.replace( + /{\/\* ── Card ──/, + `
+
+ {/* ── Card ──` +); + +newContent = newContent.replace( + /{\/\* ── Passport ──/, + `
+
+ {/* ── Passport ──` +); + +newContent = newContent.replace( + /{\/\* ── Zamun ──/, + `
+
+ {/* ── Zamun ──` +); + +newContent = newContent.replace( + / \n <\/div>/, + `
+ + 0 ? handlePrev : undefined} + onCancel={() => navigate(-1)} + cancelLabel={t('Cancel') || 'Ýatyr'} + loadingLabel={t('Loading') || 'Ýüklenilýär...'} + submitLabel={mode === 'create' + ? (t('loanOrderMobiles.createButton') || 'Karz sargyt döredüň') + : (t('loanOrders.saveButton') || 'Ýatda sakla')} + showSubmit={currentStep === stepItems.length - 1} + /> + ` +); + +fs.writeFileSync('src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx', newContent); +console.log('Done rewriting JSX!'); diff --git a/src/components/formActions.tsx b/src/components/formActions.tsx new file mode 100644 index 0000000..0bd9158 --- /dev/null +++ b/src/components/formActions.tsx @@ -0,0 +1,76 @@ +import type { ReactNode } from 'react' +import { useTranslation } from 'react-i18next' +import { Loader2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { cn } from '@/lib/utils' + +interface FormActionsProps { + isPending?: boolean + onSubmit?: () => void + onCancel?: () => void + submitLabel?: ReactNode + cancelLabel?: ReactNode + loadingLabel?: ReactNode + cancelVariant?: 'outline' | 'ghost' + className?: string + onNext?: () => void + onPrev?: () => void + nextLabel?: ReactNode + prevLabel?: ReactNode + showSubmit?: boolean +} + +export function FormActions({ + isPending = false, + onSubmit, + onCancel, + submitLabel, + cancelLabel, + loadingLabel, + cancelVariant = 'outline', + className, + onNext, + onPrev, + nextLabel, + prevLabel, + showSubmit = true, +}: FormActionsProps) { + const { t } = useTranslation() + + const cancelText = cancelLabel ?? t('common.cancel', 'Ýatyr') + const loadingText = loadingLabel ?? t('common.saving', 'Saklanýar...') + const prevText = prevLabel ?? t('common.prev', 'Yza') + const nextText = nextLabel ?? t('common.next', 'Indiki') + + return ( +
+ {onCancel && ( + + )} + {onPrev && ( + + )} + {onNext && ( + + )} + {showSubmit && onSubmit && ( + + )} +
+ ) +} diff --git a/src/components/stepBar.tsx b/src/components/stepBar.tsx index 94c2c67..92e915a 100644 --- a/src/components/stepBar.tsx +++ b/src/components/stepBar.tsx @@ -1,4 +1,3 @@ -'use client' import { useEffect, useRef, type KeyboardEvent } from 'react' import { Check, AlertTriangle } from 'lucide-react' diff --git a/src/components/ui/sidebar.tsx b/src/components/ui/sidebar.tsx index e13495f..fe5ca7c 100644 --- a/src/components/ui/sidebar.tsx +++ b/src/components/ui/sidebar.tsx @@ -1,4 +1,3 @@ -"use client" import * as React from "react" import { cva, type VariantProps } from "class-variance-authority" diff --git a/src/components/ui/tooltip.tsx b/src/components/ui/tooltip.tsx index 545cafa..29d10fd 100644 --- a/src/components/ui/tooltip.tsx +++ b/src/components/ui/tooltip.tsx @@ -1,4 +1,3 @@ -"use client" import * as React from "react" import { Tooltip as TooltipPrimitive } from "radix-ui" diff --git a/src/features/allUsers/components/allUsersForm.tsx b/src/features/allUsers/components/allUsersForm.tsx index 3ca16c5..dd3787a 100644 --- a/src/features/allUsers/components/allUsersForm.tsx +++ b/src/features/allUsers/components/allUsersForm.tsx @@ -2,10 +2,9 @@ import { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' import { Label } from '@/components/ui/label' -import { Loader2 } from 'lucide-react' +import { FormActions } from '@/components/formActions' import { useCreateUser, useUpdateUser } from '../hooks/useAllUsers' import type { User, CreateUserPayload, UpdateUserPayload } from '../api/allUsersApi' @@ -300,27 +299,14 @@ export function UserForm({ mode, initialData, userId }: UserFormProps) { - {/* Footer actions */} -
- - -
+ navigate(-1)} + submitLabel={mode === 'create' + ? t('users.actions.create', 'Ulanyjy dörediň') + : t('users.actions.save', 'Ýatda sakla')} + /> ) } \ No newline at end of file diff --git a/src/features/cardBalance/components/cardBalanceForm.tsx b/src/features/cardBalance/components/cardBalanceForm.tsx index bd9f6a8..99adadc 100644 --- a/src/features/cardBalance/components/cardBalanceForm.tsx +++ b/src/features/cardBalance/components/cardBalanceForm.tsx @@ -1,8 +1,8 @@ import { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' -import { Button } from '@/components/ui/button' import { FormInput } from '@/components/formInput' +import { FormActions } from '@/components/formActions' import { type CardBalance } from '@/features/cardBalance/api/cardBalanceApi' import { useCreateCardBalance, useUpdateCardBalance } from '@/features/cardBalance/hooks/useCardBalance' @@ -186,19 +186,18 @@ export function CardBalanceForm({ mode, initialData, cardBalanceId }: CardBalanc - {/* Actions */} -
- - -
+ ) } \ No newline at end of file diff --git a/src/features/cardPins/components/cardPinForm.tsx b/src/features/cardPins/components/cardPinForm.tsx index 464dcb7..dde4dfb 100644 --- a/src/features/cardPins/components/cardPinForm.tsx +++ b/src/features/cardPins/components/cardPinForm.tsx @@ -1,9 +1,11 @@ import { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' +import { toast } from 'sonner' +import { CreditCard, User, FileText } from 'lucide-react' import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' -import { Spinner } from '@/components/ui/spinner' +import { FormActions } from '@/components/formActions' +import { StepBarCards, type StepCardItem } from '@/components/stepBarV2' import type { CardPinItem, CardPinCreatePayload } from '@/features/cardPins/api/cardPinApi' // ─── Types ──────────────────────────────────────────────────────────────────── @@ -36,6 +38,18 @@ interface FormState { } type FormErrors = Partial> +type StepStatus = 'idle' | 'active' | 'done' | 'error' + +// ─── Step field mapping ─────────────────────────────────────────────────────── + +const STEP_FIELDS: Array> = [ + // Step 0 — Kart & Lokasiýa + ['status', 'card_type', 'card_number', 'province', 'branch'], + // Step 1 — Şahsy maglumatlar + ['first_name', 'last_name', 'birth_date', 'phone'], + // Step 2 — Pasport & Faýllar + ['passport_series', 'passport_number', 'passport_file_1', 'passport_file_2', 'passport_file_3', 'passport_file_4'], +] // ─── Constants ──────────────────────────────────────────────────────────────── @@ -45,7 +59,6 @@ const STATUS_OPTIONS = [ { value: 'rejected', label: 'Ret edildi' }, ] -// These would typically come from API — using static options as placeholder const CARD_TYPE_OPTIONS = [ { value: 'altyn_asyr', label: 'Altyn Asyr' }, { value: 'visa', label: 'Visa' }, @@ -53,10 +66,10 @@ const CARD_TYPE_OPTIONS = [ ] 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 = [ @@ -92,29 +105,57 @@ const defaultState: FormState = { // ─── Validation ─────────────────────────────────────────────────────────────── -function validate(form: FormState, mode: 'create' | 'edit'): FormErrors { - const errors: FormErrors = {} +function validate( + form: FormState, + mode: 'create' | 'edit', + stepIndex?: number, +): FormErrors { + const allErrors: FormErrors = {} - if (!form.status) errors.status = 'Status hökmany' - if (!form.card_type) errors.card_type = 'Kart görnüşi hökmany' - if (!form.card_number) errors.card_number = 'Kart belgisi hökmany' - if (!form.province) errors.province = 'Welaýat hökmany' - if (!form.branch) errors.branch = 'Şahamça hökmany' - if (!form.first_name) errors.first_name = 'Ady hökmany' - if (!form.last_name) errors.last_name = 'Familiýasy hökmany' - if (!form.birth_date) errors.birth_date = 'Doglan güni hökmany' - if (!form.phone) errors.phone = 'Telefon hökmany' - if (!form.passport_series) errors.passport_series = 'Pasport seriýasy hökmany' - if (!form.passport_number) errors.passport_number = 'Pasport belgisi hökmany' + if (!form.status) allErrors.status = 'Status hökmany' + if (!form.card_type) allErrors.card_type = 'Kart görnüşi hökmany' + if (!form.card_number) allErrors.card_number = 'Kart belgisi hökmany' + if (!form.province) allErrors.province = 'Welaýat hökmany' + if (!form.branch) allErrors.branch = 'Şahamça hökmany' + if (!form.first_name) allErrors.first_name = 'Ady hökmany' + if (!form.last_name) allErrors.last_name = 'Familiýasy hökmany' + if (!form.birth_date) allErrors.birth_date = 'Doglan güni hökmany' + if (!form.phone) allErrors.phone = 'Telefon hökmany' + if (!form.passport_series) allErrors.passport_series = 'Pasport seriýasy hökmany' + if (!form.passport_number) allErrors.passport_number = 'Pasport belgisi hökmany' if (mode === 'create') { - if (!form.passport_file_1) errors.passport_file_1 = 'Pasport (sahypa 1) hökmany' - if (!form.passport_file_2) errors.passport_file_2 = 'Pasport (2-3-nji sahypa) hökmany' - if (!form.passport_file_3) errors.passport_file_3 = 'Pasport (8-9 sahypa) hökmany' - if (!form.passport_file_4) errors.passport_file_4 = 'Pasport (32-nji sahypa) hökmany' + if (!form.passport_file_1) allErrors.passport_file_1 = 'Pasport (sahypa 1) hökmany' + if (!form.passport_file_2) allErrors.passport_file_2 = 'Pasport (2-3-nji sahypa) hökmany' + if (!form.passport_file_3) allErrors.passport_file_3 = 'Pasport (8-9 sahypa) hökmany' + if (!form.passport_file_4) allErrors.passport_file_4 = 'Pasport (32-nji sahypa) hökmany' } - return errors + if (stepIndex !== undefined) { + const stepKeys = STEP_FIELDS[stepIndex] + const stepErrors: FormErrors = {} + for (const key of stepKeys) { + if (allErrors[key]) stepErrors[key] = allErrors[key] + } + return stepErrors + } + + return allErrors +} + +// ─── Section wrapper ────────────────────────────────────────────────────────── + +function Section({ title, children }: { title?: string; children: React.ReactNode }) { + return ( +
+ {title && ( +
+

{title}

+
+ )} +
{children}
+
+ ) } // ─── Component ──────────────────────────────────────────────────────────────── @@ -123,10 +164,11 @@ export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardP const { t } = useTranslation() const navigate = useNavigate() - const [form, setForm] = useState(defaultState) + const [form, setForm] = useState(defaultState) const [errors, setErrors] = useState({}) + const [currentStep, setCurrentStep] = useState(0) + const [stepStatuses, setStepStatuses] = useState(['active', 'idle', 'idle']) - // Hydrate form when editing useEffect(() => { if (mode === 'edit' && initialData) { setForm({ @@ -153,13 +195,66 @@ export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardP const set = (key: K, value: FormState[K]) => { setForm((prev) => ({ ...prev, [key]: value })) - if (errors[key]) setErrors((prev) => ({ ...prev, [key]: undefined })) + setErrors((prev) => ({ ...prev, [key]: undefined })) } + // ── Step navigation ──────────────────────────────────────────────────────── + + const updateStatus = (index: number, status: StepStatus) => { + setStepStatuses((prev) => { + const next = [...prev] + next[index] = status + return next + }) + } + + const goToStep = (index: number) => { + updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'done') + updateStatus(index, 'active') + setCurrentStep(index) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + const handleNext = () => { + const stepErrors = validate(form, mode, currentStep) + if (Object.keys(stepErrors).length > 0) { + setErrors((prev) => ({ ...prev, ...stepErrors })) + updateStatus(currentStep, 'error') + toast.error('Dogry maglumat girizmegiňizi haýyş edýäris.') + const firstKey = Object.keys(stepErrors)[0] + document.getElementById(`field-${firstKey}`)?.scrollIntoView({ behavior: 'smooth', block: 'center' }) + return + } + updateStatus(currentStep, 'done') + const next = currentStep + 1 + updateStatus(next, 'active') + setCurrentStep(next) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + const handlePrev = () => { + const prev = currentStep - 1 + updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'idle') + updateStatus(prev, 'active') + setCurrentStep(prev) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + // ── Submit ───────────────────────────────────────────────────────────────── + const handleSubmit = () => { - const errs = validate(form, mode) - if (Object.keys(errs).length > 0) { - setErrors(errs) + const allErrors = validate(form, mode) + if (Object.keys(allErrors).length > 0) { + setErrors(allErrors) + const newStatuses = stepStatuses.map((s, i) => { + const stepKeys = STEP_FIELDS[i] + const hasError = stepKeys.some((k) => allErrors[k]) + if (i === currentStep) return hasError ? 'error' : 'active' + if (hasError) return 'error' + return s === 'idle' ? 'idle' : 'done' + }) as StepStatus[] + setStepStatuses(newStatuses) + toast.error('Dogry maglumat girizmegiňizi haýyş edýäris.') return } @@ -184,6 +279,37 @@ export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardP }) } + // ── Step bar items ───────────────────────────────────────────────────────── + + const stepDefs = [ + { + id: 'card', + title: t('cardPin.step.card', 'Kart'), + subtitle: t('cardPin.step.cardSub', 'Görnüş & lokasiýa'), + icon: CreditCard, + }, + { + id: 'personal', + title: t('cardPin.step.personal', 'Şahsy'), + subtitle: t('cardPin.step.personalSub', 'Maglumatlar'), + icon: User, + }, + { + id: 'passport', + title: t('cardPin.step.passport', 'Pasport'), + subtitle: t('cardPin.step.passportSub', 'Resminamalar'), + icon: FileText, + }, + ] + + const stepItems: StepCardItem[] = stepDefs.map((def, i) => ({ + ...def, + status: stepStatuses[i], + })) + + const isFirstStep = currentStep === 0 + const isLastStep = currentStep === stepDefs.length - 1 + const title = mode === 'create' ? t('cardPin.create', 'Kart pin bukja dörediň') : t('cardPin.edit', 'Kart pin bukja redaktirläň') @@ -192,225 +318,249 @@ export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardP ? t('cardPin.createBtn', 'Kart pin bukja dörediň') : t('cardPin.editBtn', 'Kart pin bukja redaktirläň') + // ── Render ───────────────────────────────────────────────────────────────── + return ( -
-

{title}

+
+

{title}

- {/* ── Status & Note ────────────────────────────────────────────────── */} -
- set('status', v)} - options={STATUS_OPTIONS} - error={errors.status} - required - /> - set('note', v)} - placeholder={t('cardPin.notePlaceholder', 'Bellik')} - /> -
- - {/* ── Kart ─────────────────────────────────────────────────────────── */} -
-

- {t('cardPin.cardSection', 'Kart')} -

-
- set('card_type', v)} - options={CARD_TYPE_OPTIONS} - error={errors.card_type} - required - /> - set('card_number', v)} - placeholder={t('cardPin.cardNumberPlaceholder', 'Kart belgisi')} - error={errors.card_number} - required - /> -
-
- - {/* ── Lokasiýa ─────────────────────────────────────────────────────── */} -
-

- {t('cardPin.locationSection', 'Lokasiýa')} -

-
- { set('province', v); set('branch', '') }} - options={PROVINCE_OPTIONS} - error={errors.province} - required - /> - set('branch', v)} - options={[]} // Populated dynamically based on province from API - placeholder={t('cardPin.branchPlaceholder', 'Saýlamak üçin basyň')} - error={errors.branch} - required - /> -
-
- - {/* ── Şahsy maglumatlar ─────────────────────────────────────────────── */} -
-

- {t('cardPin.personalSection', 'Şahsy maglumatlar')} -

-
- set('first_name', v)} - placeholder={t('cardPin.firstName', 'Ady')} - error={errors.first_name} - required - /> - set('last_name', v)} - placeholder={t('cardPin.lastName', 'Familiýasy')} - error={errors.last_name} - required - /> - set('father_name', v)} - placeholder={t('cardPin.fatherName', 'Atasynyň ady')} - /> -
-
- set('birth_date', v)} - error={errors.birth_date} - required - /> - set('phone', v)} - error={errors.phone} - required - /> -
-
- - {/* ── Pasport ───────────────────────────────────────────────────────── */} -
-

- {t('cardPin.passportSection', 'Pasport')} -

-
- set('passport_series', v)} - options={PASSPORT_SERIES_OPTIONS} - error={errors.passport_series} - required - /> - set('passport_number', v)} - placeholder={t('cardPin.passportNumber', 'Pasport belgisi')} - error={errors.passport_number} - required - /> -
-
- set('passport_file_1', f)} - fileValue={form.passport_file_1} - accept="image/*,.pdf" - error={errors.passport_file_1} - required={mode === 'create'} - /> - set('passport_file_2', f)} - fileValue={form.passport_file_2} - accept="image/*,.pdf" - error={errors.passport_file_2} - required={mode === 'create'} - /> - set('passport_file_3', f)} - fileValue={form.passport_file_3} - accept="image/*,.pdf" - error={errors.passport_file_3} - required={mode === 'create'} - /> - set('passport_file_4', f)} - fileValue={form.passport_file_4} - accept="image/*,.pdf" - error={errors.passport_file_4} - required={mode === 'create'} - /> -
-
- - {/* ── Actions ───────────────────────────────────────────────────────── */} -
- - + {/* ── Step Bar ─────────────────────────────────────────────────────── */} +
+
+ + {/* ── Step 0: Kart & Lokasiýa ──────────────────────────────────────── */} + {currentStep === 0 && ( + <> +
+
+
+ set('status', v)} + options={STATUS_OPTIONS} + error={errors.status} + required + /> +
+ set('note', v)} + placeholder={t('cardPin.notePlaceholder', 'Bellik')} + /> +
+
+ +
+
+
+ set('card_type', v)} + options={CARD_TYPE_OPTIONS} + error={errors.card_type} + required + /> +
+
+ set('card_number', v)} + placeholder={t('cardPin.cardNumberPlaceholder', 'Kart belgisi')} + error={errors.card_number} + required + /> +
+
+
+ +
+
+
+ { set('province', v); set('branch', '') }} + options={PROVINCE_OPTIONS} + error={errors.province} + required + /> +
+
+ set('branch', v)} + options={[]} + placeholder={t('cardPin.branchPlaceholder', 'Saýlamak üçin basyň')} + error={errors.branch} + required + /> +
+
+
+ + )} + + {/* ── Step 1: Şahsy maglumatlar ─────────────────────────────────────── */} + {currentStep === 1 && ( +
+
+
+ set('first_name', v)} + placeholder={t('cardPin.firstName', 'Ady')} + error={errors.first_name} + required + /> +
+
+ set('last_name', v)} + placeholder={t('cardPin.lastName', 'Familiýasy')} + error={errors.last_name} + required + /> +
+ set('father_name', v)} + placeholder={t('cardPin.fatherName', 'Atasynyň ady')} + /> +
+ +
+
+ set('birth_date', v)} + error={errors.birth_date} + required + /> +
+
+ set('phone', v)} + error={errors.phone} + required + /> +
+
+
+ )} + + {/* ── Step 2: Pasport & Faýllar ─────────────────────────────────────── */} + {currentStep === 2 && ( +
+
+
+ set('passport_series', v)} + options={PASSPORT_SERIES_OPTIONS} + error={errors.passport_series} + required + /> +
+
+ set('passport_number', v)} + placeholder={t('cardPin.passportNumber', 'Pasport belgisi')} + error={errors.passport_number} + required + /> +
+
+ +
+
+ set('passport_file_1', f)} + fileValue={form.passport_file_1} + accept="image/*,.pdf" + error={errors.passport_file_1} + required={mode === 'create'} + /> +
+
+ set('passport_file_2', f)} + fileValue={form.passport_file_2} + accept="image/*,.pdf" + error={errors.passport_file_2} + required={mode === 'create'} + /> +
+
+ set('passport_file_3', f)} + fileValue={form.passport_file_3} + accept="image/*,.pdf" + error={errors.passport_file_3} + required={mode === 'create'} + /> +
+
+ set('passport_file_4', f)} + fileValue={form.passport_file_4} + accept="image/*,.pdf" + error={errors.passport_file_4} + required={mode === 'create'} + /> +
+
+
+ )} + + {/* ── Form Actions ──────────────────────────────────────────────────── */} + navigate('/card-pins')} + onPrev={!isFirstStep ? handlePrev : undefined} + prevLabel={t('common.prev', 'Yza')} + onNext={!isLastStep ? handleNext : undefined} + nextLabel={t('common.next', 'Indiki')} + showSubmit={isLastStep} + onSubmit={handleSubmit} + submitLabel={submitLabel} + />
) } \ No newline at end of file diff --git a/src/features/cardReasons/components/reasonForm.tsx b/src/features/cardReasons/components/reasonForm.tsx index 8ddbc7b..42b7942 100644 --- a/src/features/cardReasons/components/reasonForm.tsx +++ b/src/features/cardReasons/components/reasonForm.tsx @@ -1,8 +1,8 @@ import { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' -import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' +import { FormActions } from '@/components/formActions' import { FormInput } from '@/components/formInput' import type { CardReason, CreateCardReasonPayload } from '../api/cardReasonsApi' import { useCreateCardReason, useUpdateCardReason } from '../hooks/useCardReasons' @@ -203,29 +203,16 @@ export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFo
- {/* Actions */} -
- - -
+ navigate('/resources/card-states')} + cancelVariant="ghost" + submitLabel={mode === 'create' + ? t('CardReasons.actions.create', 'Kartyň çykarylmagynyň sebäbini döretdiň') + : t('CardReasons.actions.update', 'Täzelemek')} + className="mt-6" + /> ) } \ No newline at end of file diff --git a/src/features/cardRequisites/components/cardRequisiteForm.tsx b/src/features/cardRequisites/components/cardRequisiteForm.tsx index df7cded..c210ab1 100644 --- a/src/features/cardRequisites/components/cardRequisiteForm.tsx +++ b/src/features/cardRequisites/components/cardRequisiteForm.tsx @@ -1,8 +1,11 @@ import { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' -import { Button } from '@/components/ui/button' +import { toast } from 'sonner' +import { CreditCard, User, FileText } from 'lucide-react' import { FormInput } from '@/components/formInput' +import { FormActions } from '@/components/formActions' +import { StepBarCards, type StepCardItem } from '@/components//stepBarV2' import type { CardRequisite, CardRequisiteStatus, CreateCardRequisitePayload } from '../api/cardRequisitesApi' import { useCreateCardRequisite, useUpdateCardRequisite } from '../hooks/useCardRequisites' @@ -59,6 +62,19 @@ interface FormErrors { passport_page32?: string } +type StepStatus = 'idle' | 'active' | 'done' | 'error' + +// ─── Step field mapping ─────────────────────────────────────────────────────── + +const STEP_FORM_FIELDS: Array> = [ + // Step 0 — Kart & Lokasiýa + ['status', 'card_type', 'card_number', 'card_expiry_month', 'card_expiry_year', 'province_id', 'branch_id'], + // Step 1 — Şahsy maglumatlar + ['first_name', 'last_name', 'birth_date', 'phone'], + // Step 2 — Pasport & Faýllar + ['passport_series', 'passport_number', 'passport_page1', 'passport_page2_3', 'passport_page8_9', 'passport_page32'], +] + // ─── Constants ──────────────────────────────────────────────────────────────── const STATUS_OPTIONS = [ @@ -143,39 +159,56 @@ function validate( files: FileState, mode: 'create' | 'edit', t: (k: string, fallback: string) => string, + stepIndex?: number, ): FormErrors { - const errors: FormErrors = {} + const allErrors: FormErrors = {} - if (!form.status) errors.status = t('Status is required', 'Status hökmanydyr') - if (!form.card_type) errors.card_type = t('Card type is required', 'Görnüşi hökmanydyr') - if (!form.card_number) errors.card_number = t('Card number is required', 'Kart belgisi hökmanydyr') - if (!form.card_expiry_month) errors.card_expiry_month = t('Expiry month is required', 'Möhleti (aý) hökmanydyr') - if (!form.card_expiry_year) errors.card_expiry_year = t('Expiry year is required', 'Möhleti (ýyl) hökmanydyr') - if (!form.province_id) errors.province_id = t('Province is required', 'Welaýat hökmanydyr') - if (!form.branch_id) errors.branch_id = t('Branch is required', 'Şahamça hökmanydyr') - if (!form.first_name) errors.first_name = t('First name is required', 'Ady hökmanydyr') - if (!form.last_name) errors.last_name = t('Last name is required', 'Familiýasy hökmanydyr') - if (!form.birth_date) errors.birth_date = t('Birth date is required', 'Doglan güni hökmanydyr') - if (!form.phone) errors.phone = t('Phone is required', 'Telefon hökmanydyr') - if (!form.passport_series) errors.passport_series = t('Passport series is required', 'Pasport seriýasy hökmanydyr') - if (!form.passport_number) errors.passport_number = t('Passport number is required', 'Pasport belgisi hökmanydyr') + if (!form.status) allErrors.status = t('Status is required', 'Status hökmanydyr') + if (!form.card_type) allErrors.card_type = t('Card type is required', 'Görnüşi hökmanydyr') + if (!form.card_number) allErrors.card_number = t('Card number is required', 'Kart belgisi hökmanydyr') + if (!form.card_expiry_month) allErrors.card_expiry_month = t('Expiry month is required', 'Möhleti (aý) hökmanydyr') + if (!form.card_expiry_year) allErrors.card_expiry_year = t('Expiry year is required', 'Möhleti (ýyl) hökmanydyr') + if (!form.province_id) allErrors.province_id = t('Province is required', 'Welaýat hökmanydyr') + if (!form.branch_id) allErrors.branch_id = t('Branch is required', 'Şahamça hökmanydyr') + if (!form.first_name) allErrors.first_name = t('First name is required', 'Ady hökmanydyr') + if (!form.last_name) allErrors.last_name = t('Last name is required', 'Familiýasy hökmanydyr') + if (!form.birth_date) allErrors.birth_date = t('Birth date is required', 'Doglan güni hökmanydyr') + if (!form.phone) allErrors.phone = t('Phone is required', 'Telefon hökmanydyr') + if (!form.passport_series) allErrors.passport_series = t('Passport series is required', 'Pasport seriýasy hökmanydyr') + if (!form.passport_number) allErrors.passport_number = t('Passport number is required', 'Pasport belgisi hökmanydyr') - // Files only required on create if (mode === 'create') { - if (!files.passport_page1) errors.passport_page1 = t('Required', 'Hökmanydyr') - if (!files.passport_page2_3) errors.passport_page2_3 = t('Required', 'Hökmanydyr') - if (!files.passport_page8_9) errors.passport_page8_9 = t('Required', 'Hökmanydyr') - if (!files.passport_page32) errors.passport_page32 = t('Required', 'Hökmanydyr') + if (!files.passport_page1) allErrors.passport_page1 = t('Required', 'Hökmanydyr') + if (!files.passport_page2_3) allErrors.passport_page2_3 = t('Required', 'Hökmanydyr') + if (!files.passport_page8_9) allErrors.passport_page8_9 = t('Required', 'Hökmanydyr') + if (!files.passport_page32) allErrors.passport_page32 = t('Required', 'Hökmanydyr') } - return errors + if (stepIndex !== undefined) { + const stepKeys = STEP_FORM_FIELDS[stepIndex] + const stepErrors: FormErrors = {} + for (const key of stepKeys) { + const k = key as keyof FormErrors + if (allErrors[k]) stepErrors[k] = allErrors[k] + } + return stepErrors + } + + return allErrors } -// ─── Section header ─────────────────────────────────────────────────────────── +// ─── Section wrapper ────────────────────────────────────────────────────────── -function SectionTitle({ children }: { children: React.ReactNode }) { +function Section({ title, children }: { title?: string; children: React.ReactNode }) { return ( -

{children}

+
+ {title && ( +
+

{title}

+
+ )} +
{children}
+
) } @@ -189,13 +222,14 @@ export function CardRequisiteForm({ const { t } = useTranslation() const navigate = useNavigate() - const [form, setForm] = useState(EMPTY_FORM) - const [files, setFiles] = useState(EMPTY_FILES) + const [form, setForm] = useState(EMPTY_FORM) + const [files, setFiles] = useState(EMPTY_FILES) const [errors, setErrors] = useState({}) + const [currentStep, setCurrentStep] = useState(0) + const [stepStatuses, setStepStatuses] = useState(['active', 'idle', 'idle']) const createMutation = useCreateCardRequisite() const updateMutation = useUpdateCardRequisite(cardRequisiteId ?? '') - const isPending = createMutation.isPending || updateMutation.isPending useEffect(() => { @@ -220,27 +254,79 @@ export function CardRequisiteForm({ } }, [mode, initialData]) + // ── Field setters ────────────────────────────────────────────────────────── + const setField = (field: keyof FormState) => (value: string) => { setForm((prev) => { const next = { ...prev, [field]: value } - // Reset branch when province changes if (field === 'province_id') next.branch_id = '' return next }) - if (errors[field as keyof FormErrors]) - setErrors((prev) => ({ ...prev, [field]: undefined })) + setErrors((prev) => ({ ...prev, [field]: undefined })) } const setFile = (field: keyof FileState) => (file: File | null) => { setFiles((prev) => ({ ...prev, [field]: file })) - if (errors[field as keyof FormErrors]) - setErrors((prev) => ({ ...prev, [field]: undefined })) + setErrors((prev) => ({ ...prev, [field]: undefined })) } + // ── Step navigation ──────────────────────────────────────────────────────── + + const updateStatus = (index: number, status: StepStatus) => { + setStepStatuses((prev) => { + const next = [...prev] + next[index] = status + return next + }) + } + + const goToStep = (index: number) => { + updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'done') + updateStatus(index, 'active') + setCurrentStep(index) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + const handleNext = () => { + const stepErrors = validate(form, files, mode, t, currentStep) + if (Object.keys(stepErrors).length > 0) { + setErrors((prev) => ({ ...prev, ...stepErrors })) + updateStatus(currentStep, 'error') + toast.error(t('Fix errors', 'Dogry maglumat girizmegiňizi haýyş edýäris.')) + const firstKey = Object.keys(stepErrors)[0] + document.getElementById(`field-${firstKey}`)?.scrollIntoView({ behavior: 'smooth', block: 'center' }) + return + } + updateStatus(currentStep, 'done') + const next = currentStep + 1 + updateStatus(next, 'active') + setCurrentStep(next) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + const handlePrev = () => { + const prev = currentStep - 1 + updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'idle') + updateStatus(prev, 'active') + setCurrentStep(prev) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + // ── Submit ───────────────────────────────────────────────────────────────── + const handleSubmit = async () => { - const validationErrors = validate(form, files, mode, t) - if (Object.keys(validationErrors).length > 0) { - setErrors(validationErrors) + const allErrors = validate(form, files, mode, t) + if (Object.keys(allErrors).length > 0) { + setErrors(allErrors) + const newStatuses = stepStatuses.map((s, i) => { + const stepKeys = STEP_FORM_FIELDS[i] + const hasError = stepKeys.some((k) => allErrors[k as keyof FormErrors]) + if (i === currentStep) return hasError ? 'error' : 'active' + if (hasError) return 'error' + return s === 'idle' ? 'idle' : 'done' + }) as StepStatus[] + setStepStatuses(newStatuses) + toast.error(t('Fix errors', 'Dogry maglumat girizmegiňizi haýyş edýäris.')) return } @@ -269,233 +355,316 @@ export function CardRequisiteForm({ const branchOptions = BRANCH_OPTIONS[form.province_id] ?? [] + // ── Step bar items ───────────────────────────────────────────────────────── + + const stepDefs = [ + { + id: 'card', + title: t('Card', 'Kart'), + subtitle: t('Type & location', 'Görnüş & lokasiýa'), + icon: CreditCard, + }, + { + id: 'personal', + title: t('Personal', 'Şahsy'), + subtitle: t('Name & contact', 'At & telefon'), + icon: User, + }, + { + id: 'passport', + title: t('Passport', 'Pasport'), + subtitle: t('Docs & files', 'Resminamalar'), + icon: FileText, + }, + ] + + const stepItems: StepCardItem[] = stepDefs.map((def, i) => ({ + ...def, + status: stepStatuses[i], + })) + + const isFirstStep = currentStep === 0 + const isLastStep = currentStep === stepDefs.length - 1 + + // ── Render ───────────────────────────────────────────────────────────────── + return ( -
- {/* ── General ── */} -
-
- - -
+
+ + {/* ── Step Bar ─────────────────────────────────────────────────────── */} +
+
- {/* ── Kart ── */} - {t('Card', 'Kart')} -
-
- - - - -
-
+ {/* ── Step 0: Kart & Lokasiýa ──────────────────────────────────────── */} + {currentStep === 0 && ( + <> +
+
+
+ +
+ +
+
- {/* ── Lokasiýa ── */} - {t('Location', 'Lokasiýa')} -
-
- - -
-
+
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+
- {/* ── Şahsy maglumatlar ── */} - {t('Personal information', 'Şahsy maglumatlar')} -
-
- - - -
-
- - -
-
+
+
+
+ +
+
+ +
+
+
+ + )} - {/* ── Pasport ── */} - {t('Passport', 'Pasport')} -
-
- - -
+ {/* ── Step 1: Şahsy maglumatlar ─────────────────────────────────────── */} + {currentStep === 1 && ( +
+
+
+ +
+
+ +
+ +
-
- - - - -
-
+
+
+ +
+
+ +
+
+ + )} - {/* ── Actions ── */} -
- -
+ : t('Save changes', 'Üýtgetmeleri sakla') + } + className="mt-6" + />
) -} +} \ No newline at end of file diff --git a/src/features/cardTransactions/components/cardTransactionForm.tsx b/src/features/cardTransactions/components/cardTransactionForm.tsx index cf49c66..1308c12 100644 --- a/src/features/cardTransactions/components/cardTransactionForm.tsx +++ b/src/features/cardTransactions/components/cardTransactionForm.tsx @@ -1,8 +1,8 @@ import { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' -import { Button } from '@/components/ui/button' import { FormInput } from '@/components/formInput' +import { FormActions } from '@/components/formActions' import type { CardTransaction } from '../api/cardTransactionsApi' import { useCreateCardTransaction, useUpdateCardTransaction } from '../hooks/useCardTransactions' @@ -200,19 +200,18 @@ export function CardTransactionForm({
- {/* Actions */} -
- - -
+ ) } diff --git a/src/features/cardTypes/components/cardTypesForm.tsx b/src/features/cardTypes/components/cardTypesForm.tsx index a8b4cf5..2ef5fb2 100644 --- a/src/features/cardTypes/components/cardTypesForm.tsx +++ b/src/features/cardTypes/components/cardTypesForm.tsx @@ -1,8 +1,8 @@ import { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' -import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' +import { FormActions } from '@/components/formActions' import { FormInput } from '@/components/formInput' import type { CardType, CreateCardTypePayload } from '../api/cardTypesApi' import { useCreateCardType, useUpdateCardType } from '../hooks/useCardTypes' @@ -196,29 +196,16 @@ export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProp - {/* Actions */} -
- - -
+ navigate('/settings/card/card-types')} + cancelVariant="ghost" + submitLabel={mode === 'create' + ? t('cardTypes.actions.create', 'Kart görnüşi döretdiň') + : t('cardTypes.actions.update', 'Täzelemek')} + className="mt-6" + /> ) } diff --git a/src/features/clients/components/clientForm.tsx b/src/features/clients/components/clientForm.tsx index 25c1979..d4ac0f5 100644 --- a/src/features/clients/components/clientForm.tsx +++ b/src/features/clients/components/clientForm.tsx @@ -1,8 +1,8 @@ import { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' -import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' +import { FormActions } from '@/components/formActions' import { FormInput } from '@/components/formInput' import { useCreateClient, useUpdateClient } from '../hooks/useClients' import type { Client, CreateClientPayload, UpdateClientPayload } from '../api/clientsApi' @@ -227,29 +227,16 @@ export function ClientForm({ mode, initialData, clientId }: ClientFormProps) { /> - {/* Actions */} -
- - -
+ navigate(-1)} + cancelVariant="ghost" + submitLabel={mode === 'create' + ? t('clients.createBtn', 'Müşderi döredin') + : t('clients.updateBtn', 'Üýtgetmeleri sakla')} + className="px-6 py-4 border-t border-border bg-muted/20" + /> ) } \ No newline at end of file diff --git a/src/features/currencyRates/components/currencyRatesForm.tsx b/src/features/currencyRates/components/currencyRatesForm.tsx index da99018..9ed429a 100644 --- a/src/features/currencyRates/components/currencyRatesForm.tsx +++ b/src/features/currencyRates/components/currencyRatesForm.tsx @@ -4,7 +4,7 @@ import { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' +import { FormActions } from '@/components/formActions' import { CURRENCY_OPTIONS, type CurrencyCode, type CurrencyRate } from '../api/currencyRatesApi' import { useCreateCurrencyRate, useUpdateCurrencyRate } from '../hooks/useCurrencyRates' @@ -175,29 +175,16 @@ export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateForm - {/* Footer Actions */} -
- - -
+ ) } \ No newline at end of file diff --git a/src/features/districts/components/districtsForm.tsx b/src/features/districts/components/districtsForm.tsx index 30f38f0..580acd0 100644 --- a/src/features/districts/components/districtsForm.tsx +++ b/src/features/districts/components/districtsForm.tsx @@ -1,8 +1,8 @@ import { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' -import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' +import { FormActions } from '@/components/formActions' import { FormInput } from '@/components/formInput' import type { District, CreateDistrictPayload } from '../api/districtsApi' import { useCreateDistrict, useUpdateDistrict } from '../hooks/useDistricts' @@ -165,28 +165,16 @@ export function DistrictForm({ mode, initialData, districtId }: DistrictFormProp -
- - -
+ navigate('/settings/location/districts')} + cancelVariant="ghost" + submitLabel={mode === 'create' + ? t('districts.actions.create', 'Etrap döret') + : t('districts.actions.update', 'Täzelemek')} + className="mt-6" + /> ) } diff --git a/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx b/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx index 2e148c2..f597a82 100644 --- a/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx +++ b/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx @@ -1,12 +1,26 @@ -import { useState, useCallback } from 'react' -import { useNavigate } from 'react-router-dom' -import { useTranslation } from 'react-i18next' -import { toast } from 'sonner' -import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' -import { useCreateLoanOrderMobile, useUpdateLoanOrderMobile } from '@/features/loanOrderMobiles/hooks/useLoanOrderMobiles' -import type { LoanOrderMobile, LoanOrderMobilePayload } from '@/features/loanOrderMobiles/api/loanOrderMobilesApi' +import { useState, useCallback } from "react"; +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; +import { + FileText, + User, + Phone, + CreditCard, + Upload, +} from "lucide-react"; +import { FormInput } from "@/components/formInput"; +import { FormActions } from "@/components/formActions"; +import { StepBarCards, type StepCardItem } from "@/components/stepBarV2"; +import { cn } from "@/lib/utils"; +import { + useCreateLoanOrderMobile, + useUpdateLoanOrderMobile, +} from "@/features/loanOrderMobiles/hooks/useLoanOrderMobiles"; +import type { + LoanOrderMobile, + LoanOrderMobilePayload, +} from "@/features/loanOrderMobiles/api/loanOrderMobilesApi"; // ─── Section Wrapper ────────────────────────────────────────────────────────── @@ -15,420 +29,562 @@ function Section({ children, className, }: { - title: string - children: React.ReactNode - className?: string + title: string; + children: React.ReactNode; + className?: string; }) { return ( -
+

{title}

{children}
- ) + ); } // ─── Grid helpers ───────────────────────────────────────────────────────────── -const grid2 = 'grid grid-cols-1 sm:grid-cols-2 gap-6' -const grid3 = 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6' -const grid4 = 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6' +const grid2 = "grid grid-cols-1 sm:grid-cols-2 gap-6"; +const grid3 = "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6"; +const grid4 = "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6"; // ─── Static options ─────────────────────────────────────────────────────────── const REGION_OPTIONS = [ - { value: 'Aşgabat', label: 'Aşgabat' }, - { value: 'Ahal', label: 'Ahal' }, - { value: 'Balkan', label: 'Balkan' }, - { value: 'Daşoguz', label: 'Daşoguz' }, - { value: 'Lebap', label: 'Lebap' }, - { value: 'Mary', label: 'Mary' }, - { value: 'Arkadag', label: 'Arkadag' }, -] + { value: "Aşgabat", label: "Aşgabat" }, + { value: "Ahal", label: "Ahal" }, + { value: "Balkan", label: "Balkan" }, + { value: "Daşoguz", label: "Daşoguz" }, + { value: "Lebap", label: "Lebap" }, + { value: "Mary", label: "Mary" }, + { value: "Arkadag", label: "Arkadag" }, +]; const EDUCATION_OPTIONS = [ - { value: 'high', label: 'Ýokary bilim' }, - { value: 'unfinished_high', label: 'Gutarylmadyk ýokary bilim' }, - { value: 'masters', label: 'Magistr' }, - { value: 'phd', label: 'Ylymlaryň doktory' }, - { value: 'middle', label: 'Orta mekdep' }, - { value: 'school', label: 'Orta bilim' }, - { value: 'school_dropout', label: 'Gutarylmadyk orta bilim' }, -] + { value: "high", label: "Ýokary bilim" }, + { value: "unfinished_high", label: "Gutarylmadyk ýokary bilim" }, + { value: "masters", label: "Magistr" }, + { value: "phd", label: "Ylymlaryň doktory" }, + { value: "middle", label: "Orta mekdep" }, + { value: "school", label: "Orta bilim" }, + { value: "school_dropout", label: "Gutarylmadyk orta bilim" }, +]; const MARRIAGE_OPTIONS = [ - { value: 'MARRIED', label: 'Öýlenen / Durmuşa çykan' }, - { value: 'SINGLE', label: 'Öýlenmedik / Durmuşa çykmadyk' }, - { value: 'DIVORCED', label: 'Aýrylşan' }, - { value: 'WIDOW', label: 'Adamsy ýa-da aýaly aradan çykan' }, - { value: 'LEGAL', label: 'Raýat nika' }, -] + { value: "MARRIED", label: "Öýlenen / Durmuşa çykan" }, + { value: "SINGLE", label: "Öýlenmedik / Durmuşa çykmadyk" }, + { value: "DIVORCED", label: "Aýrylşan" }, + { value: "WIDOW", label: "Adamsy ýa-da aýaly aradan çykan" }, + { value: "LEGAL", label: "Raýat nika" }, +]; const STATUS_OPTIONS = [ - { value: 'GARAŞYLÝAR', label: 'Garaşylýar' }, - { value: 'IŞLENÝÄR', label: 'Işlenýär' }, - { value: 'KANAGATLANDYRYLAN', label: 'Kanagatlandyrylan' }, - { value: 'RED_EDILDI', label: 'Red edildi' }, -] + { value: "GARAŞYLÝAR", label: "Garaşylýar" }, + { value: "IŞLENÝÄR", label: "Işlenýär" }, + { value: "KANAGATLANDYRYLAN", label: "Kanagatlandyrylan" }, + { value: "RED_EDILDI", label: "Red edildi" }, +]; const LOAN_TYPE_OPTIONS = [ - { value: 'consumer', label: 'Sarp ediş karzy' }, - { value: 'mortgage', label: 'Ipoteka' }, - { value: 'car', label: 'Awtoulag karzy' }, - { value: 'student', label: 'Talyplar üçin' }, - { value: 'business', label: 'Işewürlik karzy' }, -] + { value: "consumer", label: "Sarp ediş karzy" }, + { value: "mortgage", label: "Ipoteka" }, + { value: "car", label: "Awtoulag karzy" }, + { value: "student", label: "Talyplar üçin" }, + { value: "business", label: "Işewürlik karzy" }, +]; const PASSPORT_SERIES_OPTIONS = [ - { value: 'I', label: 'I' }, - { value: 'II', label: 'II' }, -] + { value: "I", label: "I" }, + { value: "II", label: "II" }, +]; // ─── Form State ─────────────────────────────────────────────────────────────── interface FormState { - status: string - loanType: string - region: string - branch: string - firstName: string - lastName: string - patronicName: string - education: string - marriageStatus: string - dateOfBirth: string - residence: string - currentResidence: string - passportSerie: string - passportNumber: string - passportDateOfIssue: string - passportGivenBy: string - bornPlace: string - email: string - phone: string - phoneAdditional: string - homePhone: string - workCompany: string - workHrPhone: string - workRegion: string - workProvince: string - position: string - salary: string - workStartedAt: string - passportPage1: File | null - passportPage23: File | null - passportPage89: File | null - passportPage32: File | null - - // New fields - note: string - loanAmount: string - loanHistory: string - - cardNumber: string - cardName: string - cardExpMonth: string - cardExpYear: string - - guarantor1Name: string - guarantor1Surname: string - guarantor1Patronic: string - guarantor1PassportSerie: string - guarantor1PassportNumber: string - guarantor1CardNumber: string - guarantor1CardName: string - guarantor1CardExpMonth: string - guarantor1CardExpYear: string - guarantor1Salary: string + status: string; + loanType: string; + region: string; + branch: string; + firstName: string; + lastName: string; + patronicName: string; + education: string; + marriageStatus: string; + dateOfBirth: string; + residence: string; + currentResidence: string; + passportSerie: string; + passportNumber: string; + passportDateOfIssue: string; + passportGivenBy: string; + bornPlace: string; + email: string; + phone: string; + phoneAdditional: string; + homePhone: string; + workCompany: string; + workHrPhone: string; + workRegion: string; + workProvince: string; + position: string; + salary: string; + workStartedAt: string; + passportPage1: File | null; + passportPage23: File | null; + passportPage89: File | null; + passportPage32: File | null; + note: string; + loanAmount: string; + loanHistory: string; + cardNumber: string; + cardName: string; + cardExpMonth: string; + cardExpYear: string; + guarantor1Name: string; + guarantor1Surname: string; + guarantor1Patronic: string; + guarantor1PassportSerie: string; + guarantor1PassportNumber: string; + guarantor1CardNumber: string; + guarantor1CardName: string; + guarantor1CardExpMonth: string; + guarantor1CardExpYear: string; + guarantor1Salary: string; } -type FormErrors = Partial> +type FormErrors = Partial>; const INITIAL_STATE: FormState = { - status: 'GARAŞYLÝAR', - loanType: '', - region: 'Aşgabat', - branch: '', - firstName: '', - lastName: '', - patronicName: '', - education: '', - marriageStatus: '', - dateOfBirth: '', - residence: '', - currentResidence: '', - passportSerie: '', - passportNumber: '', - passportDateOfIssue: '', - passportGivenBy: '', - bornPlace: '', - email: '', - phone: '', - phoneAdditional: '', - homePhone: '', - workCompany: '', - workHrPhone: '', - workRegion: 'Aşgabat', - workProvince: '', - position: '', - salary: '', - workStartedAt: '', + status: "GARAŞYLÝAR", + loanType: "", + region: "Aşgabat", + branch: "", + firstName: "", + lastName: "", + patronicName: "", + education: "", + marriageStatus: "", + dateOfBirth: "", + residence: "", + currentResidence: "", + passportSerie: "", + passportNumber: "", + passportDateOfIssue: "", + passportGivenBy: "", + bornPlace: "", + email: "", + phone: "", + phoneAdditional: "", + homePhone: "", + workCompany: "", + workHrPhone: "", + workRegion: "Aşgabat", + workProvince: "", + position: "", + salary: "", + workStartedAt: "", passportPage1: null, passportPage23: null, passportPage89: null, passportPage32: null, - - note: '', - loanAmount: '', - loanHistory: '', - - cardNumber: '', - cardName: '', - cardExpMonth: '', - cardExpYear: '', - - guarantor1Name: '', - guarantor1Surname: '', - guarantor1Patronic: '', - guarantor1PassportSerie: '', - guarantor1PassportNumber: '', - guarantor1CardNumber: '', - guarantor1CardName: '', - guarantor1CardExpMonth: '', - guarantor1CardExpYear: '', - guarantor1Salary: '', -} - -// ─── Map LoanOrder → FormState (edit modunda başlangıç değerleri) ───────────── + note: "", + loanAmount: "", + loanHistory: "", + cardNumber: "", + cardName: "", + cardExpMonth: "", + cardExpYear: "", + guarantor1Name: "", + guarantor1Surname: "", + guarantor1Patronic: "", + guarantor1PassportSerie: "", + guarantor1PassportNumber: "", + guarantor1CardNumber: "", + guarantor1CardName: "", + guarantor1CardExpMonth: "", + guarantor1CardExpYear: "", + guarantor1Salary: "", +}; function mapToFormState(order: LoanOrderMobile): FormState { return { - status: order.status ?? 'GARAŞYLÝAR', - loanType: order.loanType ?? '', - region: order.region ?? 'Aşgabat', - branch: order.branch ?? '', - firstName: order.firstName ?? '', - lastName: order.lastName ?? '', - patronicName: order.patronicName ?? '', - education: order.education ?? '', - marriageStatus: order.marriageStatus ?? '', - dateOfBirth: order.dateOfBirth ?? '', - residence: order.residence ?? '', - currentResidence: order.currentResidence ?? '', - passportSerie: order.passportSerie ?? '', - passportNumber: order.passportNumber ?? '', - passportDateOfIssue: order.passportDateOfIssue ?? '', - passportGivenBy: order.passportGivenBy ?? '', - bornPlace: order.bornPlace ?? '', - email: order.email ?? '', - phone: order.phone ?? '', - phoneAdditional: order.phoneAdditional ?? '', - homePhone: order.homePhone ?? '', - workCompany: order.workCompany ?? '', - workHrPhone: order.workHrPhone ?? '', - workRegion: order.workRegion ?? 'Aşgabat', - workProvince: order.workProvince ?? '', - position: order.position ?? '', - salary: order.salary != null ? String(order.salary) : '', - workStartedAt: order.workStartedAt ?? '', - // File field'ları edit modunda null kalır — mevcut URL'ler ayrı gösterilir - passportPage1: null, + status: order.status ?? "GARAŞYLÝAR", + loanType: order.loanType ?? "", + region: order.region ?? "Aşgabat", + branch: order.branch ?? "", + firstName: order.firstName ?? "", + lastName: order.lastName ?? "", + patronicName: order.patronicName ?? "", + education: order.education ?? "", + marriageStatus: order.marriageStatus ?? "", + dateOfBirth: order.dateOfBirth ?? "", + residence: order.residence ?? "", + currentResidence: order.currentResidence ?? "", + passportSerie: order.passportSerie ?? "", + passportNumber: order.passportNumber ?? "", + passportDateOfIssue: order.passportDateOfIssue ?? "", + passportGivenBy: order.passportGivenBy ?? "", + bornPlace: order.bornPlace ?? "", + email: order.email ?? "", + phone: order.phone ?? "", + phoneAdditional: order.phoneAdditional ?? "", + homePhone: order.homePhone ?? "", + workCompany: order.workCompany ?? "", + workHrPhone: order.workHrPhone ?? "", + workRegion: order.workRegion ?? "Aşgabat", + workProvince: order.workProvince ?? "", + position: order.position ?? "", + salary: order.salary != null ? String(order.salary) : "", + workStartedAt: order.workStartedAt ?? "", + passportPage1: null, passportPage23: null, passportPage89: null, passportPage32: null, - - note: order.note ?? '', - loanAmount: order.loanAmount != null ? String(order.loanAmount) : '', - loanHistory: order.loanHistory ?? '', - - cardNumber: order.cardNumber ?? '', - cardName: order.cardName ?? '', - cardExpMonth: order.cardExpMonth ?? '', - cardExpYear: order.cardExpYear ?? '', - - guarantor1Name: order.guarantor1Name ?? '', - guarantor1Surname: order.guarantor1Surname ?? '', - guarantor1Patronic: order.guarantor1Patronic ?? '', - guarantor1PassportSerie: order.guarantor1PassportSerie ?? '', - guarantor1PassportNumber: order.guarantor1PassportNumber ?? '', - guarantor1CardNumber: order.guarantor1CardNumber ?? '', - guarantor1CardName: order.guarantor1CardName ?? '', - guarantor1CardExpMonth: order.guarantor1CardExpMonth ?? '', - guarantor1CardExpYear: order.guarantor1CardExpYear ?? '', - guarantor1Salary: order.guarantor1Salary != null ? String(order.guarantor1Salary) : '', - } + note: order.note ?? "", + loanAmount: order.loanAmount != null ? String(order.loanAmount) : "", + loanHistory: order.loanHistory ?? "", + cardNumber: order.cardNumber ?? "", + cardName: order.cardName ?? "", + cardExpMonth: order.cardExpMonth ?? "", + cardExpYear: order.cardExpYear ?? "", + guarantor1Name: order.guarantor1Name ?? "", + guarantor1Surname: order.guarantor1Surname ?? "", + guarantor1Patronic: order.guarantor1Patronic ?? "", + guarantor1PassportSerie: order.guarantor1PassportSerie ?? "", + guarantor1PassportNumber: order.guarantor1PassportNumber ?? "", + guarantor1CardNumber: order.guarantor1CardNumber ?? "", + guarantor1CardName: order.guarantor1CardName ?? "", + guarantor1CardExpMonth: order.guarantor1CardExpMonth ?? "", + guarantor1CardExpYear: order.guarantor1CardExpYear ?? "", + guarantor1Salary: + order.guarantor1Salary != null ? String(order.guarantor1Salary) : "", + }; } +// ─── Step definitions ───────────────────────────────────────────────────────── + +// Keys that belong to each step — used for per-step validation +const STEP_FIELDS: Array> = [ + // Step 0 — Karz & Lokasiýa + ["loanType", "loanAmount", "region", "branch"], + // Step 1 — Şahsy maglumatlar & Pasport + [ + "firstName", + "lastName", + "education", + "marriageStatus", + "dateOfBirth", + "residence", + "passportSerie", + "passportNumber", + "passportDateOfIssue", + "passportGivenBy", + ], + // Step 2 — Habarlaşmak & Iş + [ + "phone", + "workCompany", + "position", + "salary", + "workStartedAt", + ], + // Step 3 — Kart & Zamun + [ + "cardNumber", + "cardName", + "cardExpMonth", + "cardExpYear", + "guarantor1Name", + "guarantor1Surname", + "guarantor1PassportSerie", + "guarantor1PassportNumber", + "guarantor1CardNumber", + "guarantor1CardName", + "guarantor1CardExpMonth", + "guarantor1CardExpYear", + "guarantor1Salary", + ], + // Step 4 — Faýllar & Status + ["passportPage1", "passportPage23"], +]; + // ─── Validation ─────────────────────────────────────────────────────────────── function validate( form: FormState, t: (k: string) => string, - mode: 'create' | 'edit' + mode: "create" | "edit", + stepIndex?: number, ): FormErrors { - const errors: FormErrors = {} + const allErrors: FormErrors = {}; const req = (key: keyof FormState, label: string) => { - const val = form[key] - if (!val || (typeof val === 'string' && !val.trim())) { - errors[key] = `${label} — ${t('required') || 'hökmany'}` + const val = form[key]; + if (!val || (typeof val === "string" && !val.trim())) { + allErrors[key] = `${label} — ${t("required") || "hökmany"}`; } + }; + + req("loanType", t("Loan type") || "Karz görnüşi"); + req("region", t("Region") || "Welaýat"); + req("branch", t("Branch") || "Şahamça"); + req("firstName", t("Name") || "Ady"); + req("lastName", t("Surname") || "Familiýasy"); + req("education", t("Education") || "Bilimi"); + req("marriageStatus", t("Marriage status") || "Maşgala ýagdaýy"); + req("dateOfBirth", t("Date of birth") || "Doglan güni"); + req("residence", t("Residence (passport)") || "Ýazgy edilen salgy"); + req("passportSerie", t("Passport serie") || "Pasport seriýasy"); + req("passportNumber", t("Passport number") || "Pasport belgisi"); + req("passportDateOfIssue", t("Passport date of issue") || "Pasport berlen senesi"); + req("passportGivenBy", t("Passport given by") || "Kim tarapyndan berildi"); + req("phone", t("Phone") || "Telefon"); + req("workCompany", t("Work company name") || "Kärhananyň ady"); + req("position", t("Position") || "Wezipe"); + req("salary", t("Salary") || "Zähmet haky"); + req("workStartedAt", t("Work started at") || "Işe başlan wagty"); + req("loanAmount", t("Loan amount") || "Karz möçberi"); + req("cardNumber", t("Card number") || "Kart belgisi"); + req("cardName", t("Card name") || "Kartdaky ady"); + req("cardExpMonth", t("Card exp month") || "Kart Möhleti (aý)"); + req("cardExpYear", t("Card exp year") || "Kart Möhleti (ýyl)"); + req("guarantor1Name", t("Guarantor name") || "Zamunyň ady"); + req("guarantor1Surname", t("Guarantor surname") || "Zamunyň familiýasy"); + req("guarantor1PassportSerie", t("Guarantor passport serie") || "Pasport seriýasy (Zamun)"); + req("guarantor1PassportNumber", t("Guarantor passport number") || "Pasport belgisi (Zamun)"); + req("guarantor1CardNumber", t("Guarantor card number") || "Kart belgisi (Zamun)"); + req("guarantor1CardName", t("Guarantor card name") || "Kartdaky ady (Zamun)"); + req("guarantor1CardExpMonth", t("Guarantor card exp month") || "Möhleti (aý) (Zamun)"); + req("guarantor1CardExpYear", t("Guarantor card exp year") || "Möhleti (ýyl) (Zamun)"); + req("guarantor1Salary", t("Guarantor salary") || "Ortaca zähmet haky (Zamun)"); + + if (form.phone && form.phone.replace(/\D/g, "").length < 8) { + allErrors.phone = "Telefon belgisi nädogry"; } - req('loanType', t('Loan type') || 'Karz görnüşi') - req('region', t('Region') || 'Welaýat') - req('branch', t('Branch') || 'Şahamça') - req('firstName', t('Name') || 'Ady') - req('lastName', t('Surname') || 'Familiýasy') - req('education', t('Education') || 'Bilimi') - req('marriageStatus', t('Marriage status') || 'Maşgala ýagdaýy') - req('dateOfBirth', t('Date of birth') || 'Doglan güni') - req('residence', t('Residence (passport)') || 'Ýazgy edilen salgy') - req('passportSerie', t('Passport serie') || 'Pasport seriýasy') - req('passportNumber', t('Passport number') || 'Pasport belgisi') - req('passportDateOfIssue', t('Passport date of issue') || 'Pasport berlen senesi') - req('passportGivenBy', t('Passport given by') || 'Kim tarapyndan berildi') - req('phone', t('Phone') || 'Telefon') - req('workCompany', t('Work company name') || 'Kärhananyň ady') - req('position', t('Position') || 'Wezipe') - req('salary', t('Salary') || 'Zähmet haky') - req('workStartedAt', t('Work started at') || 'Işe başlan wagty') - - req('loanAmount', t('Loan amount') || 'Karz möçberi') - req('cardNumber', t('Card number') || 'Kart belgisi') - req('cardName', t('Card name') || 'Kartdaky ady') - req('cardExpMonth', t('Card exp month') || 'Kart Möhleti (aý)') - req('cardExpYear', t('Card exp year') || 'Kart Möhleti (ýyl)') - - req('guarantor1Name', t('Guarantor name') || 'Zamunyň ady') - req('guarantor1Surname', t('Guarantor surname') || 'Zamunyň familiýasy') - req('guarantor1PassportSerie', t('Guarantor passport serie') || 'Pasport seriýasy (Zamun)') - req('guarantor1PassportNumber', t('Guarantor passport number') || 'Pasport belgisi (Zamun)') - req('guarantor1CardNumber',t('Guarantor card number') || 'Kart belgisi (Zamun)') - req('guarantor1CardName', t('Guarantor card name') || 'Kartdaky ady (Zamun)') - req('guarantor1CardExpMonth', t('Guarantor card exp month') || 'Möhleti (aý) (Zamun)') - req('guarantor1CardExpYear', t('Guarantor card exp year') || 'Möhleti (ýyl) (Zamun)') - req('guarantor1Salary', t('Guarantor salary') || 'Ortaca zähmet haky (Zamun)') - - if (form.phone && form.phone.replace(/\D/g, '').length < 8) { - errors.phone = 'Telefon belgisi nädogry' + if (mode === "create") { + if (!form.passportPage1) allErrors.passportPage1 = "Pasport (sahypa 1) hökmany"; + if (!form.passportPage23) allErrors.passportPage23 = "Pasport (sahypa 2-3) hökmany"; } - // File'lar diňe create modunda hökmany - if (mode === 'create') { - if (!form.passportPage1) errors.passportPage1 = 'Pasport (sahypa 1) hökmany' - if (!form.passportPage23) errors.passportPage23 = 'Pasport (sahypa 2-3) hökmany' + // If stepIndex provided, filter to only that step's fields + if (stepIndex !== undefined) { + const stepKeys = STEP_FIELDS[stepIndex]; + const stepErrors: FormErrors = {}; + for (const key of stepKeys) { + if (allErrors[key]) stepErrors[key] = allErrors[key]; + } + return stepErrors; } - return errors + return allErrors; } // ─── Props ──────────────────────────────────────────────────────────────────── interface LoanOrderMobileFormProps { - mode: 'create' | 'edit' - initialData?: LoanOrderMobile - loanOrderId?: string + mode: "create" | "edit"; + initialData?: LoanOrderMobile; + loanOrderId?: string; } // ─── Component ──────────────────────────────────────────────────────────────── -export function LoanOrderMobileForm({ mode, initialData, loanOrderId }: LoanOrderMobileFormProps) { - const { t } = useTranslation() - const navigate = useNavigate() +export function LoanOrderMobileForm({ + mode, + initialData, + loanOrderId, +}: LoanOrderMobileFormProps) { + const { t } = useTranslation(); + const navigate = useNavigate(); - const createMutation = useCreateLoanOrderMobile() - const updateMutation = useUpdateLoanOrderMobile() - - const isPending = createMutation.isPending || updateMutation.isPending + const createMutation = useCreateLoanOrderMobile(); + const updateMutation = useUpdateLoanOrderMobile(); + const isPending = createMutation.isPending || updateMutation.isPending; const [form, setForm] = useState(() => - initialData ? mapToFormState(initialData) : INITIAL_STATE - ) - const [errors, setErrors] = useState({}) - const [submitted, setSubmitted] = useState(false) + initialData ? mapToFormState(initialData) : INITIAL_STATE, + ); + const [errors, setErrors] = useState({}); + // Track which steps have been validated (done or error) + const [stepStatuses, setStepStatuses] = useState< + Array<"idle" | "active" | "done" | "error"> + >(["active", "idle", "idle", "idle", "idle"]); + const [currentStep, setCurrentStep] = useState(0); - const set = useCallback( - (key: K, value: FormState[K]) => { - setForm((prev) => ({ ...prev, [key]: value })) - if (submitted) { - setErrors((prev) => ({ ...prev, [key]: undefined })) - } + const set = useCallback((key: K, value: FormState[K]) => { + setForm((prev) => ({ ...prev, [key]: value })); + setErrors((prev) => ({ ...prev, [key]: undefined })); + }, []); + + // Build step items for StepBarCards + const STEP_DEFS = [ + { + id: "loan", + title: t("Loan") || "Karz", + subtitle: t("Type & amount") || "Görnüş & möçber", + icon: FileText, }, - [submitted] - ) + { + id: "personal", + title: t("Personal") || "Şahsy", + subtitle: t("Identity & passport") || "Şahsyýet & pasport", + icon: User, + }, + { + id: "contact", + title: t("Contact & Job") || "Habarlaşmak & Iş", + subtitle: t("Phone & employment") || "Telefon & iş", + icon: Phone, + }, + { + id: "card", + title: t("Card & Guarantor") || "Kart & Zamun", + subtitle: t("Payment & guarantor") || "Töleg & zamun", + icon: CreditCard, + }, + { + id: "files", + title: t("Files & Status") || "Faýllar & Status", + subtitle: t("Documents & review") || "Resminamalar", + icon: Upload, + }, + ]; + + const stepItems: StepCardItem[] = STEP_DEFS.map((def, i) => ({ + ...def, + status: stepStatuses[i], + })); + + const updateStepStatus = ( + index: number, + status: "idle" | "active" | "done" | "error", + ) => { + setStepStatuses((prev) => { + const next = [...prev]; + next[index] = status; + return next; + }); + }; + + const goToStep = (index: number) => { + updateStepStatus(currentStep, stepStatuses[currentStep] === "error" ? "error" : "done"); + updateStepStatus(index, "active"); + setCurrentStep(index); + window.scrollTo({ top: 0, behavior: "smooth" }); + }; + + const handleNext = () => { + const stepErrors = validate(form, t, mode, currentStep); + if (Object.keys(stepErrors).length > 0) { + setErrors((prev) => ({ ...prev, ...stepErrors })); + updateStepStatus(currentStep, "error"); + toast.error(t("Write a correct data please") || "Dogry maglumat girizmegiňizi haýyş edýäris."); + const firstKey = Object.keys(stepErrors)[0]; + document.getElementById(`field-${firstKey}`)?.scrollIntoView({ behavior: "smooth", block: "center" }); + return; + } + updateStepStatus(currentStep, "done"); + const next = currentStep + 1; + updateStepStatus(next, "active"); + setCurrentStep(next); + window.scrollTo({ top: 0, behavior: "smooth" }); + }; + + const handlePrev = () => { + const prev = currentStep - 1; + updateStepStatus(currentStep, stepStatuses[currentStep] === "error" ? "error" : "idle"); + updateStepStatus(prev, "active"); + setCurrentStep(prev); + window.scrollTo({ top: 0, behavior: "smooth" }); + }; const handleSubmit = () => { - setSubmitted(true) - const errs = validate(form, t, mode) - if (Object.keys(errs).length > 0) { - setErrors(errs) - toast.error(t('Write a correct data please') || 'Dogry maglumat girizmegiňizi haýyş edýäris.') - const firstKey = Object.keys(errs)[0] - document.getElementById(`field-${firstKey}`)?.scrollIntoView({ behavior: 'smooth', block: 'center' }) - return + // Full validation across all steps + const allErrors = validate(form, t, mode); + if (Object.keys(allErrors).length > 0) { + setErrors(allErrors); + // Mark steps with errors + const newStatuses = stepStatuses.map((s, i) => { + const stepKeys = STEP_FIELDS[i]; + const hasError = stepKeys.some((k) => allErrors[k]); + if (i === currentStep) return hasError ? "error" : "active"; + if (hasError) return "error"; + return s === "idle" ? "idle" : "done"; + }) as typeof stepStatuses; + setStepStatuses(newStatuses); + toast.error(t("Write a correct data please") || "Dogry maglumat girizmegiňizi haýyş edýäris."); + return; } const payload: LoanOrderMobilePayload = { - status: form.status, - loanType: form.loanType, - region: form.region, - branch: form.branch, - firstName: form.firstName, - lastName: form.lastName, - patronicName: form.patronicName || undefined, - education: form.education, - marriageStatus: form.marriageStatus, - dateOfBirth: form.dateOfBirth, - residence: form.residence, - currentResidence: form.currentResidence || undefined, - passportSerie: form.passportSerie, - passportNumber: form.passportNumber, + status: form.status, + loanType: form.loanType, + region: form.region, + branch: form.branch, + firstName: form.firstName, + lastName: form.lastName, + patronicName: form.patronicName || undefined, + education: form.education, + marriageStatus: form.marriageStatus, + dateOfBirth: form.dateOfBirth, + residence: form.residence, + currentResidence: form.currentResidence || undefined, + passportSerie: form.passportSerie, + passportNumber: form.passportNumber, passportDateOfIssue: form.passportDateOfIssue, - passportGivenBy: form.passportGivenBy, - bornPlace: form.bornPlace || undefined, - email: form.email || undefined, - phone: form.phone, - phoneAdditional: form.phoneAdditional || undefined, - homePhone: form.homePhone || undefined, - workCompany: form.workCompany, - workHrPhone: form.workHrPhone || undefined, - workRegion: form.workRegion || undefined, - workProvince: form.workProvince || undefined, - position: form.position, - salary: Number(form.salary), - workStartedAt: form.workStartedAt, - note: form.note || undefined, - loanAmount: Number(form.loanAmount) || undefined, - loanHistory: form.loanHistory || undefined, - cardNumber: form.cardNumber || undefined, - cardName: form.cardName || undefined, - cardExpMonth: form.cardExpMonth || undefined, - cardExpYear: form.cardExpYear || undefined, - guarantor1Name: form.guarantor1Name || undefined, - guarantor1Surname: form.guarantor1Surname || undefined, - guarantor1Patronic: form.guarantor1Patronic || undefined, - guarantor1PassportSerie: form.guarantor1PassportSerie || undefined, + passportGivenBy: form.passportGivenBy, + bornPlace: form.bornPlace || undefined, + email: form.email || undefined, + phone: form.phone, + phoneAdditional: form.phoneAdditional || undefined, + homePhone: form.homePhone || undefined, + workCompany: form.workCompany, + workHrPhone: form.workHrPhone || undefined, + workRegion: form.workRegion || undefined, + workProvince: form.workProvince || undefined, + position: form.position, + salary: Number(form.salary), + workStartedAt: form.workStartedAt, + note: form.note || undefined, + loanAmount: Number(form.loanAmount) || undefined, + loanHistory: form.loanHistory || undefined, + cardNumber: form.cardNumber || undefined, + cardName: form.cardName || undefined, + cardExpMonth: form.cardExpMonth || undefined, + cardExpYear: form.cardExpYear || undefined, + guarantor1Name: form.guarantor1Name || undefined, + guarantor1Surname: form.guarantor1Surname || undefined, + guarantor1Patronic: form.guarantor1Patronic || undefined, + guarantor1PassportSerie: form.guarantor1PassportSerie || undefined, guarantor1PassportNumber: form.guarantor1PassportNumber || undefined, - guarantor1CardNumber: form.guarantor1CardNumber || undefined, - guarantor1CardName: form.guarantor1CardName || undefined, - guarantor1CardExpMonth: form.guarantor1CardExpMonth || undefined, - guarantor1CardExpYear: form.guarantor1CardExpYear || undefined, - guarantor1Salary: Number(form.guarantor1Salary) || undefined, - } + guarantor1CardNumber: form.guarantor1CardNumber || undefined, + guarantor1CardName: form.guarantor1CardName || undefined, + guarantor1CardExpMonth: form.guarantor1CardExpMonth || undefined, + guarantor1CardExpYear: form.guarantor1CardExpYear || undefined, + guarantor1Salary: Number(form.guarantor1Salary) || undefined, + }; - if (mode === 'create') { + if (mode === "create") { createMutation.mutate(payload, { - onSuccess: () => navigate('/loan-order-mobiles'), - }) + onSuccess: () => navigate("/loan-order-mobiles"), + }); } else { updateMutation.mutate( { id: loanOrderId!, payload }, - { onSuccess: () => navigate('/loan-order-mobiles') } - ) + { onSuccess: () => navigate("/loan-order-mobiles") }, + ); } - } + }; + + const isLastStep = currentStep === STEP_DEFS.length - 1; + const isFirstStep = currentStep === 0; // ── Render ────────────────────────────────────────────────────────────────── return ( @@ -436,729 +592,763 @@ export function LoanOrderMobileForm({ mode, initialData, loanOrderId }: LoanOrde {/* Page title */}

- {mode === 'create' - ? (t('Loan order create') || 'Karz sargyt döredüň') - : (t('Loan order edit') || 'Karz sargydy üýtget')} + {mode === "create" + ? t("Loan order create") || "Karz sargyt döredüň" + : t("Loan order edit") || "Karz sargydy üýtget"}

- {/* ── Status ─────────────────────────────────────────────────────────── */} -
-
-
- set('status', v)} - options={STATUS_OPTIONS} - error={errors.status} - placeholder="Saýlaň" - /> -
-
- set('note', v)} - placeholder={t('Note') || 'Bellik'} - /> -
-
-
- - {/* ── Loan Type ──────────────────────────────────────────────────────── */} -
-
-
- set('loanType', v)} - options={LOAN_TYPE_OPTIONS} - placeholder="Saýlamak üçin basyň" - error={errors.loanType} - /> -
-
- set('loanAmount', v)} - placeholder="Karz möçberi" - error={errors.loanAmount} - /> -
-
-
- - {/* ── Location ───────────────────────────────────────────────────────── */} -
-
-
- set('region', v)} - options={REGION_OPTIONS} - placeholder="Saýlamak üçin basyň" - error={errors.region} - /> -
-
- set('branch', v)} - options={[]} - placeholder="Saýlamak üçin basyň" - error={errors.branch} - /> -
-
-
- - {/* ── Personal Data ──────────────────────────────────────────────────── */} -
-
-
-
- set('firstName', v)} - placeholder={t('Name') || 'Ady'} - error={errors.firstName} - /> -
-
- set('lastName', v)} - placeholder={t('Surname') || 'Familiýasy'} - error={errors.lastName} - /> -
-
- set('patronicName', v)} - placeholder={t('Patronic name') || 'Atasynyň ady'} - /> -
-
- -
-
- set('education', v)} - options={EDUCATION_OPTIONS} - placeholder="Saýlaň" - error={errors.education} - /> -
-
- set('marriageStatus', v)} - options={MARRIAGE_OPTIONS} - placeholder="Saýlaň" - error={errors.marriageStatus} - /> -
-
- set('dateOfBirth', v)} - error={errors.dateOfBirth} - /> -
-
- -
-
- set('residence', v)} - placeholder={t('Residence (passport)') || 'Ýazgy edilen salgyňyz'} - error={errors.residence} - /> -
-
- set('currentResidence', v)} - placeholder={t('Current Residence') || 'Häzirki ýaşaýyş ýeri'} - /> -
-
- -
- set('loanHistory', v)} - options={[]} - placeholder="Saýlamak üçin basyň" - /> -
-
-
- - {/* ── Card ───────────────────────────────────────────────────────────── */} -
-
-
- set('cardNumber', v)} - placeholder="Kart belgisi" - error={errors.cardNumber} - /> -
-
- set('cardName', v)} - placeholder="Kartdaky ady" - error={errors.cardName} - /> -
-
- set('cardExpMonth', v)} - options={Array.from({ length: 12 }, (_, i) => ({ value: String(i + 1).padStart(2, '0'), label: String(i + 1).padStart(2, '0') }))} - placeholder="Saýlamak üçin basyň" - error={errors.cardExpMonth} - /> -
-
- set('cardExpYear', v)} - options={Array.from({ length: 15 }, (_, i) => ({ value: String(new Date().getFullYear() + i), label: String(new Date().getFullYear() + i) }))} - placeholder="Saýlamak üçin basyň" - error={errors.cardExpYear} - /> -
-
-
- - {/* ── Passport ───────────────────────────────────────────────────────── */} -
-
-
-
- set('passportSerie', v)} - options={PASSPORT_SERIES_OPTIONS} - placeholder="Saýlamak üçin basyň" - error={errors.passportSerie} - /> -
-
- set('passportNumber', v)} - placeholder={t('Passport number') || 'Pasport belgisi'} - error={errors.passportNumber} - /> -
-
- set('passportDateOfIssue', v)} - error={errors.passportDateOfIssue} - /> -
-
- -
-
- set('passportGivenBy', v)} - placeholder={t('Passport given by') || 'Kim tarapyndan berildi'} - error={errors.passportGivenBy} - /> -
-
- set('bornPlace', v)} - placeholder={t('Born place (passport)') || 'Doglan ýeri (pasport)'} - /> -
-
-
-
- - {/* ── Contact ────────────────────────────────────────────────────────── */} -
-
-
- set('email', v)} - placeholder="E-poçta" - /> -
-
- set('phone', v)} - placeholder="61 097 651" - error={errors.phone} - /> -
-
- set('phoneAdditional', v)} - placeholder="61 097 651" - /> -
-
- set('homePhone', v)} - placeholder="61 097 651" - /> -
-
-
- - {/* ── Job ────────────────────────────────────────────────────────────── */} -
-
-
-
- set('workCompany', v)} - placeholder={t('Work company name') || 'Işleýän edaranyň/kärhananyň ady'} - error={errors.workCompany} - /> -
-
- set('workHrPhone', v)} - placeholder="61 097 651" - /> -
-
- -
-
- set('workRegion', v)} - options={REGION_OPTIONS} - placeholder="Saýlamak üçin basyň" - /> -
-
- set('workProvince', v)} - options={[]} - placeholder="Saýlamak üçin basyň" - /> -
-
- -
-
- set('position', v)} - placeholder={t('Position') || 'Wezipe'} - error={errors.position} - /> -
-
- set('salary', v)} - placeholder={t('Salary') || 'Zähmet haky'} - error={errors.salary} - /> -
-
- set('workStartedAt', v)} - error={errors.workStartedAt} - /> -
-
-
-
- - {/* ── Passport Files ─────────────────────────────────────────────────── */} -
- {/* Edit modunda mevcut resimleri göster */} - {mode === 'edit' && initialData && ( -
- {initialData.passportPage1Url && ( -
- - {t('Passport (page 1)') || 'Pasport (sahypa 1)'} — {t('current') || 'häzirki'} - - - {t('View file') || 'Faýly gör'} - -
- )} - {initialData.passportPage23Url && ( -
- - {t('Passport (page 2-3)') || 'Pasport (2-3-nji sahypa)'} — {t('current') || 'häzirki'} - - - {t('View file') || 'Faýly gör'} - -
- )} - {initialData.passportPage89Url && ( -
- - {t('Passport (page 8-9)') || 'Pasport (8-9 sahypa)'} — {t('current') || 'häzirki'} - - - {t('View file') || 'Faýly gör'} - -
- )} - {initialData.passportPage32Url && ( -
- - {t('Passport (page 32)') || 'Pasport (32-nji sahypa)'} — {t('current') || 'häzirki'} - - - {t('View file') || 'Faýly gör'} - -
- )} -
- )} - -
-
- set('passportPage1', f)} - placeholder="Faýl saýlaň ýa-da salmak üçin basyň" - error={errors.passportPage1} - /> -
-
- set('passportPage23', f)} - placeholder="Faýl saýlaň ýa-da salmak üçin basyň" - error={errors.passportPage23} - /> -
-
- set('passportPage89', f)} - placeholder="Faýl saýlaň ýa-da salmak üçin basyň" - /> -
-
- set('passportPage32', f)} - placeholder="Faýl saýlaň ýa-da salmak üçin basyň" - /> -
-
-
- - {/* ── Zamun ──────────────────────────────────────────────────────────── */} -
-
-
-
- set('guarantor1Name', v)} - placeholder="Zamunyň ady" - error={errors.guarantor1Name} - /> -
-
- set('guarantor1Surname', v)} - placeholder="Zamunyň familiýasy" - error={errors.guarantor1Surname} - /> -
-
- set('guarantor1Patronic', v)} - placeholder="Zamunyň atasynyň ady" - /> -
-
- -
-
- set('guarantor1PassportSerie', v)} - options={PASSPORT_SERIES_OPTIONS} - placeholder="Saýlamak üçin basyň" - error={errors.guarantor1PassportSerie} - /> -
-
- set('guarantor1PassportNumber', v)} - placeholder="Pasport belgisi" - error={errors.guarantor1PassportNumber} - /> -
-
- -
-
- set('guarantor1CardNumber', v)} - placeholder="Kart belgisi" - error={errors.guarantor1CardNumber} - /> -
-
- set('guarantor1CardName', v)} - placeholder="Kartdaky ady" - error={errors.guarantor1CardName} - /> -
-
- set('guarantor1CardExpMonth', v)} - options={Array.from({ length: 12 }, (_, i) => ({ value: String(i + 1).padStart(2, '0'), label: String(i + 1).padStart(2, '0') }))} - placeholder="Saýlamak üçin basyň" - error={errors.guarantor1CardExpMonth} - /> -
-
- set('guarantor1CardExpYear', v)} - options={Array.from({ length: 15 }, (_, i) => ({ value: String(new Date().getFullYear() + i), label: String(new Date().getFullYear() + i) }))} - placeholder="Saýlamak üçin basyň" - error={errors.guarantor1CardExpYear} - /> -
-
- -
-
- set('guarantor1Salary', v)} - placeholder="Ortaca zähmet haky" - error={errors.guarantor1Salary} - /> -
-
-
-
- - {/* ── Footer Actions ─────────────────────────────────────────────────── */} -
- - + {/* ── Step Bar ───────────────────────────────────────────────────────── */} +
+
+ + {/* ── Step 0: Karz & Lokasiýa ────────────────────────────────────────── */} + {currentStep === 0 && ( + <> +
+
+
+ set("loanType", v)} + options={LOAN_TYPE_OPTIONS} + placeholder="Saýlamak üçin basyň" + error={errors.loanType} + /> +
+
+ set("loanAmount", v)} + placeholder="Karz möçberi" + error={errors.loanAmount} + /> +
+
+
+ +
+
+
+ set("region", v)} + options={REGION_OPTIONS} + placeholder="Saýlamak üçin basyň" + error={errors.region} + /> +
+
+ set("branch", v)} + options={[]} + placeholder="Saýlamak üçin basyň" + error={errors.branch} + /> +
+
+
+ + )} + + {/* ── Step 1: Şahsy maglumatlar & Pasport ───────────────────────────── */} + {currentStep === 1 && ( + <> +
+
+
+
+ set("firstName", v)} + placeholder={t("Name") || "Ady"} + error={errors.firstName} + /> +
+
+ set("lastName", v)} + placeholder={t("Surname") || "Familiýasy"} + error={errors.lastName} + /> +
+
+ set("patronicName", v)} + placeholder={t("Patronic name") || "Atasynyň ady"} + /> +
+
+ +
+
+ set("education", v)} + options={EDUCATION_OPTIONS} + placeholder="Saýlaň" + error={errors.education} + /> +
+
+ set("marriageStatus", v)} + options={MARRIAGE_OPTIONS} + placeholder="Saýlaň" + error={errors.marriageStatus} + /> +
+
+ set("dateOfBirth", v)} + error={errors.dateOfBirth} + /> +
+
+ +
+
+ set("residence", v)} + placeholder={t("Residence (passport)") || "Ýazgy edilen salgyňyz"} + error={errors.residence} + /> +
+
+ set("currentResidence", v)} + placeholder={t("Current Residence") || "Häzirki ýaşaýyş ýeri"} + /> +
+
+ +
+ set("loanHistory", v)} + options={[]} + placeholder="Saýlamak üçin basyň" + /> +
+
+
+ +
+
+
+
+ set("passportSerie", v)} + options={PASSPORT_SERIES_OPTIONS} + placeholder="Saýlamak üçin basyň" + error={errors.passportSerie} + /> +
+
+ set("passportNumber", v)} + placeholder={t("Passport number") || "Pasport belgisi"} + error={errors.passportNumber} + /> +
+
+ set("passportDateOfIssue", v)} + error={errors.passportDateOfIssue} + /> +
+
+ +
+
+ set("passportGivenBy", v)} + placeholder={t("Passport given by") || "Kim tarapyndan berildi"} + error={errors.passportGivenBy} + /> +
+
+ set("bornPlace", v)} + placeholder={t("Born place (passport)") || "Doglan ýeri (pasport)"} + /> +
+
+
+
+ + )} + + {/* ── Step 2: Habarlaşmak & Iş ──────────────────────────────────────── */} + {currentStep === 2 && ( + <> +
+
+
+ set("email", v)} + placeholder="E-poçta" + /> +
+
+ set("phone", v)} + placeholder="61 097 651" + error={errors.phone} + /> +
+
+ set("phoneAdditional", v)} + placeholder="61 097 651" + /> +
+
+ set("homePhone", v)} + placeholder="61 097 651" + /> +
+
+
+ +
+
+
+
+ set("workCompany", v)} + placeholder={t("Work company name") || "Işleýän edaranyň/kärhananyň ady"} + error={errors.workCompany} + /> +
+
+ set("workHrPhone", v)} + placeholder="61 097 651" + /> +
+
+ +
+
+ set("workRegion", v)} + options={REGION_OPTIONS} + placeholder="Saýlamak üçin basyň" + /> +
+
+ set("workProvince", v)} + options={[]} + placeholder="Saýlamak üçin basyň" + /> +
+
+ +
+
+ set("position", v)} + placeholder={t("Position") || "Wezipe"} + error={errors.position} + /> +
+
+ set("salary", v)} + placeholder={t("Salary") || "Zähmet haky"} + error={errors.salary} + /> +
+
+ set("workStartedAt", v)} + error={errors.workStartedAt} + /> +
+
+
+
+ + )} + + {/* ── Step 3: Kart & Zamun ──────────────────────────────────────────── */} + {currentStep === 3 && ( + <> +
+
+
+ set("cardNumber", v)} + placeholder="Kart belgisi" + error={errors.cardNumber} + /> +
+
+ set("cardName", v)} + placeholder="Kartdaky ady" + error={errors.cardName} + /> +
+
+ set("cardExpMonth", v)} + options={Array.from({ length: 12 }, (_, i) => ({ + value: String(i + 1).padStart(2, "0"), + label: String(i + 1).padStart(2, "0"), + }))} + placeholder="Saýlamak üçin basyň" + error={errors.cardExpMonth} + /> +
+
+ set("cardExpYear", v)} + options={Array.from({ length: 15 }, (_, i) => ({ + value: String(new Date().getFullYear() + i), + label: String(new Date().getFullYear() + i), + }))} + placeholder="Saýlamak üçin basyň" + error={errors.cardExpYear} + /> +
+
+
+ +
+
+
+
+ set("guarantor1Name", v)} + placeholder="Zamunyň ady" + error={errors.guarantor1Name} + /> +
+
+ set("guarantor1Surname", v)} + placeholder="Zamunyň familiýasy" + error={errors.guarantor1Surname} + /> +
+
+ set("guarantor1Patronic", v)} + placeholder="Zamunyň atasynyň ady" + /> +
+
+ +
+
+ set("guarantor1PassportSerie", v)} + options={PASSPORT_SERIES_OPTIONS} + placeholder="Saýlamak üçin basyň" + error={errors.guarantor1PassportSerie} + /> +
+
+ set("guarantor1PassportNumber", v)} + placeholder="Pasport belgisi" + error={errors.guarantor1PassportNumber} + /> +
+
+ +
+
+ set("guarantor1CardNumber", v)} + placeholder="Kart belgisi" + error={errors.guarantor1CardNumber} + /> +
+
+ set("guarantor1CardName", v)} + placeholder="Kartdaky ady" + error={errors.guarantor1CardName} + /> +
+
+ set("guarantor1CardExpMonth", v)} + options={Array.from({ length: 12 }, (_, i) => ({ + value: String(i + 1).padStart(2, "0"), + label: String(i + 1).padStart(2, "0"), + }))} + placeholder="Saýlamak üçin basyň" + error={errors.guarantor1CardExpMonth} + /> +
+
+ set("guarantor1CardExpYear", v)} + options={Array.from({ length: 15 }, (_, i) => ({ + value: String(new Date().getFullYear() + i), + label: String(new Date().getFullYear() + i), + }))} + placeholder="Saýlamak üçin basyň" + error={errors.guarantor1CardExpYear} + /> +
+
+ +
+
+ set("guarantor1Salary", v)} + placeholder="Ortaca zähmet haky" + error={errors.guarantor1Salary} + /> +
+
+
+
+ + )} + + {/* ── Step 4: Faýllar & Status ──────────────────────────────────────── */} + {currentStep === 4 && ( + <> +
+
+
+ set("status", v)} + options={STATUS_OPTIONS} + error={errors.status} + placeholder="Saýlaň" + /> +
+
+ set("note", v)} + placeholder={t("Note") || "Bellik"} + /> +
+
+
+ +
+ {/* Edit modunda mevcut dosyaları göster */} + {mode === "edit" && initialData && ( +
+ {initialData.passportPage1Url && ( +
+ + {t("Passport (page 1)") || "Pasport (sahypa 1)"} —{" "} + {t("current") || "häzirki"} + + + {t("View file") || "Faýly gör"} + +
+ )} + {initialData.passportPage23Url && ( +
+ + {t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)"} —{" "} + {t("current") || "häzirki"} + + + {t("View file") || "Faýly gör"} + +
+ )} + {initialData.passportPage89Url && ( +
+ + {t("Passport (page 8-9)") || "Pasport (8-9 sahypa)"} —{" "} + {t("current") || "häzirki"} + + + {t("View file") || "Faýly gör"} + +
+ )} + {initialData.passportPage32Url && ( +
+ + {t("Passport (page 32)") || "Pasport (32-nji sahypa)"} —{" "} + {t("current") || "häzirki"} + + + {t("View file") || "Faýly gör"} + +
+ )} +
+ )} + +
+
+ set("passportPage1", f)} + placeholder="Faýl saýlaň ýa-da salmak üçin basyň" + error={errors.passportPage1} + /> +
+
+ set("passportPage23", f)} + placeholder="Faýl saýlaň ýa-da salmak üçin basyň" + error={errors.passportPage23} + /> +
+
+ set("passportPage89", f)} + placeholder="Faýl saýlaň ýa-da salmak üçin basyň" + /> +
+
+ set("passportPage32", f)} + placeholder="Faýl saýlaň ýa-da salmak üçin basyň" + /> +
+
+
+ + )} + + {/* ── Form Actions ───────────────────────────────────────────────────── */} + navigate(-1)} + cancelLabel={t("Cancel") || "Ýatyr"} + loadingLabel={t("Loading") || "Ýüklenilýär..."} + // Prev button: visible from step 1 onward + onPrev={!isFirstStep ? handlePrev : undefined} + prevLabel={t("common.prev") || "Yza"} + // Next button: visible on all steps except the last + onNext={!isLastStep ? handleNext : undefined} + nextLabel={t("common.next") || "Indiki"} + // Submit button: only on the last step + showSubmit={isLastStep} + onSubmit={handleSubmit} + submitLabel={ + mode === "create" + ? t("loanOrderMobiles.createButton") || "Karz sargyt döredüň" + : t("loanOrders.saveButton") || "Ýatda sakla" + } + />
- ) + ); } \ No newline at end of file diff --git a/src/features/loanOrders/components/loanOrderForm.tsx b/src/features/loanOrders/components/loanOrderForm.tsx index 19e302b..0676b37 100644 --- a/src/features/loanOrders/components/loanOrderForm.tsx +++ b/src/features/loanOrders/components/loanOrderForm.tsx @@ -2,17 +2,18 @@ import { useState, useCallback, useMemo } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' import { toast } from 'sonner' -import { ChevronLeft, ChevronRight, Loader2 } from 'lucide-react' -import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' -import { useCreateLoanOrder, useUpdateLoanOrder } from '@/features/loanOrders/hooks/useLoanOrders' -import type { LoanOrder, LoanOrderPayload } from '@/features/loanOrders/api/loanOrdersApi' -import { StepBarCards, type StepCardItem } from '@/components/stepBarV2' import { CircleDot, CreditCard, MapPin, User, Wallet, - FileText, Phone, Briefcase, FolderOpen, ShieldCheck + FileText, Phone, Briefcase, FolderOpen, ShieldCheck, } 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 { useCreateLoanOrder, useUpdateLoanOrder } from '@/features/loanOrders/hooks/useLoanOrders' +import type { LoanOrder, LoanOrderPayload } from '@/features/loanOrders/api/loanOrdersApi' + // ─── Static options ─────────────────────────────────────────────────────────── const REGION_OPTIONS = [ @@ -36,11 +37,11 @@ const EDUCATION_OPTIONS = [ ] const MARRIAGE_OPTIONS = [ - { value: 'MARRIED', label: 'Öýlenen / Durmuşa çykan' }, - { value: 'SINGLE', label: 'Öýlenmedik / Durmuşa çykmadyk' }, - { value: 'DIVORCED', label: 'Aýrylşan' }, - { value: 'WIDOW', label: 'Adamsy ýa-da aýaly aradan çykan' }, - { value: 'LEGAL', label: 'Raýat nika' }, + { value: 'MARRIED', label: 'Öýlenen / Durmuşa çykan' }, + { value: 'SINGLE', label: 'Öýlenmedik / Durmuşa çykmadyk' }, + { value: 'DIVORCED', label: 'Aýrylşan' }, + { value: 'WIDOW', label: 'Adamsy ýa-da aýaly aradan çykan' }, + { value: 'LEGAL', label: 'Raýat nika' }, ] const STATUS_OPTIONS = [ @@ -73,7 +74,7 @@ const YEAR_OPTIONS = Array.from({ length: 15 }, (_, i) => ({ label: String(new Date().getFullYear() + i), })) -// ─── Form State ─────────────────────────────────────────────────────────────── +// ─── FormState ──────────────────────────────────────────────────────────────── interface FormState { status: string @@ -130,55 +131,20 @@ interface FormState { type FormErrors = Partial> const INITIAL_STATE: FormState = { - status: 'GARAŞYLÝAR', - loanType: '', - region: 'Aşgabat', - branch: '', - firstName: '', - lastName: '', - patronicName: '', - education: '', - marriageStatus: '', - dateOfBirth: '', - residence: '', - currentResidence: '', - passportSerie: '', - passportNumber: '', - passportDateOfIssue: '', - passportGivenBy: '', - bornPlace: '', - email: '', - phone: '', - phoneAdditional: '', - homePhone: '', - workCompany: '', - workHrPhone: '', - workRegion: 'Aşgabat', - workProvince: '', - position: '', - salary: '', - workStartedAt: '', - passportPage1: null, - passportPage23: null, - passportPage89: null, - passportPage32: null, - note: '', - loanAmount: '', - loanHistory: '', - cardNumber: '', - cardName: '', - cardExpMonth: '', - cardExpYear: '', - guarantor1Name: '', - guarantor1Surname: '', - guarantor1Patronic: '', - guarantor1PassportSerie: '', - guarantor1PassportNumber: '', - guarantor1CardNumber: '', - guarantor1CardName: '', - guarantor1CardExpMonth: '', - guarantor1CardExpYear: '', - guarantor1Salary: '', + status: 'GARAŞYLÝAR', loanType: '', region: 'Aşgabat', branch: '', + firstName: '', lastName: '', patronicName: '', education: '', + marriageStatus: '', dateOfBirth: '', residence: '', currentResidence: '', + passportSerie: '', passportNumber: '', passportDateOfIssue: '', + passportGivenBy: '', bornPlace: '', email: '', phone: '', + phoneAdditional: '', homePhone: '', workCompany: '', workHrPhone: '', + workRegion: 'Aşgabat', workProvince: '', position: '', salary: '', + workStartedAt: '', passportPage1: null, passportPage23: null, + passportPage89: null, passportPage32: null, note: '', loanAmount: '', + loanHistory: '', cardNumber: '', cardName: '', cardExpMonth: '', cardExpYear: '', + guarantor1Name: '', guarantor1Surname: '', guarantor1Patronic: '', + guarantor1PassportSerie: '', guarantor1PassportNumber: '', + guarantor1CardNumber: '', guarantor1CardName: '', + guarantor1CardExpMonth: '', guarantor1CardExpYear: '', guarantor1Salary: '', } function mapToFormState(order: LoanOrder): FormState { @@ -211,15 +177,13 @@ function mapToFormState(order: LoanOrder): FormState { position: order.position ?? '', salary: order.salary != null ? String(order.salary) : '', workStartedAt: order.workStartedAt ?? '', - passportPage1: null, - passportPage23: null, - passportPage89: null, - passportPage32: null, - note: order.note ?? '', + passportPage1: null, passportPage23: null, + passportPage89: null, passportPage32: null, + note: order.note ?? '', loanAmount: order.loanAmount != null ? String(order.loanAmount) : '', loanHistory: order.loanHistory ?? '', - cardNumber: order.cardNumber ?? '', - cardName: order.cardName ?? '', + cardNumber: order.cardNumber ?? '', + cardName: order.cardName ?? '', cardExpMonth: order.cardExpMonth ?? '', cardExpYear: order.cardExpYear ?? '', guarantor1Name: order.guarantor1Name ?? '', @@ -241,29 +205,20 @@ interface StepDef { id: string titleKey: string titleFallback: string - shortLabel: string - icon: LucideIcon subtitle: string + icon: LucideIcon validate: (form: FormState, mode: 'create' | 'edit') => FormErrors } -// 3. STEPS dizisini güncelle + const STEPS: StepDef[] = [ { - id: 'status', - titleKey: 'Status', - titleFallback: 'Status', - shortLabel: 'Status', - icon: CircleDot, - subtitle: 'Ýagdaý we bellik', + id: 'status', titleKey: 'Status', titleFallback: 'Status', + subtitle: 'Ýagdaý we bellik', icon: CircleDot, validate: () => ({}), }, { - id: 'loan', - titleKey: 'Loan', - titleFallback: 'Karz', - shortLabel: 'Karz', - icon: Wallet, - subtitle: 'Görnüş we möçber', + id: 'loan', titleKey: 'Loan', titleFallback: 'Karz', + subtitle: 'Görnüş we möçber', icon: Wallet, validate: (form) => { const e: FormErrors = {} if (!form.loanType) e.loanType = 'Karz görnüşi — hökmany' @@ -272,12 +227,8 @@ const STEPS: StepDef[] = [ }, }, { - id: 'location', - titleKey: 'Location', - titleFallback: 'Lokasiýa', - shortLabel: 'Lokasiýa', - icon: MapPin, - subtitle: 'Welaýat we şahamça', + id: 'location', titleKey: 'Location', titleFallback: 'Lokasiýa', + subtitle: 'Welaýat we şahamça', icon: MapPin, validate: (form) => { const e: FormErrors = {} if (!form.region) e.region = 'Welaýat — hökmany' @@ -286,12 +237,8 @@ const STEPS: StepDef[] = [ }, }, { - id: 'personal', - titleKey: 'Personal data', - titleFallback: 'Şahsy maglumatlar', - shortLabel: 'Şahsy', - icon: User, - subtitle: 'At, bilim, maşgala', + id: 'personal', titleKey: 'Personal data', titleFallback: 'Şahsy maglumatlar', + subtitle: 'At, bilim, maşgala', icon: User, validate: (form) => { const e: FormErrors = {} if (!form.firstName) e.firstName = 'Ady — hökmany' @@ -304,12 +251,8 @@ const STEPS: StepDef[] = [ }, }, { - id: 'card', - titleKey: 'Card (Salary)', - titleFallback: 'Kart (Zähmet haky)', - shortLabel: 'Kart', - icon: CreditCard, - subtitle: 'Zähmet haky karty', + id: 'card', titleKey: 'Card (Salary)', titleFallback: 'Kart (Zähmet haky)', + subtitle: 'Zähmet haky karty', icon: CreditCard, validate: (form) => { const e: FormErrors = {} if (!form.cardNumber) e.cardNumber = 'Kart belgisi — hökmany' @@ -320,12 +263,8 @@ const STEPS: StepDef[] = [ }, }, { - id: 'passport', - titleKey: 'Passport', - titleFallback: 'Pasport', - shortLabel: 'Pasport', - icon: FileText, - subtitle: 'Seriýa, belgisi, senesi', + id: 'passport', titleKey: 'Passport', titleFallback: 'Pasport', + subtitle: 'Seriýa, belgisi, senesi', icon: FileText, validate: (form) => { const e: FormErrors = {} if (!form.passportSerie) e.passportSerie = 'Pasport seriýasy — hökmany' @@ -336,12 +275,8 @@ const STEPS: StepDef[] = [ }, }, { - id: 'contact', - titleKey: 'Contact data', - titleFallback: 'Habarlaşmak', - shortLabel: 'Habarlaşmak', - icon: Phone, - subtitle: 'Telefon we e-poçta', + id: 'contact', titleKey: 'Contact data', titleFallback: 'Habarlaşmak', + subtitle: 'Telefon we e-poçta', icon: Phone, validate: (form) => { const e: FormErrors = {} if (!form.phone) { @@ -353,12 +288,8 @@ const STEPS: StepDef[] = [ }, }, { - id: 'job', - titleKey: 'Job', - titleFallback: 'Iş', - shortLabel: 'Iş', - icon: Briefcase, - subtitle: 'Kärhana we wezipe', + id: 'job', titleKey: 'Job', titleFallback: 'Iş', + subtitle: 'Kärhana we wezipe', icon: Briefcase, validate: (form) => { const e: FormErrors = {} if (!form.workCompany) e.workCompany = 'Kärhananyň ady — hökmany' @@ -369,12 +300,8 @@ const STEPS: StepDef[] = [ }, }, { - id: 'files', - titleKey: 'Passport files', - titleFallback: 'Pasport faýllar', - shortLabel: 'Faýllar', - icon: FolderOpen, - subtitle: 'Pasport suratlary', + id: 'files', titleKey: 'Passport files', titleFallback: 'Pasport faýllar', + subtitle: 'Pasport suratlary', icon: FolderOpen, validate: (form, mode) => { const e: FormErrors = {} if (mode === 'create') { @@ -385,12 +312,8 @@ const STEPS: StepDef[] = [ }, }, { - id: 'guarantor', - titleKey: '1. Guarantor', - titleFallback: '1. Zamun', - shortLabel: 'Zamun', - icon: ShieldCheck, - subtitle: 'Zamun maglumatlary', + id: 'guarantor', titleKey: '1. Guarantor', titleFallback: '1. Zamun', + subtitle: 'Zamun maglumatlary', icon: ShieldCheck, validate: (form) => { const e: FormErrors = {} if (!form.guarantor1Name) e.guarantor1Name = 'Zamunyň ady — hökmany' @@ -407,184 +330,408 @@ const STEPS: StepDef[] = [ }, ] -// ─── Step content renderers ─────────────────────────────────────────────────── +// ─── Bento primitives ───────────────────────────────────────────────────────── + +function BentoGrid({ + cols = 2, + children, +}: { + cols?: 1 | 2 | 3 | 4 + children: React.ReactNode +}) { + const colClass = { + 1: 'grid-cols-1', + 2: 'grid-cols-1 sm:grid-cols-2', + 3: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3', + 4: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-4', + }[cols] + return
{children}
+} + +function BentoCard({ + title, + span, + children, +}: { + title?: string + span?: 'full' | 2 | 3 + children: React.ReactNode +}) { + const spanClass = + span === 'full' ? 'sm:col-span-full' : + span === 2 ? 'sm:col-span-2' : + span === 3 ? 'sm:col-span-3' : '' + + return ( +
+ {title && ( +

+ {title} +

+ )} + {children} +
+ ) +} + +// ─── Shared step content props ──────────────────────────────────────────────── + +interface StepContentProps { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void +} + +// ─── Step panels ────────────────────────────────────────────────────────────── function StepStatus({ form, errors, set }: StepContentProps) { return ( -
-
- set('status', v)} options={STATUS_OPTIONS} error={errors.status} placeholder="Saýlaň" /> -
- set('note', v)} placeholder="Bellik" /> -
+ + + set('status', v)} + options={STATUS_OPTIONS} + error={errors.status} + placeholder="Saýlaň" + /> + + + + set('note', v)} + placeholder="Bellik..." + rows={3} + /> + + ) } function StepLoan({ form, errors, set }: StepContentProps) { return ( -
- set('loanType', v)} options={LOAN_TYPE_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.loanType} /> - set('loanAmount', v)} placeholder="Karz möçberi" error={errors.loanAmount} /> -
+ + + set('loanType', v)} + options={LOAN_TYPE_OPTIONS} + placeholder="Saýlamak üçin basyň" + error={errors.loanType} + /> + + + + set('loanAmount', v)} + placeholder="0.00" + error={errors.loanAmount} + /> + + ) } function StepLocation({ form, errors, set }: StepContentProps) { return ( -
- set('region', v)} options={REGION_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.region} /> - set('branch', v)} options={[]} placeholder="Saýlamak üçin basyň" error={errors.branch} /> -
+ + + { set('region', v); set('branch', '') }} + options={REGION_OPTIONS} + placeholder="Saýlamak üçin basyň" + error={errors.region} + /> +

+ Welaýaty saýlasaňyz şahamçalar güncellenar. +

+
+ + + set('branch', v)} + options={[]} + placeholder="Saýlamak üçin basyň" + disabled={!form.region} + error={errors.branch} + /> + +
) } function StepPersonal({ form, errors, set }: StepContentProps) { return ( -
-
- set('firstName', v)} placeholder="Ady" error={errors.firstName} /> - set('lastName', v)} placeholder="Familiýasy" error={errors.lastName} /> - set('patronicName', v)} placeholder="Atasynyň ady" /> -
-
- set('education', v)} options={EDUCATION_OPTIONS} placeholder="Saýlaň" error={errors.education} /> - set('marriageStatus', v)} options={MARRIAGE_OPTIONS} placeholder="Saýlaň" error={errors.marriageStatus} /> - set('dateOfBirth', v)} error={errors.dateOfBirth} /> -
-
- set('residence', v)} placeholder="Ýazgy edilen salgy" error={errors.residence} /> - set('currentResidence', v)} placeholder="Häzirki ýaşaýyş ýeri" /> -
-
- set('loanHistory', v)} options={[]} placeholder="Saýlamak üçin basyň" /> -
+
+ + + set('firstName', v)} placeholder="Ady" error={errors.firstName} /> + + + set('lastName', v)} placeholder="Familiýasy" error={errors.lastName} /> + + + set('patronicName', v)} placeholder="Atasynyň ady" /> + + + + + + set('education', v)} options={EDUCATION_OPTIONS} placeholder="Saýlaň" error={errors.education} /> + + + set('marriageStatus', v)} options={MARRIAGE_OPTIONS} placeholder="Saýlaň" error={errors.marriageStatus} /> + + + set('dateOfBirth', v)} error={errors.dateOfBirth} /> + + + + + + set('residence', v)} placeholder="Ýazgy edilen salgy" error={errors.residence} /> + + + set('currentResidence', v)} placeholder="Häzirki ýaşaýyş ýeri" /> + + + set('loanHistory', v)} options={[]} placeholder="Saýlamak üçin basyň" /> + +
) } function StepCard({ form, errors, set }: StepContentProps) { return ( -
- set('cardNumber', v)} placeholder="Kart belgisi" error={errors.cardNumber} /> - set('cardName', v)} placeholder="Kartdaky ady" error={errors.cardName} /> - set('cardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpMonth} /> - set('cardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpYear} /> -
+ + + set('cardNumber', v)} placeholder="Kart belgisi" error={errors.cardNumber} /> + set('cardName', v)} placeholder="Kartdaky ady" error={errors.cardName} /> + + + + set('cardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpMonth} /> + set('cardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpYear} /> + + ) } function StepPassport({ form, errors, set }: StepContentProps) { return ( -
-
- set('passportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.passportSerie} /> - set('passportNumber', v)} placeholder="Pasport belgisi" error={errors.passportNumber} /> - set('passportDateOfIssue', v)} error={errors.passportDateOfIssue} /> -
-
- set('passportGivenBy', v)} placeholder="Kim tarapyndan berildi" error={errors.passportGivenBy} /> - set('bornPlace', v)} placeholder="Doglan ýeri (pasport)" /> -
+
+ + + set('passportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.passportSerie} /> + + + set('passportNumber', v)} placeholder="Pasport belgisi" error={errors.passportNumber} /> + + + set('passportDateOfIssue', v)} error={errors.passportDateOfIssue} /> + + + + + + set('passportGivenBy', v)} placeholder="Kim tarapyndan berildi" error={errors.passportGivenBy} /> + + + set('bornPlace', v)} placeholder="Doglan ýeri (pasport)" /> + +
) } function StepContact({ form, errors, set }: StepContentProps) { return ( -
- set('email', v)} placeholder="E-poçta" /> - set('phone', v)} placeholder="61 097 651" error={errors.phone} /> - set('phoneAdditional', v)} placeholder="61 097 651" /> - set('homePhone', v)} placeholder="61 097 651" /> -
+ + + set('phone', v)} placeholder="61 097 651" error={errors.phone} /> + set('email', v)} placeholder="E-poçta" /> + + + + set('phoneAdditional', v)} placeholder="61 097 651" /> + set('homePhone', v)} placeholder="61 097 651" /> + + ) } function StepJob({ form, errors, set }: StepContentProps) { return ( -
-
- set('workCompany', v)} placeholder="Kärhananyň ady" error={errors.workCompany} /> - set('workHrPhone', v)} placeholder="61 097 651" /> -
-
- set('workRegion', v)} options={REGION_OPTIONS} placeholder="Saýlamak üçin basyň" /> - set('workProvince', v)} options={[]} placeholder="Saýlamak üçin basyň" /> -
-
- set('position', v)} placeholder="Wezipe" error={errors.position} /> - set('salary', v)} placeholder="Zähmet haky" error={errors.salary} /> - set('workStartedAt', v)} error={errors.workStartedAt} /> -
+
+ + + set('workCompany', v)} placeholder="Kärhananyň ady" error={errors.workCompany} /> + set('workHrPhone', v)} placeholder="61 097 651" /> + + + + set('workRegion', v)} options={REGION_OPTIONS} placeholder="Saýlamak üçin basyň" /> + set('workProvince', v)} options={[]} placeholder="Saýlamak üçin basyň" /> + + + + + + set('position', v)} placeholder="Wezipe" error={errors.position} /> + + + set('salary', v)} placeholder="Zähmet haky" error={errors.salary} /> + + + set('workStartedAt', v)} error={errors.workStartedAt} /> + +
) } -function StepFiles({ form, errors, set, mode, initialData }: StepContentProps & { mode: 'create' | 'edit'; initialData?: LoanOrder }) { +function StepFiles({ + form, errors, set, mode, initialData, +}: StepContentProps & { mode: 'create' | 'edit'; initialData?: LoanOrder }) { + const existingFiles = mode === 'edit' && initialData + ? [ + { url: initialData.passportPage1Url, label: 'Pasport (sahypa 1)' }, + { url: initialData.passportPage23Url, label: 'Pasport (2-3-nji sahypa)' }, + { url: initialData.passportPage89Url, label: 'Pasport (8-9 sahypa)' }, + { url: initialData.passportPage32Url, label: 'Pasport (32-nji sahypa)' }, + ].filter((f): f is { url: string; label: string } => !!f.url) + : [] + return ( -
- {mode === 'edit' && initialData && ( -
- {( - [ - { url: initialData.passportPage1Url, label: 'Pasport (sahypa 1)' }, - { url: initialData.passportPage23Url, label: 'Pasport (2-3-nji sahypa)' }, - { url: initialData.passportPage89Url, label: 'Pasport (8-9 sahypa)' }, - { url: initialData.passportPage32Url, label: 'Pasport (32-nji sahypa)' }, - ] as { url?: string; label: string }[] - ).map(({ url, label }) => - url ? ( -
- {label} — häzirki - Faýly gör -
- ) : null - )} -
+
+ {existingFiles.length > 0 && ( + + {existingFiles.map(({ url, label }) => ( + + + Faýly gör + + + ))} + )} -
- set('passportPage1', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" error={errors.passportPage1} /> - set('passportPage23', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" error={errors.passportPage23} /> - set('passportPage89', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" /> - set('passportPage32', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" /> -
+ + + + set('passportPage1', f)} + error={errors.passportPage1} + /> + + + + set('passportPage23', f)} + error={errors.passportPage23} + /> + + + + set('passportPage89', f)} + /> + + + + set('passportPage32', f)} + /> + +
) } function StepGuarantor({ form, errors, set }: StepContentProps) { return ( -
-
- set('guarantor1Name', v)} placeholder="Zamunyň ady" error={errors.guarantor1Name} /> - set('guarantor1Surname', v)} placeholder="Zamunyň familiýasy" error={errors.guarantor1Surname} /> - set('guarantor1Patronic', v)} placeholder="Zamunyň atasynyň ady" /> -
-
- set('guarantor1PassportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1PassportSerie} /> - set('guarantor1PassportNumber', v)} placeholder="Pasport belgisi" error={errors.guarantor1PassportNumber} /> -
-
- set('guarantor1CardNumber', v)} placeholder="Kart belgisi" error={errors.guarantor1CardNumber} /> - set('guarantor1CardName', v)} placeholder="Kartdaky ady" error={errors.guarantor1CardName} /> - set('guarantor1CardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpMonth} /> - set('guarantor1CardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpYear} /> -
-
- set('guarantor1Salary', v)} placeholder="Ortaca zähmet haky" error={errors.guarantor1Salary} /> -
+
+ + + set('guarantor1Name', v)} placeholder="Zamunyň ady" error={errors.guarantor1Name} /> + + + set('guarantor1Surname', v)} placeholder="Zamunyň familiýasy" error={errors.guarantor1Surname} /> + + + set('guarantor1Patronic', v)} placeholder="Zamunyň atasynyň ady" /> + + + + + + set('guarantor1PassportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1PassportSerie} /> + + + set('guarantor1PassportNumber', v)} placeholder="Pasport belgisi" error={errors.guarantor1PassportNumber} /> + + + + + + set('guarantor1CardNumber', v)} placeholder="Kart belgisi" error={errors.guarantor1CardNumber} /> + set('guarantor1CardName', v)} placeholder="Kartdaky ady" error={errors.guarantor1CardName} /> + + + + set('guarantor1CardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpMonth} /> + set('guarantor1CardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpYear} /> + set('guarantor1Salary', v)} placeholder="Ortaca zähmet haky" error={errors.guarantor1Salary} /> + +
) } -// ─── Shared step content prop type ─────────────────────────────────────────── - -interface StepContentProps { - form: FormState - errors: FormErrors - set: (k: K, v: FormState[K]) => void -} - // ─── Props ──────────────────────────────────────────────────────────────────── interface LoanOrderFormProps { @@ -606,17 +753,10 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP const [form, setForm] = useState(() => initialData ? mapToFormState(initialData) : INITIAL_STATE) const [errors, setErrors] = useState({}) const [currentStep, setCurrentStep] = useState(0) - - /** - * `visited`: steps the user has explicitly moved away from (via Next or direct nav). - * Used to mark steps as "done" or "error" in the step bar. - * In edit mode all steps start visited so errors show immediately on submit. - */ const [visited, setVisited] = useState>( - () => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set() + () => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set(), ) - /** Steps with at least one error (evaluated lazily — only after being visited). */ const stepsWithErrors = useMemo(() => { const out = new Set() visited.forEach((i) => { @@ -671,7 +811,6 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP // ── Submit ────────────────────────────────────────────────────────────────── const handleSubmit = () => { - // Mark all steps visited so error states show in the bar setVisited(new Set(STEPS.map((_, i) => i))) const allErrors: FormErrors = {} @@ -682,8 +821,7 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP toast.error('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 @@ -696,35 +834,35 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP branch: form.branch, firstName: form.firstName, lastName: form.lastName, - patronicName: form.patronicName || undefined, + patronicName: form.patronicName || undefined, education: form.education, marriageStatus: form.marriageStatus, dateOfBirth: form.dateOfBirth, residence: form.residence, - currentResidence: form.currentResidence || undefined, + currentResidence: form.currentResidence || undefined, passportSerie: form.passportSerie, passportNumber: form.passportNumber, passportDateOfIssue: form.passportDateOfIssue, passportGivenBy: form.passportGivenBy, - bornPlace: form.bornPlace || undefined, - email: form.email || undefined, + bornPlace: form.bornPlace || undefined, + email: form.email || undefined, phone: form.phone, - phoneAdditional: form.phoneAdditional || undefined, - homePhone: form.homePhone || undefined, + phoneAdditional: form.phoneAdditional || undefined, + homePhone: form.homePhone || undefined, workCompany: form.workCompany, - workHrPhone: form.workHrPhone || undefined, - workRegion: form.workRegion || undefined, - workProvince: form.workProvince || undefined, + workHrPhone: form.workHrPhone || undefined, + workRegion: form.workRegion || undefined, + workProvince: form.workProvince || undefined, position: form.position, salary: Number(form.salary), workStartedAt: form.workStartedAt, - note: form.note || undefined, - loanAmount: Number(form.loanAmount) || undefined, - loanHistory: form.loanHistory || undefined, - cardNumber: form.cardNumber || undefined, - cardName: form.cardName || undefined, - cardExpMonth: form.cardExpMonth || undefined, - cardExpYear: form.cardExpYear || undefined, + note: form.note || undefined, + loanAmount: Number(form.loanAmount) || undefined, + loanHistory: form.loanHistory || undefined, + cardNumber: form.cardNumber || undefined, + cardName: form.cardName || undefined, + cardExpMonth: form.cardExpMonth || undefined, + cardExpYear: form.cardExpYear || undefined, guarantor1Name: form.guarantor1Name || undefined, guarantor1Surname: form.guarantor1Surname || undefined, guarantor1Patronic: form.guarantor1Patronic || undefined, @@ -740,114 +878,91 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP if (mode === 'create') { createMutation.mutate(payload, { onSuccess: () => navigate('/loan-orders') }) } else { - updateMutation.mutate({ id: loanOrderId!, payload }, { onSuccess: () => navigate('/loan-orders') }) + updateMutation.mutate( + { id: loanOrderId!, payload }, + { onSuccess: () => navigate('/loan-orders') }, + ) } } // ── StepBar items ─────────────────────────────────────────────────────────── - // 4. stepBarItems'i StepCardItem[] olarak oluştur -const stepBarItems: StepCardItem[] = STEPS.map((s, i) => { - const isActive = i === currentStep - const hasErrors = stepsWithErrors.has(i) - const isDone = visited.has(i) && !hasErrors + const stepBarItems: StepCardItem[] = STEPS.map((s, i) => { + const isActive = i === currentStep + const hasErrors = stepsWithErrors.has(i) + const isDone = visited.has(i) && !hasErrors + return { + id: s.id, + title: t(s.titleKey) || s.titleFallback, + subtitle: s.subtitle, + icon: s.icon, + status: isActive ? 'active' : hasErrors ? 'error' : isDone ? 'done' : 'idle', + } + }) - return { - id: s.id, - title: t(s.titleKey) || s.titleFallback, - subtitle: s.subtitle, - 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 (
{/* Page header */} -
+

- {mode === 'create' ? (t('Loan order create') || 'Karz sargyt döredüň') : (t('Loan order edit') || 'Karz sargydy üýtget')} + {mode === 'create' + ? (t('Loan order create') || 'Karz sargyt döredüň') + : (t('Loan order edit') || 'Karz sargydy üýtget')}

-

+

{t('Fill in all sections step by step') || 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.'}

- {/* Horizontal step bar — sits above the form card */} - - - {/* Form card */} -
- {/* Card header */} -
- - {currentStep + 1} / {STEPS.length} - -

- {t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback} -

-
- - {/* Card body */} -
- {currentStep === 0 && } - {currentStep === 1 && } - {currentStep === 2 && } - {currentStep === 3 && } - {currentStep === 4 && } - {currentStep === 5 && } - {currentStep === 6 && } - {currentStep === 7 && } - {currentStep === 8 && } - {currentStep === 9 && } -
- - {/* Card footer */} -
- - - {isLastStep ? ( - - ) : ( - - )} -
+ {/* Step bar */} +
+
+ + {/* Step label */} +
+ + {currentStep + 1} / {STEPS.length} + +

+ {t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback} +

+
+ + {/* Step content */} + {currentStep === 0 && } + {currentStep === 1 && } + {currentStep === 2 && } + {currentStep === 3 && } + {currentStep === 4 && } + {currentStep === 5 && } + {currentStep === 6 && } + {currentStep === 7 && } + {currentStep === 8 && } + {currentStep === 9 && } + + {/* Actions */} + navigate(-1) : undefined} + onPrev={currentStep > 0 ? handleBack : undefined} + onNext={!isLastStep ? handleNext : undefined} + showSubmit={isLastStep} + onSubmit={isLastStep ? handleSubmit : undefined} + submitLabel={ + mode === 'create' + ? (t('loanOrderMobiles.createButton') || 'Karz sargyt döredüň') + : (t('loanOrders.saveButton') || 'Ýatda sakla') + } + loadingLabel={t('Loading') || 'Ýüklenilýär...'} + cancelLabel={t('Cancel') || 'Ýatyr'} + prevLabel={t('Back') || 'Yza'} + nextLabel={t('Next') || 'Indiki'} + />
) } \ No newline at end of file diff --git a/src/features/loanRemaining/components/LoanRemainingForm.tsx b/src/features/loanRemaining/components/LoanRemainingForm.tsx index 4de7572..3c297e6 100644 --- a/src/features/loanRemaining/components/LoanRemainingForm.tsx +++ b/src/features/loanRemaining/components/LoanRemainingForm.tsx @@ -1,11 +1,10 @@ import { useState, useEffect, useCallback } from 'react' import { useTranslation } from 'react-i18next' import { useNavigate } from 'react-router-dom' -import { Loader2 } from 'lucide-react' import { toast } from 'sonner' -import { Button } from '@/components/ui/button' import { FormInput } from '@/components/formInput' +import { FormActions } from '@/components/formActions' import { useCreateLoanRemaining, @@ -99,8 +98,8 @@ export function LoanRemainingForm({ return Object.keys(newErrors).length === 0 } - const handleSubmit = (e: React.FormEvent) => { - e.preventDefault() + const handleSubmit = (e?: React.FormEvent) => { + e?.preventDefault() setSubmitted(true) if (!validate()) { @@ -168,22 +167,14 @@ export function LoanRemainingForm({
-
- - -
+ navigate('/loan-remaining')} + submitLabel={mode === 'create' + ? t('common.create', 'Döret') + : t('common.save', 'Ýatda sakla')} + /> ) } diff --git a/src/features/loanTypes/components/loanTypesForm.tsx b/src/features/loanTypes/components/loanTypesForm.tsx index fbd3b19..5d8f313 100644 --- a/src/features/loanTypes/components/loanTypesForm.tsx +++ b/src/features/loanTypes/components/loanTypesForm.tsx @@ -4,8 +4,8 @@ import { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' import { Label } from '@/components/ui/label' +import { FormActions } from '@/components/formActions' import { Checkbox } from '@/components/ui/checkbox' import { useCreateLoanType, useUpdateLoanType } from '../hooks/useLoanTypes' import type { LoanType, CreateLoanTypePayload } from '../api/loanTypesApi' @@ -241,28 +241,16 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
- {/* Actions */} -
- - -
+
) } \ No newline at end of file diff --git a/src/features/operators/components/operatorForms.tsx b/src/features/operators/components/operatorForms.tsx index 835e886..ef1d9c8 100644 --- a/src/features/operators/components/operatorForms.tsx +++ b/src/features/operators/components/operatorForms.tsx @@ -1,8 +1,8 @@ import { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' -import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' +import { FormActions } from '@/components/formActions' import { FormInput } from '@/components/formInput' import { useCreateOperator, useUpdateOperator } from '../hooks/useOperators' import type { Operator, CreateOperatorPayload, UpdateOperatorPayload } from '../api/operatorsApi' @@ -225,29 +225,16 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp />
- {/* Actions */} -
- - -
+ navigate(-1)} + cancelVariant="ghost" + submitLabel={mode === 'create' + ? t('operators.createBtn', 'Operator döredin') + : t('operators.updateBtn', 'Üýtgetmeleri sakla')} + className="px-6 py-4 border-t border-border bg-muted/20" + />
) } \ No newline at end of file diff --git a/src/features/orderNewCard/components/orderNewCardForm.tsx b/src/features/orderNewCard/components/orderNewCardForm.tsx index 7b13dd9..6115608 100644 --- a/src/features/orderNewCard/components/orderNewCardForm.tsx +++ b/src/features/orderNewCard/components/orderNewCardForm.tsx @@ -1,7 +1,10 @@ import { useState, useEffect } from 'react' import { useTranslation } from 'react-i18next' +import { toast } from 'sonner' +import { CreditCard, User, FileText, Upload } from 'lucide-react' import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' +import { FormActions } from '@/components/formActions' +import { StepBarCards, type StepCardItem } from '@/components/stepBarV2' import type { SelectOption } from '@/components/formInput' import type { CardOrder, @@ -31,12 +34,10 @@ interface FormState { isPaid: boolean status: CardOrderStatus | '' note: string - issuanceReasonId: string cardTypeId: string provinceId: string branchId: string - firstName: string lastName: string middleName: string @@ -48,107 +49,135 @@ interface FormState { registeredAddress: string currentAddress: string workplace: string - passportSeriesId: string passportNumber: string passportIssueDate: string passportIssuedBy: string passportBirthPlace: string - passportPage1: File | null passportPage23: File | null passportPage89: File | null passportPage32: File | null - termsAccepted: boolean } type FormErrors = Partial> +type StepStatus = 'idle' | 'active' | 'done' | 'error' + +// ─── Step field mapping ─────────────────────────────────────────────────────── + +const STEP_FIELDS: Array> = [ + // Step 0 — Kart & Lokasiýa + ['status', 'issuanceReasonId', 'cardTypeId', 'provinceId', 'branchId'], + // Step 1 — Şahsy maglumatlar + [ + 'firstName', 'lastName', 'birthDate', 'phone', + 'citizenship', 'registeredAddress', 'currentAddress', 'workplace', + ], + // Step 2 — Pasport + [ + 'passportSeriesId', 'passportNumber', 'passportIssueDate', + 'passportIssuedBy', 'passportBirthPlace', + ], + // Step 3 — Faýllar & Şertler + ['passportPage1', 'passportPage23', 'passportPage89', 'passportPage32', 'termsAccepted'], +] // ─── Initial state ──────────────────────────────────────────────────────────── function getInitialState(data?: CardOrder): FormState { return { - isPaid: data?.isPaid ?? false, - status: data?.status ?? '', - note: data?.note ?? '', - - issuanceReasonId: data?.issuanceReasonId ? String(data.issuanceReasonId) : '', - cardTypeId: data?.cardTypeId ? String(data.cardTypeId) : '', - provinceId: data?.provinceId ? String(data.provinceId) : '', - branchId: data?.branchId ? String(data.branchId) : '', - - firstName: data?.firstName ?? '', - lastName: data?.lastName ?? '', - middleName: data?.middleName ?? '', - formerLastName: data?.formerLastName ?? '', - birthDate: data?.birthDate ?? '', - phone: data?.phone ?? '', - phoneExtra: data?.phoneExtra ?? '', - citizenship: data?.citizenship ?? 'Turkmenistan', - registeredAddress: data?.registeredAddress ?? '', - currentAddress: data?.currentAddress ?? '', - workplace: data?.workplace ?? '', - - passportSeriesId: data?.passportSeriesId ? String(data.passportSeriesId) : '', - passportNumber: data?.passportNumber ?? '', - passportIssueDate: data?.passportIssueDate ?? '', - passportIssuedBy: data?.passportIssuedBy ?? '', - passportBirthPlace:data?.passportBirthPlace?? '', - + isPaid: data?.isPaid ?? false, + status: data?.status ?? '', + note: data?.note ?? '', + issuanceReasonId: data?.issuanceReasonId ? String(data.issuanceReasonId) : '', + cardTypeId: data?.cardTypeId ? String(data.cardTypeId) : '', + provinceId: data?.provinceId ? String(data.provinceId) : '', + branchId: data?.branchId ? String(data.branchId) : '', + firstName: data?.firstName ?? '', + lastName: data?.lastName ?? '', + middleName: data?.middleName ?? '', + formerLastName: data?.formerLastName ?? '', + birthDate: data?.birthDate ?? '', + phone: data?.phone ?? '', + phoneExtra: data?.phoneExtra ?? '', + citizenship: data?.citizenship ?? 'Turkmenistan', + registeredAddress: data?.registeredAddress ?? '', + currentAddress: data?.currentAddress ?? '', + workplace: data?.workplace ?? '', + passportSeriesId: data?.passportSeriesId ? String(data.passportSeriesId) : '', + passportNumber: data?.passportNumber ?? '', + passportIssueDate: data?.passportIssueDate ?? '', + passportIssuedBy: data?.passportIssuedBy ?? '', + passportBirthPlace: data?.passportBirthPlace ?? '', passportPage1: null, passportPage23: null, passportPage89: null, passportPage32: null, - termsAccepted: false, } } // ─── Validation ─────────────────────────────────────────────────────────────── -function validate(form: FormState, mode: 'create' | 'edit', t: (k: string, fb: string) => string): FormErrors { - const errors: FormErrors = {} +function validate( + form: FormState, + mode: 'create' | 'edit', + t: (k: string, fb: string) => string, + stepIndex?: number, +): FormErrors { + const allErrors: FormErrors = {} const req = (field: keyof FormState, msg: string) => { const v = form[field] - if (!v || (typeof v === 'string' && !v.trim())) errors[field] = msg + if (!v || (typeof v === 'string' && !v.trim())) allErrors[field] = msg } - req('status', t('validation.required', 'Bu meýdan hökmanydyr')) - req('issuanceReasonId', t('validation.required', 'Bu meýdan hökmanydyr')) - req('cardTypeId', t('validation.required', 'Bu meýdan hökmanydyr')) - req('provinceId', t('validation.required', 'Bu meýdan hökmanydyr')) - req('branchId', t('validation.required', 'Bu meýdan hökmanydyr')) - req('firstName', t('validation.required', 'Bu meýdan hökmanydyr')) - req('lastName', t('validation.required', 'Bu meýdan hökmanydyr')) - req('birthDate', t('validation.required', 'Bu meýdan hökmanydyr')) - req('phone', t('validation.required', 'Bu meýdan hökmanydyr')) - req('citizenship', t('validation.required', 'Bu meýdan hökmanydyr')) - req('registeredAddress', t('validation.required', 'Bu meýdan hökmanydyr')) - req('currentAddress', t('validation.required', 'Bu meýdan hökmanydyr')) - req('workplace', t('validation.required', 'Bu meýdan hökmanydyr')) - req('passportSeriesId', t('validation.required', 'Bu meýdan hökmanydyr')) - req('passportNumber', t('validation.required', 'Bu meýdan hökmanydyr')) - req('passportIssueDate', t('validation.required', 'Bu meýdan hökmanydyr')) - req('passportIssuedBy', t('validation.required', 'Bu meýdan hökmanydyr')) - req('passportBirthPlace',t('validation.required', 'Bu meýdan hökmanydyr')) + const R = t('validation.required', 'Bu meýdan hökmanydyr') + + req('status', R) + req('issuanceReasonId', R) + req('cardTypeId', R) + req('provinceId', R) + req('branchId', R) + req('firstName', R) + req('lastName', R) + req('birthDate', R) + req('phone', R) + req('citizenship', R) + req('registeredAddress', R) + req('currentAddress', R) + req('workplace', R) + req('passportSeriesId', R) + req('passportNumber', R) + req('passportIssueDate', R) + req('passportIssuedBy', R) + req('passportBirthPlace', R) if (mode === 'create') { - if (!form.passportPage1) errors.passportPage1 = t('validation.required', 'Bu meýdan hökmanydyr') - if (!form.passportPage23) errors.passportPage23 = t('validation.required', 'Bu meýdan hökmanydyr') - if (!form.passportPage89) errors.passportPage89 = t('validation.required', 'Bu meýdan hökmanydyr') - if (!form.passportPage32) errors.passportPage32 = t('validation.required', 'Bu meýdan hökmanydyr') - if (!form.termsAccepted) errors.termsAccepted = t('validation.terms', 'Şertnama bilen razylaşmaly') + if (!form.passportPage1) allErrors.passportPage1 = R + if (!form.passportPage23) allErrors.passportPage23 = R + if (!form.passportPage89) allErrors.passportPage89 = R + if (!form.passportPage32) allErrors.passportPage32 = R + if (!form.termsAccepted) allErrors.termsAccepted = t('validation.terms', 'Şertnama bilen razylaşmaly') } - return errors + if (stepIndex !== undefined) { + const stepKeys = STEP_FIELDS[stepIndex] + const stepErrors: FormErrors = {} + for (const key of stepKeys) { + if (allErrors[key]) stepErrors[key] = allErrors[key] + } + return stepErrors + } + + return allErrors } // ─── Section wrapper ────────────────────────────────────────────────────────── function FormSection({ title, children }: { title?: string; children: React.ReactNode }) { return ( -
+
{title && (

{title}

)} @@ -171,20 +200,22 @@ export function CardOrderForm({ const { t } = useTranslation() const isEdit = mode === 'edit' - const [form, setForm] = useState(() => getInitialState(initialData)) - const [errors, setErrors] = useState({}) - const [touched, setTouched] = useState(false) + const [form, setForm] = useState(() => getInitialState(initialData)) + const [errors, setErrors] = useState({}) + const [currentStep, setCurrentStep] = useState(0) + const [stepStatuses, setStepStatuses] = useState([ + 'active', 'idle', 'idle', 'idle', + ]) - // Reset form when initialData loads (edit mode) useEffect(() => { if (initialData) setForm(getInitialState(initialData)) }, [initialData]) // Lookup data - const { data: reasons = [] } = useCardIssuanceReasons() - const { data: cardTypes = [] } = useCardTypes() - const { data: provinces = [] } = useProvinces() - const { data: branches = [] } = useBranches( + const { data: reasons = [] } = useCardIssuanceReasons() + const { data: cardTypes = [] } = useCardTypes() + const { data: provinces = [] } = useProvinces() + const { data: branches = [] } = useBranches( form.provinceId ? Number(form.provinceId) : undefined, ) @@ -195,26 +226,77 @@ export function CardOrderForm({ // Helpers const set = (key: keyof FormState) => (value: string) => - setForm((f) => ({ ...f, [key]: value })) + setForm((f) => { + const next = { ...f, [key]: value } + setErrors((prev) => ({ ...prev, [key]: undefined })) + return next + }) - const setFile = (key: keyof FormState) => (file: File | null) => + const setFile = (key: keyof FormState) => (file: File | null) => { setForm((f) => ({ ...f, [key]: file })) + setErrors((prev) => ({ ...prev, [key]: undefined })) + } const toOptions = (arr: { id: number; name: string }[]): SelectOption[] => arr.map((x) => ({ value: String(x.id), label: x.name })) - // Validate on every change if user has already submitted once - useEffect(() => { - if (touched) setErrors(validate(form, mode, t)) - }, [form, touched, mode]) + // ── Step navigation ──────────────────────────────────────────────────────── + + const updateStatus = (index: number, status: StepStatus) => { + setStepStatuses((prev) => { + const next = [...prev] + next[index] = status + return next + }) + } + + const goToStep = (index: number) => { + updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'done') + updateStatus(index, 'active') + setCurrentStep(index) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + const handleNext = () => { + const stepErrors = validate(form, mode, t, currentStep) + if (Object.keys(stepErrors).length > 0) { + setErrors((prev) => ({ ...prev, ...stepErrors })) + updateStatus(currentStep, 'error') + toast.error(t('validation.fixErrors', 'Dogry maglumat girizmegiňizi haýyş edýäris.')) + const firstKey = Object.keys(stepErrors)[0] + document.getElementById(`field-${firstKey}`)?.scrollIntoView({ behavior: 'smooth', block: 'center' }) + return + } + updateStatus(currentStep, 'done') + const next = currentStep + 1 + updateStatus(next, 'active') + setCurrentStep(next) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + const handlePrev = () => { + const prev = currentStep - 1 + updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'idle') + updateStatus(prev, 'active') + setCurrentStep(prev) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } // ── Submit ───────────────────────────────────────────────────────────────── const handleSubmit = async () => { - setTouched(true) - const errs = validate(form, mode, t) - if (Object.keys(errs).length > 0) { - setErrors(errs) + const allErrors = validate(form, mode, t) + if (Object.keys(allErrors).length > 0) { + setErrors(allErrors) + const newStatuses = stepStatuses.map((s, i) => { + const stepKeys = STEP_FIELDS[i] + const hasError = stepKeys.some((k) => allErrors[k]) + if (i === currentStep) return hasError ? 'error' : 'active' + if (hasError) return 'error' + return s === 'idle' ? 'idle' : 'done' + }) as StepStatus[] + setStepStatuses(newStatuses) + toast.error(t('validation.fixErrors', 'Dogry maglumat girizmegiňizi haýyş edýäris.')) return } @@ -228,7 +310,7 @@ export function CardOrderForm({ branchId: Number(form.branchId), firstName: form.firstName, lastName: form.lastName, - middleName: form.middleName || null, + middleName: form.middleName || null, formerLastName: form.formerLastName || null, birthDate: form.birthDate, phone: form.phone, @@ -260,7 +342,7 @@ export function CardOrderForm({ } } - // ── Status options ───────────────────────────────────────────────────────── + // ── Options ──────────────────────────────────────────────────────────────── const statusOptions: SelectOption[] = [ { value: 'PENDING', label: t('cardOrder.status.pending', 'Garaşylýar') }, @@ -269,351 +351,457 @@ export function CardOrderForm({ ] const citizenshipOptions: SelectOption[] = [ - { value: 'Turkmenistan', label: t('citizenship.tm', 'Turkmenistan') }, - { value: 'Russia', label: t('citizenship.ru', 'Russiýa') }, + { value: 'Turkmenistan', label: t('citizenship.tm', 'Turkmenistan') }, + { value: 'Russia', label: t('citizenship.ru', 'Russiýa') }, { value: 'Other', label: t('citizenship.other', 'Beýlekiler') }, ] + // ── Step bar items ───────────────────────────────────────────────────────── + + const stepDefs = [ + { + id: 'card', + title: t('cardOrder.step.card', 'Kart'), + subtitle: t('cardOrder.step.cardSub', 'Görnüş & lokasiýa'), + icon: CreditCard, + }, + { + id: 'personal', + title: t('cardOrder.step.personal', 'Şahsy'), + subtitle: t('cardOrder.step.personalSub', 'Maglumatlar'), + icon: User, + }, + { + id: 'passport', + title: t('cardOrder.step.passport', 'Pasport'), + subtitle: t('cardOrder.step.passportSub', 'Resmi maglumat'), + icon: FileText, + }, + { + id: 'files', + title: t('cardOrder.step.files', 'Faýllar'), + subtitle: t('cardOrder.step.filesSub', 'Ýüklemek & Tassyklamak'), + icon: Upload, + }, + ] + + const stepItems: StepCardItem[] = stepDefs.map((def, i) => ({ + ...def, + status: stepStatuses[i], + })) + + const isFirstStep = currentStep === 0 + const isLastStep = currentStep === stepDefs.length - 1 + // ── Render ──────────────────────────────────────────────────────────────── return ( -
+
- {/* ── Status section ── */} - -
- setForm((f) => ({ ...f, isPaid: e.target.checked }))} - className="w-4 h-4 accent-primary cursor-pointer" - /> - -
+ {/* ── Step Bar ─────────────────────────────────────────────────────── */} +
+ +
-
- - -
-
+ {/* ── Step 0: Kart & Lokasiýa ──────────────────────────────────────── */} + {currentStep === 0 && ( + <> + + {/* isPaid toggle */} +
+ setForm((f) => ({ ...f, isPaid: e.target.checked }))} + className="w-4 h-4 accent-primary cursor-pointer" + /> + +
- {/* ── Kart ── */} - -
- - -
-
+
+
+ +
+ +
+
- {/* ── Lokasiýa ── */} - -
- { - setForm((f) => ({ ...f, provinceId: v, branchId: '' })) - }} - options={toOptions(provinces)} - error={errors.provinceId} - /> - -
-
+ +
+
+ +
+
+ +
+
+
- {/* ── Şahsy maglumatlar ── */} - -
- - - -
- -
- - -
- -
- - - -
- -
- - -
- - -
- - {/* ── Pasport ── */} - -
- - - -
- -
- - -
-
- - {/* ── Pasport faýýlar ── */} - -
- - - - -
-
- - {/* ── Terms ── */} - {!isEdit && ( -
setForm((f) => ({ ...f, termsAccepted: !f.termsAccepted }))} - > -
- {form.termsAccepted && ( - - - - )} -
- - {t('cardOrder.terms', 'Şertnama bilen razylaşýaryn (Okamak üçin bas)')} - -
+ +
+
+ { + setForm((f) => ({ ...f, provinceId: v, branchId: '' })) + setErrors((prev) => ({ ...prev, provinceId: undefined, branchId: undefined })) + }} + options={toOptions(provinces)} + error={errors.provinceId} + /> +
+
+ +
+
+
+ )} - {/* ── Actions ── */} -
- {onCancel && ( - - )} - -
+ {/* ── Step 1: Şahsy maglumatlar ─────────────────────────────────────── */} + {currentStep === 1 && ( + +
+
+ +
+
+ +
+ +
+ +
+ +
+ +
+
+ +
+
+ +
+ +
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+ +
+
+ )} + + {/* ── Step 2: Pasport ───────────────────────────────────────────────── */} + {currentStep === 2 && ( + +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+ )} + + {/* ── Step 3: Faýllar & Şertler ─────────────────────────────────────── */} + {currentStep === 3 && ( + <> + +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+ + {/* Terms — only in create mode */} + {!isEdit && ( +
{ + setForm((f) => ({ ...f, termsAccepted: !f.termsAccepted })) + setErrors((prev) => ({ ...prev, termsAccepted: undefined })) + }} + > +
+ {form.termsAccepted && ( + + + + )} +
+ + {t('cardOrder.terms', 'Şertnama bilen razylaşýaryn (Okamak üçin bas)')} + +
+ )} + + )} + + {/* ── Form Actions ──────────────────────────────────────────────────── */} +
) } \ No newline at end of file diff --git a/src/features/permissions/components/permissionsForm.tsx b/src/features/permissions/components/permissionsForm.tsx index f07a4a5..5845314 100644 --- a/src/features/permissions/components/permissionsForm.tsx +++ b/src/features/permissions/components/permissionsForm.tsx @@ -2,7 +2,7 @@ import { useState } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' +import { FormActions } from '@/components/formActions' import { useCreatePermission, useUpdatePermission } from '../hooks/usePermissions' import type { Permission, PermissionPayload } from '../api/permissionsApi' @@ -175,28 +175,15 @@ export function PermissionForm({ mode, initialData, permissionId }: PermissionFo />
- {/* Actions */} -
- - -
+ navigate('/settings/users/permissions')} + submitLabel={mode === 'create' + ? t('permissions.actions.create', 'Rugsat dörediň') + : t('permissions.actions.save', 'Ýatda sakla')} + className="px-5 py-4 border-t border-border bg-muted/20" + />
) } \ No newline at end of file diff --git a/src/features/requiredDocuments/components/requiredDocumentsForm.tsx b/src/features/requiredDocuments/components/requiredDocumentsForm.tsx index a3bd53d..8185fa4 100644 --- a/src/features/requiredDocuments/components/requiredDocumentsForm.tsx +++ b/src/features/requiredDocuments/components/requiredDocumentsForm.tsx @@ -21,7 +21,7 @@ import { } from 'lucide-react' import { cn } from '@/lib/utils' import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' +import { FormActions } from '@/components/formActions' import { useCreateRequiredDocument, useUpdateRequiredDocument } from '../hooks/useRequiredDocuments' import type { LoanDocument, LoanDocumentPayload, LoanDocumentTranslation } from '../api/requiredDocumentsApi' @@ -222,8 +222,8 @@ export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }: // ── Submit ────────────────────────────────────────────────────────────────── - const handleSubmit = async (e: React.FormEvent) => { - e.preventDefault() + const handleSubmit = async (e?: React.FormEvent) => { + e?.preventDefault() if (!validate()) return const payload: LoanDocumentPayload = { name, description } @@ -292,20 +292,15 @@ export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }:
- {/* ── Actions ──────────────────────────────────────────────────────────── */} -
- - -
+ navigate('/settings/loan/loan-documents')} + cancelVariant="ghost" + loadingLabel={t('common.saving', 'Saklanylýar...')} + submitLabel={submitLabel} + className="mt-4" + /> ) } \ No newline at end of file diff --git a/src/features/roles/components/roleForm.tsx b/src/features/roles/components/roleForm.tsx index 647ccda..cc137dc 100644 --- a/src/features/roles/components/roleForm.tsx +++ b/src/features/roles/components/roleForm.tsx @@ -2,7 +2,7 @@ import { useState } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' +import { FormActions } from '@/components/formActions' import { useCreateRole, useUpdateRole } from '../hooks/useRoles' import type { Role, RolePayload } from '../api/rolesApi' @@ -176,28 +176,16 @@ export function RoleForm({ mode, initialData, roleId }: RoleFormProps) { /> - {/* Actions */} -
- - -
+ navigate('/settings/users/roles')} + loadingLabel={t('common.saving', 'Ýüklenýär...')} + submitLabel={mode === 'create' + ? t('roles.actions.create', 'Rol dörediň') + : t('roles.actions.save', 'Ýatda sakla')} + className="px-5 py-4 border-t border-border bg-muted/20" + /> ) } \ No newline at end of file diff --git a/src/features/sberPayments/components/sberPaymentsForm.tsx b/src/features/sberPayments/components/sberPaymentsForm.tsx index 280f60c..e822b59 100644 --- a/src/features/sberPayments/components/sberPaymentsForm.tsx +++ b/src/features/sberPayments/components/sberPaymentsForm.tsx @@ -1,15 +1,24 @@ -'use client' - import { useState, useEffect } from 'react' +import { useNavigate } from 'react-router-dom' import { toast } from 'sonner' -import { Plus } from 'lucide-react' +import { User, MapPin, IdCard, CreditCard, Files } from 'lucide-react' import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' -import { Spinner } from '@/components/ui/spinner' -import { useCreateSberPayment, useUpdateSberPayment } from '@/features/sberPayments/hooks/useSberPayments' -import { WELAYATLAR, SAHAMCALAR, STATUSES, type SberPaymentOrder, type SberPaymentFormData, type PaymentStatus } from '@/features/sberPayments/api/sberPaymentsApi' -import { useNavigate } from 'react-router-dom' +import { FormActions } from '@/components/formActions' +import { StepBarCards, type StepCardItem } from '@/components/stepBarV2' +import type { StepStatus } from '@/components/stepBar' +import { + useCreateSberPayment, + useUpdateSberPayment, +} from '@/features/sberPayments/hooks/useSberPayments' +import { + WELAYATLAR, + SAHAMCALAR, + STATUSES, + type SberPaymentOrder, + type SberPaymentFormData, + type PaymentStatus, +} from '@/features/sberPayments/api/sberPaymentsApi' // ─── Types ──────────────────────────────────────────────────────────────────── @@ -19,376 +28,604 @@ interface SberPaymentFormProps { orderId?: string } -// ─── Document Labels ────────────────────────────────────────────────────────── +// ─── Document lists ─────────────────────────────────────────────────────────── -const acceptedDocumentLabels = [ - 'Talyba degisli walýuta "SBERBANK" kartyň rekwizitleri', - 'Talybýň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwanamasy', - 'Talybýň bildirisli göcürmesi', - 'Talyba degisli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi', - 'Talybýň Türkmenistandan çykmak we Türkmenistana girmek üçin (zagran) pasportynyň göçürmesi', - 'Talybýň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportyndaky daşary ýurda göýberilmegi barada beriim miiletti hereket edijan rughsatnamasyniyň (wizasynyň) bellenen sahypasynyň göçürmesi', - 'Talybýň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportyndaky Türkmenistandan çykanday we daşary ýurt döwletine girenligi baradaky ştamplaryň (belgi ştamply) bellenen sahypasynyň göçürmesi', - 'Talybýň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwanamasynyň doly takyk dili wýagdayýnda talyk dili magumatyň sebäpleri baradaky daşary ýurt döwletiniň ýokary okuw mekdebinden haty', +type AcceptedDocKey = + | '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' + +const ACCEPTED_DOCS: { key: AcceptedDocKey; label: string }[] = [ + { key: 'acc_sberbank_card', label: 'Talýba degişli SBERBANK kartynyň rekwizitleri' }, + { key: 'acc_enrollment', label: 'Daşary ýurt ÝOM-da okaýandygy baradaky güwänamasy' }, + { key: 'acc_summons', label: 'Çagyrylma hatynyn göçürmesi' }, + { key: 'acc_passport_tm', label: 'TM içki pasportynyň asyl görnüşi we göçürmesi' }, + { key: 'acc_zagran_passport', label: 'Daşary ýurt (zagran) pasportynyň göçürmesi' }, + { key: 'acc_visa_page', label: 'Daşary ýurda rugsat (wizasy) bellenen sahypasynyň göçürmesi' }, + { key: 'acc_entry_stamp', label: 'Daşary ýurt döwletine girenliği baradaky ştamply sahypasynyň göçürmesi' }, + { key: 'acc_school_letter', label: 'ÝOM-dan hat (daşary ýurt dilinde maglumatly)' }, ] -const sentDocumentLabels = [ - 'Ugradyjy degisli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi', - 'Ugradyjy degisli Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň asyl görnüşi we göçürmesi', - 'Ugradyjy degisli Türkmenistandan çykmak we Türkmenistana girmek üçin pasportyndaky daşary döwletine girenliği we daşary döwlete baradaky ştamply bellenen sahypasynyň göçürmesi', - 'Ugradyjynýň we kabul edijinin (talybýň) özara garyndaşlyk denjesini tassyklaýjy resminamalarynýň göçürmesi', - 'Ugradyjy we kabul ediji (talyp) 2015-nji ýyldan soňra Türkmenistanyň raýatynýň pasportyny kiriş gerek alan bolsa, onda birnji gerek alan pasportynyň seriyasy baradaky maglumat', - 'Ugradyjy we kabul ediji (talyp) 2015-nji ýyldan soňra Türkmenistanyň raýatynýň pasportyny kiriş gerek alandan soňra birnji gerek alan pasportynyň seriyasy baradaky magumatý bilmeýän, balsa onda polisijyenyň degisli ekedasynýdan birnji alan pasportynyň seriyasy baradaky güwanamasy', +const SENT_DOCS: { key: SentDocKey; label: string }[] = [ + { key: 'snt_passport_tm', label: 'Ugradyjynyň TM içki pasportynyň asyl görnüşi we göçürmesi' }, + { key: 'snt_zagran_passport', label: 'Ugradyjynyň daşary ýurt pasportynyň asyl görnüşi we göçürmesi' }, + { key: 'snt_entry_stamp', label: 'Ugradyjynyň daşary döwletine girenliği ştamply sahypasynyň göçürmesi' }, + { key: 'snt_relation_doc', label: 'Ugradyjy we kabul edijiniň garyndaşlyk tassyklaýjy resminamasynyn göçürmesi' }, + { key: 'snt_new_passport_series', label: 'Ugradyjy/kabul ediji täze (2015+) pasport seriýasy maglumaty' }, + { key: 'snt_old_passport_series', label: 'Ugradyjy/kabul ediji köne pasport seriýasy baradaky güwänamasy' }, ] -// ─── Shared Form Component ──────────────────────────────────────────────────── -export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormProps) { - const router = useNavigate() - const createMutation = useCreateSberPayment() - const updateMutation = useUpdateSberPayment() - - const isLoading = createMutation.isPending || updateMutation.isPending - - // Form state - const [formData, setFormData] = useState({ - welayat: '', - sahamca: '', - firstName: '', - lastName: '', - phone: '', - email: '', - address: '', - status: 'GARASYLYYAR', - bellik: '', - accountNumber: '', - passportSeries: '', - passportNumber: '', - fullName: '', - }) - +// ─── FormState ──────────────────────────────────────────────────────────────── - - // Validation errors - const [errors, setErrors] = useState>>({}) - - // Populate form with initial data in edit mode - useEffect(() => { - if (mode === 'edit' && initialData) { - setFormData({ - welayat: initialData.welayat, - sahamca: initialData.sahamca, - firstName: initialData.firstName, - lastName: initialData.lastName, - phone: initialData.phone, - email: initialData.email, - address: initialData.address, - status: initialData.status, - bellik: initialData.bellik, - accountNumber: initialData.accountNumber, - passportSeries: initialData.passportSeries, - passportNumber: initialData.passportNumber, - fullName: initialData.fullName, - }) - } - }, [mode, initialData]) - - // Get available branches based on selected welayat - const availableBranches = formData.welayat ? SAHAMCALAR[formData.welayat] ?? [] : [] - - // Update field helper - const updateField = ( - field: K, - value: SberPaymentFormData[K] - ) => { - setFormData((prev) => ({ ...prev, [field]: value })) - if (errors[field]) { - setErrors((prev) => ({ ...prev, [field]: undefined })) - } - } - - // Validate form - const validate = (): boolean => { - const newErrors: Partial> = {} - - if (!formData.welayat) newErrors.welayat = 'Welayat saylanmaly' - if (!formData.sahamca) newErrors.sahamca = 'Sahamca saylanmaly' - if (!formData.firstName) newErrors.firstName = 'Ady girizmeli' - if (!formData.lastName) newErrors.lastName = 'Familiyasy girizmeli' - if (!formData.phone) newErrors.phone = 'Telefon girizmeli' - if (!formData.address) newErrors.address = 'Salgy girizmeli' - if (!formData.passportSeries) newErrors.passportSeries = 'Pasport seriyasy girizmeli' - if (!formData.passportNumber) newErrors.passportNumber = 'Pasport nomeri girizmeli' - if (!formData.fullName) newErrors.fullName = 'Doly ady girizmeli' - if (!formData.accountNumber) newErrors.accountNumber = 'Goyum hasaby girizmeli' - - setErrors(newErrors) - return Object.keys(newErrors).length === 0 - } - - // Submit handler - const handleSubmit = async () => { - if (!validate()) { - toast.error('Meydanlary dolduryň') - return - } - - try { - if (mode === 'create') { - await createMutation.mutateAsync(formData) - toast.success('Toleg ustunlikli doredildi') - router('/sber-payments') - } else if (orderId) { - await updateMutation.mutateAsync({ ...formData, id: orderId }) - toast.success('Toleg ustunlikli tazelendi') - router(`/sber-payments/${orderId}`) - } - } catch { - toast.error('Yalnyshlyk yuze cykdy') - } - } - +interface FormState extends SberPaymentFormData { + client_id: string + // file fields + acc_sberbank_card: File | null + acc_enrollment: File | null + acc_summons: File | null + acc_passport_tm: File | null + acc_zagran_passport: File | null + acc_visa_page: File | null + acc_entry_stamp: File | null + acc_school_letter: File | null + snt_passport_tm: File | null + snt_zagran_passport: File | null + snt_entry_stamp: File | null + snt_relation_doc: File | null + snt_new_passport_series: File | null + snt_old_passport_series: File | null +} + +type FormErrors = Partial> + +// ─── Default state ──────────────────────────────────────────────────────────── + +const defaultState: FormState = { + client_id: '', + welayat: '', + sahamca: '', + firstName: '', + lastName: '', + phone: '', + email: '', + address: '', + status: 'GARASYLYYAR', + bellik: '', + accountNumber: '', + passportSeries: '', + passportNumber: '', + fullName: '', + acc_sberbank_card: null, + acc_enrollment: null, + acc_summons: null, + acc_passport_tm: null, + acc_zagran_passport: null, + acc_visa_page: null, + acc_entry_stamp: null, + acc_school_letter: null, + snt_passport_tm: null, + snt_zagran_passport: null, + snt_entry_stamp: null, + snt_relation_doc: null, + snt_new_passport_series: null, + snt_old_passport_series: null, +} + +// ─── Step definitions ───────────────────────────────────────────────────────── + +type StepId = 'general' | 'location' | 'personal' | 'payment' | 'docs' + +const STEPS: { id: StepId; title: string; subtitle: string }[] = [ + { id: 'general', title: 'Esasy', subtitle: 'Status, müşderi' }, + { id: 'location', title: 'Lokasiýa', subtitle: 'Welaýat, şahamça' }, + { id: 'personal', title: 'Şahsy', subtitle: 'Pasport, kontakt' }, + { id: 'payment', title: 'Töleg', subtitle: 'Hasap, ugradyjy' }, + { id: 'docs', title: 'Resminamalar', subtitle: '14 resminama' }, +] + +const STEP_REQUIRED: Partial> = { + general: ['status'], + location: ['welayat', 'sahamca'], + personal: ['firstName', 'lastName', 'phone', 'address'], + payment: ['passportSeries', 'passportNumber', 'fullName', 'accountNumber'], +} + +const ERROR_LABELS: Partial> = { + status: 'Status hökmany', + welayat: 'Welaýat hökmany', + sahamca: 'Şahamça hökmany', + firstName: 'Ady hökmany', + lastName: 'Familiýasy hökmany', + phone: 'Telefon hökmany', + address: 'Salgy hökmany', + passportSeries:'Pasport seriýasy hökmany', + passportNumber:'Pasport nomeri hökmany', + fullName: 'Doly ady hökmany', + accountNumber: 'Goýum hasaby hökmany', +} + +// ─── Bento primitives ───────────────────────────────────────────────────────── + +function BentoGrid({ cols = 2, children }: { cols?: 1 | 2; children: React.ReactNode }) { return ( -
- {/* Status Section */} -
-

Status

-
- {}} - options={[]} - /> - updateField('status', val as PaymentStatus)} - options={STATUSES} - error={errors.status} - /> - updateField('bellik', val)} - placeholder="Bellik" - /> -
-
- - {/* Location Section */} -
-

Lokasiya

-
- { - updateField('welayat', val) - updateField('sahamca', '') // Reset branch when region changes - }} - options={WELAYATLAR.map((w) => ({ value: w, label: w }))} - placeholder="Asgabat" - error={errors.welayat} - /> - updateField('sahamca', val)} - options={availableBranches.map((b) => ({ value: b, label: b }))} - placeholder="Saylamak ucin basyn" - disabled={!formData.welayat} - error={errors.sahamca} - /> -
-
- - {/* Personal Info Section */} -
-

Sahsy maglumatlar

-
- updateField('firstName', val)} - placeholder="Pasportdaky ady" - error={errors.firstName} - /> - updateField('lastName', val)} - placeholder="Pasportdaky familiya" - error={errors.lastName} - /> - updateField('phone', val)} - placeholder="61 097 651" - error={errors.phone} - /> - updateField('email', val)} - placeholder="E-pocta" - /> - updateField('address', val)} - placeholder="Hazirki yasayys yeri" - error={errors.address} - /> -
-
- - {/* Payment Info Section */} -
-

Tolegi ugradyjynyn maglumatlary

-
- updateField('passportSeries', val)} - 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' }, - ]} - placeholder="Saylamak ucin basyn" - error={errors.passportSeries} - /> - updateField('passportNumber', val)} - placeholder="Pasport nomeri" - error={errors.passportNumber} - /> - updateField('fullName', val)} - placeholder="Ady Familiyasy Atasynyn ady" - error={errors.fullName} - /> - updateField('accountNumber', val)} - placeholder="Goyum hasaby" - error={errors.accountNumber} - /> -
-
- - {/* Recipient Info Section */} -
-

Tolegi kabul edijinin maglumatlary

-
-
- - Tolegi kabul edijinin maglumatlary - - -
-
-
- - {/* Accepted Documents Section */} -
-

- Kabul ediji talyp boyunca resminamalary -

-
- {acceptedDocumentLabels.map((label, index) => ( -
- - {label} - - -
- ))} -
-
- - {/* Sent Documents Section */} -
-

- Ugradyjy boyunca resminamalary -

-
- {sentDocumentLabels.map((label, index) => ( -
- - {label} - - -
- ))} -
-
- - {/* Actions */} -
- - -
+
+ {children}
) } + +function BentoCard({ + title, + span, + children, +}: { + title?: string + span?: 'full' + children: React.ReactNode +}) { + return ( +
+ {title && ( +

+ {title} +

+ )} + {children} +
+ ) +} + +// ─── Step panels ────────────────────────────────────────────────────────────── + +function StepGeneral({ + form, errors, set, +}: { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void +}) { + return ( + + + set('client_id', v)} + options={[]} + placeholder="Saýlamak üçin basyň" + required + /> + + + + set('status', v as PaymentStatus)} + options={STATUSES} + error={errors.status} + required + /> + + + + set('bellik', v)} + placeholder="Bellik..." + rows={2} + /> + + + ) +} + +function StepLocation({ + form, errors, set, +}: { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void +}) { + const branches = form.welayat ? (SAHAMCALAR[form.welayat] ?? []) : [] + + return ( + + + { set('welayat', v); set('sahamca', '') }} + options={WELAYATLAR.map((w) => ({ value: w, label: w }))} + placeholder="Aşgabat" + error={errors.welayat} + required + /> +

+ Welaýaty saýlasaňyz şahamçalar güncellenar. +

+
+ + + set('sahamca', v)} + options={branches.map((b) => ({ value: b, label: b }))} + placeholder="Saýlamak üçin basyň" + disabled={!form.welayat} + error={errors.sahamca} + required + /> + +
+ ) +} + +function StepPersonal({ + form, errors, set, +}: { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void +}) { + return ( + + + set('lastName', v)} + placeholder="NURYYEW" + error={errors.lastName} + required + /> + set('firstName', v)} + placeholder="HAÝDAR" + error={errors.firstName} + required + /> + + + + set('phone', v)} + error={errors.phone} + required + /> + set('email', v)} + placeholder="email@example.com" + /> + + + + set('address', v)} + placeholder="Köçe, jaý belgisi..." + error={errors.address} + required + /> + + + ) +} + +function StepPayment({ + form, errors, set, +}: { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void +}) { + return ( + + + 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' }, + ]} + placeholder="Saýlamak üçin basyň" + error={errors.passportSeries} + required + /> + set('passportNumber', v)} + placeholder="A123456" + error={errors.passportNumber} + required + /> + + + + set('fullName', v)} + placeholder="Doly ady..." + error={errors.fullName} + required + /> + set('accountNumber', v)} + placeholder="1234 5678 ..." + error={errors.accountNumber} + required + /> + + + ) +} + +function StepDocs({ + form, set, +}: { + form: FormState + set: (k: K, v: FormState[K]) => void +}) { + return ( + + +
+ {ACCEPTED_DOCS.map(({ key, label }) => ( + set(key, f)} + fileValue={form[key] as File | null} + accept="image/*,.pdf" + /> + ))} +
+
+ + +
+ {SENT_DOCS.map(({ key, label }) => ( + set(key, f)} + fileValue={form[key] as File | null} + accept="image/*,.pdf" + /> + ))} +
+
+
+ ) +} + +// ─── Main component ─────────────────────────────────────────────────────────── + +export function SberPaymentForm({ mode, initialData, orderId }: SberPaymentFormProps) { + const navigate = useNavigate() + const createMutation = useCreateSberPayment() + const updateMutation = useUpdateSberPayment() + const isLoading = createMutation.isPending || updateMutation.isPending + + const [form, setForm] = useState(defaultState) + const [errors, setErrors] = useState({}) + const [currentStep, setCurrentStep] = useState(0) + const [stepStatuses, setStepStatuses] = useState( + STEPS.map((_, i) => (i === 0 ? 'active' : 'idle')), + ) + + // ── Populate in edit mode ── + useEffect(() => { + if (mode === 'edit' && initialData) { + setForm((prev) => ({ + ...prev, + welayat: initialData.welayat, + sahamca: initialData.sahamca, + firstName: initialData.firstName, + lastName: initialData.lastName, + phone: initialData.phone, + email: initialData.email, + address: initialData.address, + status: initialData.status, + bellik: initialData.bellik, + accountNumber: initialData.accountNumber, + passportSeries: initialData.passportSeries, + passportNumber: initialData.passportNumber, + fullName: initialData.fullName, + })) + // Let user jump freely to any step in edit mode + setStepStatuses(STEPS.map((_, i) => (i === 0 ? 'active' : i < 4 ? 'done' : 'idle'))) + } + }, [mode, initialData]) + + // ── Field setter ── + const set = (key: K, value: FormState[K]) => { + setForm((prev) => ({ ...prev, [key]: value })) + if (errors[key]) setErrors((prev) => ({ ...prev, [key]: undefined })) + } + + // ── Step validation ── + const validateStep = (stepId: StepId): FormErrors => { + const fields = STEP_REQUIRED[stepId] ?? [] + const errs: FormErrors = {} + fields.forEach((f) => { + if (!form[f]) errs[f] = ERROR_LABELS[f] ?? 'Hökmany' + }) + return errs + } + + const validateAll = (): FormErrors => { + const errs: FormErrors = {} + Object.entries(ERROR_LABELS).forEach(([k, msg]) => { + if (!form[k as keyof FormState]) errs[k as keyof FormState] = msg + }) + return errs + } + + // ── Navigation ── + const goStep = (idx: number) => { + if (idx < 0 || idx >= STEPS.length) return + setStepStatuses((prev) => { + const next = [...prev] + if (idx > currentStep) next[currentStep] = 'done' + next[idx] = 'active' + if (idx < currentStep) { + for (let i = idx + 1; i <= currentStep; i++) { + if (next[i] !== 'done') next[i] = 'idle' + } + } + return next + }) + setErrors({}) + setCurrentStep(idx) + } + + const handleNext = () => { + const stepId = STEPS[currentStep].id + const stepErrors = validateStep(stepId) + if (Object.keys(stepErrors).length > 0) { + setErrors(stepErrors) + setStepStatuses((prev) => { + const next = [...prev]; next[currentStep] = 'error'; return next + }) + return + } + if (currentStep === STEPS.length - 1) { + handleSubmit() + } else { + goStep(currentStep + 1) + } + } + + // ── Submit ── + const handleSubmit = async () => { + const allErrors = validateAll() + if (Object.keys(allErrors).length > 0) { + setErrors(allErrors) + toast.error('Meýdanlary dolduryň') + return + } + try { + const payload: SberPaymentFormData = { + welayat: form.welayat, + sahamca: form.sahamca, + firstName: form.firstName, + lastName: form.lastName, + phone: form.phone, + email: form.email, + address: form.address, + status: form.status, + bellik: form.bellik, + accountNumber: form.accountNumber, + passportSeries: form.passportSeries, + passportNumber: form.passportNumber, + fullName: form.fullName, + } + if (mode === 'create') { + await createMutation.mutateAsync(payload) + toast.success('Töleg üstünlikli döredildi') + navigate('/sber-payments') + } else if (orderId) { + await updateMutation.mutateAsync({ ...payload, id: orderId }) + toast.success('Töleg üstünlikli täzelendi') + navigate(`/sber-payments/${orderId}`) + } + } catch { + toast.error('Ýalňyşlyk ýüze çykdy') + } + } + + // ── StepBarCards data ── + const stepCardItems: StepCardItem[] = STEPS.map((s, i) => ({ + id: s.id, + title: s.title, + subtitle: s.subtitle, + status: stepStatuses[i], + icon: ([User, MapPin, IdCard, CreditCard, Files] as const)[i], + })) + + const isLastStep = currentStep === STEPS.length - 1 + + const submitLabel = mode === 'create' + ? 'Sber töleg (talyplar üçin) dörediň' + : 'Ýatda sakla' + + return ( +
+

+ {mode === 'create' ? 'Sber töleg dörediň' : 'Sber töleg redaktirläň'} +

+ + {/* ── Step bar ──────────────────────────────────────────────────────── */} +
+ { + if (stepStatuses[i] !== 'idle') goStep(i) + }} + /> +
+ + {/* ── Step content ─────────────────────────────────────────────────── */} + {STEPS[currentStep].id === 'general' && } + {STEPS[currentStep].id === 'location' && } + {STEPS[currentStep].id === 'personal' && } + {STEPS[currentStep].id === 'payment' && } + {STEPS[currentStep].id === 'docs' && } + + {/* ── Actions ───────────────────────────────────────────────────────── */} + navigate('/sber-payments')} + onPrev={currentStep > 0 ? () => goStep(currentStep - 1) : undefined} + onNext={!isLastStep ? handleNext : undefined} + showSubmit={isLastStep} + onSubmit={isLastStep ? handleNext : undefined} + submitLabel={submitLabel} + loadingLabel="Ýüklenýär..." + /> +
+ ) +} \ No newline at end of file diff --git a/src/features/sberPayments/hooks/useSberPayments.ts b/src/features/sberPayments/hooks/useSberPayments.ts index afab9ab..3a2caad 100644 --- a/src/features/sberPayments/hooks/useSberPayments.ts +++ b/src/features/sberPayments/hooks/useSberPayments.ts @@ -1,4 +1,3 @@ -'use client' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { diff --git a/src/features/visaMasterPayments/components/intlPaymentForm.tsx b/src/features/visaMasterPayments/components/intlPaymentForm.tsx index aa09de8..a816ce6 100644 --- a/src/features/visaMasterPayments/components/intlPaymentForm.tsx +++ b/src/features/visaMasterPayments/components/intlPaymentForm.tsx @@ -1,10 +1,19 @@ import { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' +import { + User, MapPin, IdCard, CreditCard, Files, +} from 'lucide-react' import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' -import { Spinner } from '@/components/ui/spinner' -import type { IntlPaymentItem, IntlPaymentCreatePayload, IntlPaymentStatus, CurrencyType } from '../api/visaMasterPaymentsApi' +import { FormActions } from '@/components/formActions' +import { StepBarCards, type StepCardItem } from '@/components//stepBarV2' +import type { StepStatus } from '@/components/stepBar' +import type { + IntlPaymentItem, + IntlPaymentCreatePayload, + IntlPaymentStatus, + CurrencyType, +} from '../api/visaMasterPaymentsApi' // ─── Types ──────────────────────────────────────────────────────────────────── @@ -87,29 +96,69 @@ const PROVINCE_OPTIONS = [ { value: 'balkan', label: 'Balkan' }, ] -// Kabul ediji docs — 9 sany const KABUL_DOCS: { key: FileKey; label: string }[] = [ - { key: 'doc_sberbank_account', label: 'Talypyň degişli welaýata "SBERBANK" kartyň rekwizitleri' }, - { key: 'doc_school_enrollment', label: 'Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwänamasy' }, - { key: 'doc_summons', label: 'Talypyň bilendiriň göçürmesi' }, - { key: 'doc_passport_tm', label: 'Talypyň degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi' }, - { key: 'doc_foreign_passport', label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi' }, - { key: 'doc_foreign_passport_copy',label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň daşary ýurtda galan döwründe bakýan döwleti baradaky bellenen sahypasynyň göçürmesi' }, - { key: 'doc_exit_permission', label: 'Talypyň Türkmenistandan çykmak — we Türkmenistana girmek üçin pasportynyň dowletiniň girmesiz baradaky bellenen (goşmaç şaýmynyň) bellenen sahypasynyň göçürmesi' }, - { key: 'doc_school_foreign_info', label: 'Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy barada doly takyk dil ulgaýynda takyk dil maglumatly sebäpleri daşary ýurt döwletiniň ýokary okuw mekdebinden haty' }, - { key: 'doc_school_departure_info',label: 'Talypyň daşary ýurt döwletinde döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwänamany döwlet dili maglumatlaryny talabap doly takyk dil ulgaýynda talaby daşary ýurt döwletiniň ýokary okuw mekdebinden haty' }, + { 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)' }, ] -// Upgradyý docs — 6 sany const UPGRAD_DOCS: { key: FileKey; label: string }[] = [ - { key: 'upd_doc_passport_tm', label: 'Upgradyý degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi' }, - { key: 'upd_doc_foreign_passport', label: 'Upgradyý degişli Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi' }, - { key: 'upd_doc_visa', label: 'Upgradyý Türkmenistandan — çykmak we Türkmenistana girmek üçin pasportynyň daşary ýurt döwletinde galýandygy we daşary ýurt döwleti baradaky şaýmynyň bellenen sahypasynyň göçürmesi' }, - { key: 'upd_doc_acceptance_letter', label: 'Upgradyýyň we kabul edijiniň Batalyý töräre garyşdyryjy resminamalarynyň göçürmesi' }, - { key: 'upd_doc_passport_biometric', label: 'Upgradyý we kabul ediji täze 2015-nji ýyldan soňra Türkmenistanyň raýatynyň pasportynyň tässy göreli alan bolsa, osta üstü görli 1 pasportynyň seriýasy baradaky maglumatlary' }, - { key: 'upd_doc_passport_old', label: 'Upgradyý we kabul ediji täze 2015-nji ýyldan soňra Türkmenistanyň raýatynyň pasportynyň köp göreli alanlar soňra birleşi göreli alan bolsa, biri miwe möhüründen doglan doglan ata-enelerden biriniň alan pasportynyň seriýasy baradaky göwnamasy' }, + { 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' + +interface Step { + id: StepId + title: string + subtitle: string +} + +const STEPS: Step[] = [ + { id: 'general', title: 'Esasy', subtitle: 'Status, müşderi' }, + { id: 'location', title: 'Lokasiýa', subtitle: 'Welaýat, şahamça' }, + { id: 'personal', title: 'Şahsy', subtitle: 'Pasport, kontakt' }, + { id: 'payment', title: 'Töleg', subtitle: 'Töleýji, kabul ediji' }, + { id: 'docs', title: 'Resminamalar', subtitle: '15 resminama' }, +] + +// Per-step required fields for incremental validation +const STEP_REQUIRED_FIELDS: Partial> = { + general: ['client_id', 'status', 'currency_type'], + location: ['province', 'branch'], + personal: ['passport_first_name', 'passport_last_name', 'phone'], + payment: ['passport_series', 'passport_number', 'payer_full_name', 'payer_account_number', 'receiver_info'], +} + +const STEP_ERROR_LABELS: Partial> = { + client_id: 'Ulanyjy hökmany', + status: 'Status hökmany', + currency_type: 'Ýüztumanyň görnüşi hökmany', + province: 'Welaýat hökmany', + branch: 'Şahamça hökmany', + passport_first_name: 'Ady hökmany', + passport_last_name: 'Familiýasy hökmany', + phone: 'Telefon hökmany', + passport_series: 'Pasport seriýasy hökmany', + passport_number: 'Pasport nomeri hökmany', + payer_full_name: 'Doly ady hökmany', + payer_account_number: 'Goşun hasaby hökmany', + receiver_info: 'Kabul edijiniň maglumatlary hökmany', +} + // ─── Default state ──────────────────────────────────────────────────────────── const defaultState: FormState = { @@ -130,48 +179,355 @@ const defaultState: FormState = { upd_doc_passport_biometric: null, upd_doc_passport_old: null, } -// ─── Validation ─────────────────────────────────────────────────────────────── +// ─── Full validation (final submit) ────────────────────────────────────────── -function validate(form: FormState): FormErrors { +function validateAll(form: FormState): FormErrors { const errors: FormErrors = {} - if (!form.client_id) errors.client_id = 'Ulanyjy hökmany' - if (!form.status) errors.status = 'Status hökmany' - if (!form.currency_type) errors.currency_type = 'Ýüztumanyň görnüşi hökmany' - if (!form.province) errors.province = 'Welaýat hökmany' - if (!form.branch) errors.branch = 'Şahamça hökmany' - if (!form.passport_first_name) errors.passport_first_name = 'Ady hökmany' - if (!form.passport_last_name) errors.passport_last_name = 'Familiýasy hökmany' - if (!form.phone) errors.phone = 'Telefon hökmany' - if (!form.passport_series) errors.passport_series = 'Pasport seriýasy hökmany' - if (!form.passport_number) errors.passport_number = 'Pasport nomeri hökmany' - if (!form.payer_full_name) errors.payer_full_name = 'Ady Familiýasy Atasnyň ady hökmany' - if (!form.payer_account_number)errors.payer_account_number= 'Goşun hasaby hökmany' - if (!form.receiver_info) errors.receiver_info = 'Töleg kabul edijiniň maglumatlary hökmany' + Object.entries(STEP_ERROR_LABELS).forEach(([key, msg]) => { + if (!form[key as keyof FormState]) errors[key as keyof FormState] = msg + }) return errors } -// ─── Section wrapper ────────────────────────────────────────────────────────── +function validateStep(form: FormState, stepId: StepId): FormErrors { + const fields = STEP_REQUIRED_FIELDS[stepId] ?? [] + const errors: FormErrors = {} + fields.forEach((f) => { + if (!form[f]) errors[f] = STEP_ERROR_LABELS[f] ?? 'Hökmany' + }) + return errors +} -function Section({ title, children }: { title: string; children: React.ReactNode }) { +// ─── Bento layout primitive ─────────────────────────────────────────────────── + +function BentoGrid({ + cols = 2, + children, +}: { + cols?: 1 | 2 | 3 + children: React.ReactNode +}) { + const colClass = { 1: 'grid-cols-1', 2: 'grid-cols-1 sm:grid-cols-2', 3: 'grid-cols-1 sm:grid-cols-3' }[cols] return ( -
+
+ {children} +
+ ) +} + +function BentoCard({ + title, + children, + span, +}: { + title?: string + children: React.ReactNode + span?: 'full' +}) { + return ( +
{title && ( -

{title}

+

+ {title} +

)} {children} -
+
+ ) +} + +// ─── Step content panels ────────────────────────────────────────────────────── + +function StepGeneral({ + form, errors, set, +}: { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void +}) { + return ( + + + set('client_id', v)} + options={[]} + placeholder="Saýlamak üçin basyň" + error={errors.client_id} + required + /> + + + + set('status', v)} + options={STATUS_OPTIONS} + error={errors.status} + required + /> + + + + set('currency_type', v)} + options={CURRENCY_OPTIONS} + error={errors.currency_type} + required + /> + + + + set('note', v)} + placeholder="Bellik..." + rows={2} + /> + + + ) +} + +function StepLocation({ + form, errors, set, +}: { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void +}) { + return ( + + + { set('province', v); set('branch', '') }} + options={PROVINCE_OPTIONS} + error={errors.province} + required + /> +

+ Welaýaty saýlasaňyz şahamçalar güncellenar. +

+
+ + + set('branch', v)} + options={[]} // filtered by province + placeholder="Saýlamak üçin basyň" + error={errors.branch} + required + /> + +
+ ) +} + +function StepPersonal({ + form, errors, set, +}: { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void +}) { + return ( + + + set('passport_last_name', v)} + placeholder="NURYYEW" + error={errors.passport_last_name} + required + /> + set('passport_first_name', v)} + placeholder="HAÝDAR" + error={errors.passport_first_name} + required + /> + + + + set('phone', v)} + error={errors.phone} + required + /> + set('email', v)} + placeholder="email@example.com" + /> + + + + set('home_address', v)} + placeholder="Köçe, jaý belgisi..." + /> + + + ) +} + +function StepPayment({ + form, errors, set, +}: { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void +}) { + return ( + + + set('passport_series', v)} + options={PASSPORT_SERIES_OPTIONS} + error={errors.passport_series} + required + /> + set('passport_number', v)} + placeholder="A123456" + error={errors.passport_number} + required + /> + + + + set('payer_full_name', v)} + placeholder="Doly ady..." + error={errors.payer_full_name} + required + /> + set('payer_account_number', v)} + placeholder="1234 5678 ..." + error={errors.payer_account_number} + required + /> + + + + set('receiver_info', v)} + placeholder="Kabul ediji bank, hasap, Swift..." + rows={3} + error={errors.receiver_info} + required + /> + + + ) +} + +function StepDocs({ + form, set, +}: { + form: FormState + set: (k: K, v: FormState[K]) => void +}) { + return ( + + +
+ {KABUL_DOCS.map(({ key, label }) => ( + set(key, f)} + fileValue={form[key] as File | null} + accept="image/*,.pdf" + /> + ))} +
+
+ + +
+ {UPGRAD_DOCS.map(({ key, label }) => ( + set(key, f)} + fileValue={form[key] as File | null} + accept="image/*,.pdf" + /> + ))} +
+
+
) } // ─── Component ──────────────────────────────────────────────────────────────── -export function IntlPaymentForm({ mode, initialData, onSubmit, isSubmitting }: IntlPaymentFormProps) { +export function IntlPaymentForm({ + mode, + initialData, + onSubmit, + isSubmitting, +}: IntlPaymentFormProps) { const { t } = useTranslation() const navigate = useNavigate() const [form, setForm] = useState(defaultState) const [errors, setErrors] = useState({}) + const [currentStep, setCurrentStep] = useState(0) + const [stepStatuses, setStepStatuses] = useState( + STEPS.map((_, i) => (i === 0 ? 'active' : 'idle')), + ) + // ── Populate in edit mode ── useEffect(() => { if (mode === 'edit' && initialData) { setForm({ @@ -200,18 +556,60 @@ export function IntlPaymentForm({ mode, initialData, onSubmit, isSubmitting }: I upd_doc_visa: null, upd_doc_acceptance_letter: null, upd_doc_passport_biometric: null, upd_doc_passport_old: null, }) + // Mark all non-doc steps done in edit mode so the user can jump freely + setStepStatuses(STEPS.map((_, i) => (i === 0 ? 'active' : i < 4 ? 'done' : 'idle'))) } }, [mode, initialData]) + // ── Field setter ── const set = (key: K, value: FormState[K]) => { setForm((prev) => ({ ...prev, [key]: value })) if (errors[key]) setErrors((prev) => ({ ...prev, [key]: undefined })) } + // ── Step navigation ── + const goStep = (idx: number) => { + if (idx < 0 || idx >= STEPS.length) return + setStepStatuses((prev) => { + const next = [...prev] + // going forward: mark current done + if (idx > currentStep) next[currentStep] = 'done' + next[idx] = 'active' + // going back: reset steps after target to idle (only those not yet done) + if (idx < currentStep) { + for (let i = idx + 1; i <= currentStep; i++) { + if (next[i] !== 'done') next[i] = 'idle' + } + } + return next + }) + setErrors({}) + setCurrentStep(idx) + } + + const handleNext = () => { + const stepId = STEPS[currentStep].id + const stepErrors = validateStep(form, stepId) + if (Object.keys(stepErrors).length > 0) { + setErrors(stepErrors) + setStepStatuses((prev) => { + const next = [...prev] + next[currentStep] = 'error' + return next + }) + return + } + if (currentStep === STEPS.length - 1) { + handleSubmit() + } else { + goStep(currentStep + 1) + } + } + const handleSubmit = () => { - const errs = validate(form) - if (Object.keys(errs).length > 0) { - setErrors(errs) + const allErrors = validateAll(form) + if (Object.keys(allErrors).length > 0) { + setErrors(allErrors) return } onSubmit({ @@ -221,243 +619,59 @@ export function IntlPaymentForm({ mode, initialData, onSubmit, isSubmitting }: I }) } + // ── StepBarCards data ── + const stepCardItems: StepCardItem[] = STEPS.map((s, i) => ({ + id: s.id, + title: s.title, + subtitle: s.subtitle, + status: stepStatuses[i], + icon: [User, MapPin, IdCard, CreditCard, Files][i], + })) + + const isLastStep = currentStep === STEPS.length - 1 + const title = mode === 'create' ? t('intlPayment.createTitle', 'Visa/Master tölegler (talyplar üçin) dörediň') : t('intlPayment.editTitle', 'Visa/Master tölegler (talyplar üçin) redaktirläň') - const submitLabel = mode === 'create' - ? t('intlPayment.createBtn', 'Visa/Master tölegler (talyplar üçin) dörediň') - : t('intlPayment.editBtn', 'Visa/Master tölegler (talyplar üçin) redaktirläň') + const submitLabel = isLastStep + ? (mode === 'create' + ? t('intlPayment.createBtn', 'Dörediň') + : t('intlPayment.editBtn', 'Redaktirläň')) + : undefined // not used on non-last steps return (

{title}

- {/* ── Status ────────────────────────────────────────────────────────── */} -
- set('client_id', v)} - options={[]} // Fetched from clients API - placeholder="Saýlamak üçin basyň" - error={errors.client_id} - required + {/* ── Step bar ────────────────────────────────────────────────────── */} +
+ { + // Allow jumping only to done/active steps + if (stepStatuses[i] !== 'idle') goStep(i) + }} /> - set('status', v)} - options={STATUS_OPTIONS} - error={errors.status} - required - /> - set('note', v)} - placeholder="Bellik" - rows={2} - /> -
+
- {/* ── Ýüztumanyň görnüşi ───────────────────────────────────────────── */} -
- set('currency_type', v)} - options={CURRENCY_OPTIONS} - error={errors.currency_type} - required - /> -
- - {/* ── Lokasiýa ─────────────────────────────────────────────────────── */} -
-
- { set('province', v); set('branch', '') }} - options={PROVINCE_OPTIONS} - error={errors.province} - required - /> - set('branch', v)} - options={[]} // Fetched from branches API filtered by province - placeholder="Saýlamak üçin basyň" - error={errors.branch} - required - /> -
-
- - {/* ── Şahsy maglumatlar ─────────────────────────────────────────────── */} -
-
- set('passport_last_name', v)} - options={[]} - placeholder="Pasportdaky familýa" - error={errors.passport_last_name} - required - /> - set('passport_first_name', v)} - placeholder="Pasportdaky ady" - error={errors.passport_first_name} - required - /> -
-
- set('phone', v)} - error={errors.phone} - required - /> - set('email', v)} - placeholder="E-poçta" - /> -
- set('home_address', v)} - placeholder="Häzirki ýaşyş ýeri" - /> -
- - {/* ── Töleg upgradyjynyň maglumatlary ──────────────────────────────── */} -
-
- set('passport_series', v)} - options={PASSPORT_SERIES_OPTIONS} - error={errors.passport_series} - required - /> - set('passport_number', v)} - placeholder="Pasport nomeri" - error={errors.passport_number} - required - /> -
- set('payer_full_name', v)} - placeholder="Ady Familiýasy Atasnyň ady" - error={errors.payer_full_name} - required - /> - set('payer_account_number', v)} - placeholder="Goşun hasaby" - error={errors.payer_account_number} - required - /> -
- - {/* ── Töleg kabul edijiniň maglumatlary ────────────────────────────── */} -
- set('receiver_info', v)} - placeholder="Saňa ger" - rows={3} - error={errors.receiver_info} - required - /> -
- - {/* ── Kabul ediji talyp boyunca resminamalar ────────────────────────── */} -
-
- {KABUL_DOCS.map(({ key, label }) => ( - set(key, f)} - fileValue={form[key] as File | null} - accept="image/*,.pdf" - /> - ))} -
-
- - {/* ── Upgradyý boyunca resminamalar ─────────────────────────────────── */} -
-
- {UPGRAD_DOCS.map(({ key, label }) => ( - set(key, f)} - fileValue={form[key] as File | null} - accept="image/*,.pdf" - /> - ))} -
-
+ {/* ── Step content ─────────────────────────────────────────────────── */} + {STEPS[currentStep].id === 'general' && } + {STEPS[currentStep].id === 'location' && } + {STEPS[currentStep].id === 'personal' && } + {STEPS[currentStep].id === 'payment' && } + {STEPS[currentStep].id === 'docs' && } {/* ── Actions ───────────────────────────────────────────────────────── */} -
- - -
+ navigate('/intl-payments/visa-master')} + onPrev={currentStep > 0 ? () => goStep(currentStep - 1) : undefined} + onNext={!isLastStep ? handleNext : undefined} + showSubmit={isLastStep} + onSubmit={isLastStep ? handleNext : undefined} + submitLabel={submitLabel} + /> ) -} +} \ No newline at end of file diff --git a/src/features/visaMasterSberSettings/components/visaMasterSberSettingsForm.tsx b/src/features/visaMasterSberSettings/components/visaMasterSberSettingsForm.tsx index 7bbfb30..708509c 100644 --- a/src/features/visaMasterSberSettings/components/visaMasterSberSettingsForm.tsx +++ b/src/features/visaMasterSberSettings/components/visaMasterSberSettingsForm.tsx @@ -4,7 +4,7 @@ import { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' import { FormInput } from '@/components/formInput' -import { Button } from '@/components/ui/button' +import { FormActions } from '@/components/formActions' import { type VisaMasterSetting } from '../api/visaMasterSberSettingsApi' import { useCreateVisaMasterSetting, @@ -162,29 +162,16 @@ export function VisaMasterSettingForm({ /> - {/* Footer */} -
- - -
+ ) } \ No newline at end of file diff --git a/src/pages/internationalPayments/sberPaymentsCreate/index.tsx b/src/pages/internationalPayments/sberPaymentsCreate/index.tsx index 07a5737..179f50c 100644 --- a/src/pages/internationalPayments/sberPaymentsCreate/index.tsx +++ b/src/pages/internationalPayments/sberPaymentsCreate/index.tsx @@ -1,4 +1,3 @@ -'use client' import { SberPaymentForm } from '@/features/sberPayments/components/sberPaymentsForm'