From dfb8e0b322e1e58e7eccbaed9cfe3fb7f33049d1 Mon Sep 17 00:00:00 2001 From: "@jcarymuhammedow" Date: Fri, 15 May 2026 12:15:27 +0500 Subject: [PATCH] fixed some page ui --- .env | 2 + PROJECT_STANDARDS.md | 12 + src/app/providers/QueryProvider.tsx | 33 +- src/app/router/index.tsx | 133 +- src/app/store/authStore.ts | 38 +- .../cardPins/components/cardPinForm.tsx | 884 ++++++----- .../cardRequisites/api/cardRequisitesApi.ts | 123 +- .../components/cardRequisiteForm.tsx | 1033 +++++++------ .../components/orderNewCardForm.tsx | 1337 +++++++++-------- src/lib/api/client.ts | 101 +- .../sberPaymentsView/index.tsx | 593 +++----- .../visaMasterPaymentsView/index.tsx | 370 ++--- src/pages/notFoundPage/index.tsx | 42 + 13 files changed, 2498 insertions(+), 2203 deletions(-) create mode 100644 .env create mode 100644 src/pages/notFoundPage/index.tsx diff --git a/.env b/.env new file mode 100644 index 0000000..db87a9b --- /dev/null +++ b/.env @@ -0,0 +1,2 @@ +VITE_API_URL=/api +VITE_ENABLE_MOCKS=true diff --git a/PROJECT_STANDARDS.md b/PROJECT_STANDARDS.md index 3b77b57..41bb536 100644 --- a/PROJECT_STANDARDS.md +++ b/PROJECT_STANDARDS.md @@ -95,3 +95,15 @@ src/ [Feature]CreatePage.tsx ← <[Feature]Form mode="create" /> [Feature]EditPage.tsx ← id fetch → <[Feature]Form mode="edit" initialData={data} loanOrderId={id} /> ``` +8. **Hata Yönetimi Kuralları:** + - Custom hook'lar veya API istekleri yazarken, hatalar zaten merkezi QueryCache ve MutationCache tarafından yakalandığı için hook içinde tekrar toast.error() yazma (kod tekrarını önle). + - İstisnai olarak, bir hatanın ekrana toast basmasını istemiyorsan, query veya mutation tanımına meta: { silent: true } parametresini geç. + - Kod bloklarında asla ham try-catch kullanarak hataları yutma (catch (e) { } boş bırakılamaz). Hata yutulacaksa bile konsola console.error ile basılmalı veya log servisine yönlendirilmelidir. +9. **Senior Authentication (Refresh Token & Session) Kuralları:** + - **Giriş (Login):** API'den dönen `token` ve `user` verilerini `authStore.setAuth()` ile zustand state'ine kaydet. + - **İstekler (Requests):** `axios` client'ı otomatik olarak zustand'dan token çeker ve `Authorization: Bearer ` header'ını ekler. + - **401 Unauthorized:** Kullanıcı başka bir yerde oturum açar veya token süresi solar ve istek 401 dönerse: + 1. **Otomatik Yenileme (Auto-Refresh):** Interceptor, durumu yakalar ve gizlice yeni token almaya çalışır. + 2. **Çakışma Önleme:** Aynı anda birden fazla 401 gelirse, `isRefreshing` bayrağı ile diğer istekler beklemede tutulur. + - **Başarısız Refresh:** Yeni token alınamazsa (`refreshToken` hata dönerse), sistem kullanıcıyı otomatik olarak çıkışa zorlar (`logout()`) ve kullanıcıyı Login sayfasına yönlendirir. + - **403 Forbidden:** Kullanıcının o sayfaya erişim izni yoksa (Rol yetkisi eksik), toast ile uyarı verilir ancak kullanıcı aynı sayfada kalır (Kritik sayfadan atılmaz). diff --git a/src/app/providers/QueryProvider.tsx b/src/app/providers/QueryProvider.tsx index c43d768..9032a92 100644 --- a/src/app/providers/QueryProvider.tsx +++ b/src/app/providers/QueryProvider.tsx @@ -1,12 +1,39 @@ -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { QueryClient, QueryClientProvider, QueryCache, MutationCache } from '@tanstack/react-query' import type { ReactNode } from 'react' +import { toast } from 'sonner' +import i18next from 'i18next' const queryClient = new QueryClient({ + queryCache: new QueryCache({ + onError: (error: any, query) => { + // Eğer sorguya özel gizlilik istenmediyse tekilleştirilmiş toast göster + if (query.meta?.silent !== true) { + const serverMessage = error?.response?.data?.message + toast.error(serverMessage || i18next.t('errors.fetchFailed'), { + id: 'global-query-error', // Aynı ID'li toast'lar üst üste binmez + }) + } + }, + }), + mutationCache: new MutationCache({ + onError: (error: any, _variables, _context, mutation) => { + if (mutation.meta?.silent !== true) { + const serverMessage = error?.response?.data?.message + toast.error(serverMessage || i18next.t('errors.actionFailed'), { + id: 'global-mutation-error', + }) + } + }, + }), defaultOptions: { queries: { staleTime: 1000 * 60 * 5, // 5 min gcTime: 1000 * 60 * 10, // 10 min - retry: 1, + retry: (failureCount, error: any) => { + // Kritik auth veya bulunamadı hatalarında boşa retry atıp ağı yorma + if ([401, 403, 404].includes(error.response?.status)) return false + return failureCount < 1 + }, refetchOnWindowFocus: false, }, mutations: { @@ -25,4 +52,4 @@ export function QueryProvider({ children }: QueryProviderProps) { {children} ) -} +} \ No newline at end of file diff --git a/src/app/router/index.tsx b/src/app/router/index.tsx index fc5bed7..d3345b2 100644 --- a/src/app/router/index.tsx +++ b/src/app/router/index.tsx @@ -3,87 +3,44 @@ import { createBrowserRouter, Navigate, Outlet } from "react-router-dom"; import { useAuthStore } from "../store/authStore"; import { Spinner } from "@/components/ui/spinner"; import { DashboardLayout } from "@/layouts/DashboardLayout"; +import NotFoundPage from "@/pages/notFoundPage"; const LoginPage = lazy(() => import("@/pages/login")); const DashboardPage = lazy(() => import("@/pages/dashboard")); const LoanOrdersPage = lazy(() => import("@/pages/loanDepartment/loanOrders")); -const LoanOrderMobilesPage = lazy( - () => import("@/pages/loanDepartment/loanOrderMobile"), -); -const LoanRemainingPage = lazy( - () => import("@/pages/loanDepartment/loanRemaining"), -); -const LoanRemainingCreatePage = lazy( - () => import("@/pages/loanDepartment/loanRemainingCreate"), -); -const LoanRemainingViewPage = lazy( - () => import("@/pages/loanDepartment/loanRemainingView"), -); -const LoanRemainingEditPage = lazy( - () => import("@/pages/loanDepartment/loanRemainingEdit"), -); -const LoanPaidOffLettersPage = lazy( - () => import("@/pages/loanDepartment/loanPaidOffLetters"), -); -const LoanOrderCreatePage = lazy( - () => import("@/pages/loanDepartment/loanOrderCreate"), -); -const LoanOrderViewPage = lazy( - () => import("@/pages/loanDepartment/loanOrderView"), -); -const LoanOrderMobileViewPage = lazy( - () => import("@/pages/loanDepartment/loanOrderMobileView"), -); -const LoanOrderMobileEditPage = lazy( - () => import("@/pages/loanDepartment/loanOrderMobileEdit"), -); -const LoanOrderMobileCreatePage = lazy( - () => import("@/pages/loanDepartment/loanOrderMobileCreate"), -); -const LoanOrderEditPage = lazy( - () => import("@/pages/loanDepartment/loanOrderEdit"), -); -const OrderNewCardPage = lazy( - () => import("@/pages/cardDepartment/orderNewCard"), -); -const OrderNewCardCreatePage = lazy( - () => import("@/pages/cardDepartment/orderNewCardCreate"), -); -const OrderNewCardViewPage = lazy( - () => import("@/pages/cardDepartment/orderNewCardView"), -); -const OrderNewCardEditPage = lazy( - () => import("@/pages/cardDepartment/orderNewCardEdit"), -); -const CardTransactionsPage = lazy( - () => import("@/pages/cardDepartment/cardTransactions"), -); -const CardTransactionViewPage = lazy( - () => import("@/pages/cardDepartment/cardTransactionsView"), -); -const CardTransactionCreatePage = lazy( - () => import("@/pages/cardDepartment/cardTransactionsCreate"), -); -const CardTransactionEditPage = lazy( - () => import("@/pages/cardDepartment/cardTransactionsEdit"), -); +const LoanOrderMobilesPage = lazy(() => import("@/pages/loanDepartment/loanOrderMobile")); +const LoanRemainingPage = lazy(() => import("@/pages/loanDepartment/loanRemaining")); +const LoanRemainingCreatePage = lazy(() => import("@/pages/loanDepartment/loanRemainingCreate")); +const LoanRemainingViewPage = lazy(() => import("@/pages/loanDepartment/loanRemainingView")); +const LoanRemainingEditPage = lazy(() => import("@/pages/loanDepartment/loanRemainingEdit")); +const LoanPaidOffLettersPage = lazy(() => import("@/pages/loanDepartment/loanPaidOffLetters")); +const LoanOrderCreatePage = lazy(() => import("@/pages/loanDepartment/loanOrderCreate")); +const LoanOrderViewPage = lazy(() => import("@/pages/loanDepartment/loanOrderView")); +const LoanOrderMobileViewPage = lazy(() => import("@/pages/loanDepartment/loanOrderMobileView")); +const LoanOrderMobileEditPage = lazy(() => import("@/pages/loanDepartment/loanOrderMobileEdit")); +const LoanOrderMobileCreatePage = lazy(() => import("@/pages/loanDepartment/loanOrderMobileCreate")); +const LoanOrderEditPage = lazy(() => import("@/pages/loanDepartment/loanOrderEdit")); + +const OrderNewCardPage = lazy(() => import("@/pages/cardDepartment/orderNewCard")); +const OrderNewCardCreatePage = lazy(() => import("@/pages/cardDepartment/orderNewCardCreate")); +const OrderNewCardViewPage = lazy(() => import("@/pages/cardDepartment/orderNewCardView")); +const OrderNewCardEditPage = lazy(() => import("@/pages/cardDepartment/orderNewCardEdit")); + +const CardTransactionsPage = lazy(() => import("@/pages/cardDepartment/cardTransactions")); +const CardTransactionViewPage = lazy(() => import("@/pages/cardDepartment/cardTransactionsView")); +const CardTransactionCreatePage = lazy(() => import("@/pages/cardDepartment/cardTransactionsCreate")); +const CardTransactionEditPage = lazy(() => import("@/pages/cardDepartment/cardTransactionsEdit")); + +const CardRequisitesPage = lazy(() => import("@/pages/cardDepartment/cardRequisites")); +const CardRequisiteViewPage = lazy(() => import("@/pages/cardDepartment/cardRequisitesView")); +const CardRequisiteCreatePage = lazy(() => import("@/pages/cardDepartment/cardRequisitesCreate")); +const CardRequisiteEditPage = lazy(() => import("@/pages/cardDepartment/cardRequisitesEdit")); -const CardRequisitesPage = lazy( - () => import("@/pages/cardDepartment/cardRequisites"), -); -const CardRequisiteViewPage = lazy( - () => import("@/pages/cardDepartment/cardRequisitesView"), -); -const CardRequisiteCreatePage = lazy( - () => import("@/pages/cardDepartment/cardRequisitesCreate"), -); -const CardRequisiteEditPage = lazy( - () => import("@/pages/cardDepartment/cardRequisitesEdit"), -); const CardBalancePage = lazy(() => import("@/pages/cardDepartment/cardBalance")); const CardBalanceCreatePage = lazy(() => import("@/pages/cardDepartment/cardBalanceCreate")); const CardBalanceViewPage = lazy(() => import("@/pages/cardDepartment/cardBalanceView")); const CardBalanceEditPage = lazy(() => import("@/pages/cardDepartment/cardBalanceEdit")); + const CardPinsPage = lazy(() => import("@/pages/cardDepartment/cardPins")); const CardPinsCreatePage = lazy(() => import("@/pages/cardDepartment/cardPinsCreate")); const CardPinsViewPage = lazy(() => import("@/pages/cardDepartment/cardPinsView")); @@ -93,13 +50,12 @@ const VisaMasterPaymentsPage = lazy(() => import("@/pages/internationalPayments/ const VisaMasterPaymentCreatePage = lazy(() => import("@/pages/internationalPayments/visaMasterPaymentsCreate")); const VisaMasterPaymentViewPage = lazy(() => import("@/pages/internationalPayments/visaMasterPaymentsView")); const VisaMasterPaymentEditPage = lazy(() => import("@/pages/internationalPayments/visaMasterPaymentsEdit")); + const SberPaymentPage = lazy(() => import("@/pages/internationalPayments/sberPayments")); const SberPaymentCreatePage = lazy(() => import("@/pages/internationalPayments/sberPaymentsCreate")); const SberPaymentViewPage = lazy(() => import("@/pages/internationalPayments/sberPaymentsView")); const SberPaymentEditPage = lazy(() => import("@/pages/internationalPayments/sberPaymentsEdit")); - - const OperatorsPage = lazy(() => import("@/pages/users/operators")); const OperatorCreatePage = lazy(() => import("@/pages/users/operatorsCreate")); const OperatorsViewPage = lazy(() => import("@/pages/users/operatorsView")); @@ -487,7 +443,8 @@ export const router = createBrowserRouter([ ), }, - { // Sidebar: /visa-master-payments + { + // Sidebar: /visa-master-payments path: "/visa-master", element: ( }> @@ -519,7 +476,8 @@ export const router = createBrowserRouter([ ), }, - { // Sidebar: /sber-payments + { + // Sidebar: /sber-payments path: "/sber-payments", element: ( }> @@ -551,7 +509,8 @@ export const router = createBrowserRouter([ ), }, - { // Sidebar: /operators + { + // Sidebar: /operators path: "/operators", element: ( }> @@ -583,7 +542,8 @@ export const router = createBrowserRouter([ ), }, - { // Sidebar: /all-users + { + // Sidebar: /all-users path: "/all-users", element: ( }> @@ -615,7 +575,8 @@ export const router = createBrowserRouter([ ), }, - { // Sidebar: /clients + { + // Sidebar: /clients path: "/clients", element: ( }> @@ -647,7 +608,8 @@ export const router = createBrowserRouter([ ), }, - { // Sidebar: /currencies-rates + { + // Sidebar: /currencies-rates path: "/currency-rates", element: ( }> @@ -679,7 +641,8 @@ export const router = createBrowserRouter([ ), }, - { // Sidebar: /visa-master-sber-settings + { + // Sidebar: /visa-master-sber-settings path: "/visa-master-sber-settings", element: ( }> @@ -911,7 +874,8 @@ export const router = createBrowserRouter([ ), }, - { // Sidebar: /settings/location/districts + { + // Sidebar: /settings/location/districts path: "/settings/location/districts", element: ( }> @@ -943,7 +907,8 @@ export const router = createBrowserRouter([ ), }, - { // Sidebar: /settings/location/branches + { + // Sidebar: /settings/location/branches path: "/settings/location/branches", element: ( }> @@ -981,6 +946,6 @@ export const router = createBrowserRouter([ }, { path: "*", - element: , + element: , }, ]); diff --git a/src/app/store/authStore.ts b/src/app/store/authStore.ts index ffc61b4..d939c4d 100644 --- a/src/app/store/authStore.ts +++ b/src/app/store/authStore.ts @@ -1,5 +1,6 @@ import { create } from 'zustand' import { persist } from 'zustand/middleware' +import axios from 'axios' export interface AuthUser { id: string @@ -15,21 +16,54 @@ interface AuthState { isAuthenticated: boolean setAuth: (token: string, user: AuthUser) => void clearAuth: () => void + logout: () => void // Eklendi + refreshToken: () => Promise // Eklendi } export const useAuthStore = create()( persist( - (set) => ({ + (set, get) => ({ token: null, user: null, isAuthenticated: false, + setAuth: (token, user) => set({ token, user, isAuthenticated: true }), + clearAuth: () => set({ token: null, user: null, isAuthenticated: false }), + + logout: () => { + // Çıkış yapıldığında hem local state'i temizle hem de gerekirse API'ye logout isteği at + get().clearAuth() + }, + + refreshToken: async () => { + try { + // Interceptor dairesel bağımlılığı bozmasın diye doğrudan bağımsız axios çağrısı yapıyoruz + const response = await axios.post<{ token: string }>( + `${import.meta.env.VITE_API_BASE_URL}/auth/refresh`, + {}, + { + headers: { + Authorization: `Bearer ${get().token}`, // Mevcut süresi dolmuş token'ı gönderiyoruz + }, + } + ) + + const newToken = response.data.token + // Yeni token'ı store'a kaydet + set((state) => ({ ...state, token: newToken })) + return newToken + } catch (error) { + // Eğer refresh token da patlarsa her şeyi sıfırla + get().clearAuth() + throw error + } + } }), { name: 'tbbank-auth', }, ), -) +) \ No newline at end of file diff --git a/src/features/cardPins/components/cardPinForm.tsx b/src/features/cardPins/components/cardPinForm.tsx index dde4dfb..2f0b432 100644 --- a/src/features/cardPins/components/cardPinForm.tsx +++ b/src/features/cardPins/components/cardPinForm.tsx @@ -1,8 +1,10 @@ -import { useState, useEffect } from 'react' +import { useState, useCallback, useMemo, 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 type { LucideIcon } from 'lucide-react' + import { FormInput } from '@/components/formInput' import { FormActions } from '@/components/formActions' import { StepBarCards, type StepCardItem } from '@/components/stepBarV2' @@ -38,223 +40,502 @@ 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 ──────────────────────────────────────────────────────────────── const STATUS_OPTIONS = [ - { value: 'pending', label: 'Garaşylýar' }, + { value: 'pending', label: 'Garaşylýar' }, { value: 'approved', label: 'Tassyklandy' }, - { value: 'rejected', label: 'Ret edildi' }, + { value: 'rejected', label: 'Ret edildi' }, ] const CARD_TYPE_OPTIONS = [ { value: 'altyn_asyr', label: 'Altyn Asyr' }, - { value: 'visa', label: 'Visa' }, - { value: 'mastercard', label: 'MasterCard' }, + { value: 'visa', label: 'Visa' }, + { value: 'mastercard', label: 'MasterCard' }, ] const PASSPORT_SERIES_OPTIONS = [ - { value: 'I', label: 'I' }, - { value: 'II', label: 'II' }, - { value: 'I-MR', label: 'I-MR' }, + { value: 'I', label: 'I' }, + { value: 'II', label: 'II' }, + { value: 'I-MR', label: 'I-MR' }, { value: 'II-MR', label: 'II-MR' }, ] const PROVINCE_OPTIONS = [ { value: 'ashgabat', label: 'Aşgabat' }, - { value: 'mary', label: 'Mary' }, + { value: 'mary', label: 'Mary' }, { value: 'dasoguz', label: 'Daşoguz' }, - { value: 'lebap', label: 'Lebap' }, - { value: 'balkan', label: 'Balkan' }, - { value: 'ahal', label: 'Ahal' }, + { value: 'lebap', label: 'Lebap' }, + { value: 'balkan', label: 'Balkan' }, + { value: 'ahal', label: 'Ahal' }, ] -// ─── Default state ──────────────────────────────────────────────────────────── - -const defaultState: FormState = { - status: 'pending', - note: '', - card_type: '', - card_number: '', - province: '', - branch: '', - first_name: '', - last_name: '', - father_name: '', - birth_date: '', - phone: '', - passport_series: '', - passport_number: '', - passport_file_1: null, - passport_file_2: null, - passport_file_3: null, - passport_file_4: null, +const INITIAL_STATE: FormState = { + status: 'pending', note: '', card_type: '', card_number: '', + province: '', branch: '', first_name: '', last_name: '', father_name: '', + birth_date: '', phone: '', passport_series: '', passport_number: '', + passport_file_1: null, passport_file_2: null, + passport_file_3: null, passport_file_4: null, } -// ─── Validation ─────────────────────────────────────────────────────────────── - -function validate( - form: FormState, - mode: 'create' | 'edit', - stepIndex?: number, -): FormErrors { - const allErrors: FormErrors = {} - - 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) 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' +function mapToFormState(data: CardPinItem): FormState { + return { + status: data.status ?? 'pending', + note: data.note ?? '', + card_type: data.card_type ?? '', + card_number: data.card_number ?? '', + province: data.province ?? '', + branch: data.branch ?? '', + first_name: data.first_name ?? '', + last_name: data.last_name ?? '', + father_name: data.father_name ?? '', + birth_date: data.birth_date ?? '', + phone: data.phone ?? '', + passport_series: data.passport_series ?? '', + passport_number: data.passport_number ?? '', + passport_file_1: null, passport_file_2: null, + passport_file_3: null, passport_file_4: null, } - - 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 ────────────────────────────────────────────────────────── +// ─── Step definitions ───────────────────────────────────────────────────────── + +interface StepDef { + id: string + titleKey: string + titleFallback: string + subtitle: string + icon: LucideIcon + validate: (form: FormState, mode: 'create' | 'edit') => FormErrors +} + +const STEPS: StepDef[] = [ + { + id: 'card', + titleKey: 'cardPin.step.card', + titleFallback: 'Kart', + subtitle: 'Görnüş & lokasiýa', + icon: CreditCard, + validate: (form) => { + const e: FormErrors = {} + if (!form.status) e.status = 'Status hökmany' + if (!form.card_type) e.card_type = 'Kart görnüşi hökmany' + if (!form.card_number) e.card_number = 'Kart belgisi hökmany' + if (!form.province) e.province = 'Welaýat hökmany' + if (!form.branch) e.branch = 'Şahamça hökmany' + return e + }, + }, + { + id: 'personal', + titleKey: 'cardPin.step.personal', + titleFallback: 'Şahsy', + subtitle: 'Maglumatlar', + icon: User, + validate: (form) => { + const e: FormErrors = {} + if (!form.first_name) e.first_name = 'Ady hökmany' + if (!form.last_name) e.last_name = 'Familiýasy hökmany' + if (!form.birth_date) e.birth_date = 'Doglan güni hökmany' + if (!form.phone) e.phone = 'Telefon hökmany' + return e + }, + }, + { + id: 'passport', + titleKey: 'cardPin.step.passport', + titleFallback: 'Pasport', + subtitle: 'Resminamalar', + icon: FileText, + validate: (form, mode) => { + const e: FormErrors = {} + if (!form.passport_series) e.passport_series = 'Pasport seriýasy hökmany' + if (!form.passport_number) e.passport_number = 'Pasport belgisi hökmany' + if (mode === 'create') { + if (!form.passport_file_1) e.passport_file_1 = 'Pasport (sahypa 1) hökmany' + if (!form.passport_file_2) e.passport_file_2 = 'Pasport (2-3-nji sahypa) hökmany' + if (!form.passport_file_3) e.passport_file_3 = 'Pasport (8-9 sahypa) hökmany' + if (!form.passport_file_4) e.passport_file_4 = 'Pasport (32-nji sahypa) hökmany' + } + return e + }, + }, +] + +// ─── 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' : '' -function Section({ title, children }: { title?: string; children: React.ReactNode }) { return ( -
+
{title && ( -
-

{title}

-
+

+ {title} +

)} -
{children}
+ {children}
) } -// ─── Component ──────────────────────────────────────────────────────────────── +// ─── Shared step content props ──────────────────────────────────────────────── + +interface StepContentProps { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void +} + +// ─── Step panels ────────────────────────────────────────────────────────────── + +function StepCard({ form, errors, set }: StepContentProps) { + return ( +
+ + + set('status', v)} + options={STATUS_OPTIONS} + error={errors.status} + placeholder="Saýlaň" + /> + + + set('note', v)} + placeholder="Bellik..." + /> + + + + + + set('card_type', v)} + options={CARD_TYPE_OPTIONS} + placeholder="Saýlamak üçin basyň" + error={errors.card_type} + /> + set('card_number', v)} + placeholder="Kart belgisi" + error={errors.card_number} + /> + + + + { set('province', v); set('branch', '') }} + options={PROVINCE_OPTIONS} + placeholder="Saýlamak üçin basyň" + error={errors.province} + /> + set('branch', v)} + options={[]} + placeholder="Saýlamak üçin basyň" + disabled={!form.province} + error={errors.branch} + /> + + +
+ ) +} + +function StepPersonal({ form, errors, set }: StepContentProps) { + return ( +
+ + + set('first_name', v)} + placeholder="Ady" error={errors.first_name} + /> + + + set('last_name', v)} + placeholder="Familiýasy" error={errors.last_name} + /> + + + set('father_name', v)} + placeholder="Atasynyň ady" + /> + + + + + + set('birth_date', v)} + error={errors.birth_date} + /> + + + set('phone', v)} + error={errors.phone} + /> + + +
+ ) +} + +function StepPassport({ form, errors, set, mode, initialData }: StepContentProps & { + mode: 'create' | 'edit' + initialData?: CardPinItem +}) { + const existingFiles = + mode === 'edit' && initialData + ? [ + { url: initialData.passport_file_1, label: 'Pasport (sahypa 1)' }, + { url: initialData.passport_file_2, label: 'Pasport (2-3-nji sahypa)' }, + { url: initialData.passport_file_3, label: 'Pasport (8-9 sahypa)' }, + { url: initialData.passport_file_4, label: 'Pasport (32-nji sahypa)' }, + ].filter((f): f is { url: string; label: string } => !!f.url) + : [] + + return ( +
+ + + set('passport_series', v)} + options={PASSPORT_SERIES_OPTIONS} + placeholder="Saýlamak üçin basyň" + error={errors.passport_series} + /> + + + set('passport_number', v)} + placeholder="Pasport belgisi" + error={errors.passport_number} + /> + + + + {existingFiles.length > 0 && ( + + {existingFiles.map(({ url, label }) => ( + + + Faýly gör + + + ))} + + )} + + + + set('passport_file_1', f)} + error={errors.passport_file_1} + /> + + + set('passport_file_2', f)} + error={errors.passport_file_2} + /> + + + set('passport_file_3', f)} + error={errors.passport_file_3} + /> + + + set('passport_file_4', f)} + error={errors.passport_file_4} + /> + + +
+ ) +} + +// ─── Main Component ─────────────────────────────────────────────────────────── export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardPinFormProps) { - const { t } = useTranslation() + const { t } = useTranslation() const navigate = useNavigate() - const [form, setForm] = useState(defaultState) + const [form, setForm] = useState(() => initialData ? mapToFormState(initialData) : INITIAL_STATE) const [errors, setErrors] = useState({}) - const [currentStep, setCurrentStep] = useState(0) - const [stepStatuses, setStepStatuses] = useState(['active', 'idle', 'idle']) + const [currentStep, setCurrentStep] = useState(0) + const [visited, setVisited] = useState>( + () => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set(), + ) useEffect(() => { - if (mode === 'edit' && initialData) { - setForm({ - status: initialData.status, - note: initialData.note ?? '', - card_type: initialData.card_type, - card_number: initialData.card_number, - province: initialData.province, - branch: initialData.branch, - first_name: initialData.first_name, - last_name: initialData.last_name, - father_name: initialData.father_name, - birth_date: initialData.birth_date, - phone: initialData.phone, - passport_series: initialData.passport_series, - passport_number: initialData.passport_number, - passport_file_1: null, - passport_file_2: null, - passport_file_3: null, - passport_file_4: null, - }) - } - }, [mode, initialData]) + if (initialData) setForm(mapToFormState(initialData)) + }, [initialData]) - const set = (key: K, value: FormState[K]) => { + // ── Computed step errors ─────────────────────────────────────────────────── + + const stepsWithErrors = useMemo(() => { + const out = new Set() + visited.forEach((i) => { + if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i) + }) + return out + }, [form, mode, visited]) + + // ── set helper ───────────────────────────────────────────────────────────── + + const set = useCallback((key: K, value: FormState[K]) => { setForm((prev) => ({ ...prev, [key]: value })) setErrors((prev) => ({ ...prev, [key]: undefined })) - } + }, []) - // ── Step navigation ──────────────────────────────────────────────────────── + const stepProps = useMemo(() => ({ form, errors, set }), [form, errors, set]) - const updateStatus = (index: number, status: StepStatus) => { - setStepStatuses((prev) => { - const next = [...prev] - next[index] = status - return next - }) - } + // ── Navigation ───────────────────────────────────────────────────────────── - const goToStep = (index: number) => { - updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'done') - updateStatus(index, 'active') - setCurrentStep(index) - window.scrollTo({ top: 0, behavior: 'smooth' }) - } + const markVisited = (i: number) => + setVisited((prev) => new Set([...prev, i])) const handleNext = () => { - const stepErrors = validate(form, mode, currentStep) - if (Object.keys(stepErrors).length > 0) { - setErrors((prev) => ({ ...prev, ...stepErrors })) - updateStatus(currentStep, 'error') + markVisited(currentStep) + const errs = STEPS[currentStep].validate(form, mode) + if (Object.keys(errs).length > 0) { + setErrors(errs) 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) + setErrors({}) + setCurrentStep(currentStep + 1) window.scrollTo({ top: 0, behavior: 'smooth' }) } - const handlePrev = () => { - const prev = currentStep - 1 - updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'idle') - updateStatus(prev, 'active') - setCurrentStep(prev) + const handleBack = () => { + markVisited(currentStep) + setErrors({}) + setCurrentStep(currentStep - 1) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + const handleGoTo = (i: number) => { + markVisited(currentStep) + setErrors({}) + setCurrentStep(i) window.scrollTo({ top: 0, behavior: 'smooth' }) } // ── Submit ───────────────────────────────────────────────────────────────── const handleSubmit = () => { - const allErrors = validate(form, mode) + setVisited(new Set(STEPS.map((_, i) => i))) + + const allErrors: FormErrors = {} + for (const step of STEPS) Object.assign(allErrors, step.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.') + 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 + } + } return } @@ -279,287 +560,56 @@ export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardP }) } - // ── Step bar items ───────────────────────────────────────────────────────── + // ── StepBar 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 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', + } + }) - 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äň') - - const submitLabel = mode === 'create' - ? t('cardPin.createBtn', 'Kart pin bukja dörediň') - : t('cardPin.editBtn', 'Kart pin bukja redaktirläň') + const isLastStep = currentStep === STEPS.length - 1 // ── Render ───────────────────────────────────────────────────────────────── return (
-

{title}

+ - {/* ── Step Bar ─────────────────────────────────────────────────────── */} + {/* 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 ─────────────────────────────────────── */} + {/* Step content */} + {currentStep === 0 && } + {currentStep === 1 && } {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 ──────────────────────────────────────────────────── */} + {/* Actions */} navigate('/card-pins')} - onPrev={!isFirstStep ? handlePrev : undefined} + onCancel={currentStep === 0 ? () => navigate('/card-pins') : undefined} + onPrev={currentStep > 0 ? handleBack : undefined} prevLabel={t('common.prev', 'Yza')} onNext={!isLastStep ? handleNext : undefined} nextLabel={t('common.next', 'Indiki')} showSubmit={isLastStep} - onSubmit={handleSubmit} - submitLabel={submitLabel} + onSubmit={isLastStep ? handleSubmit : undefined} + submitLabel={ + mode === 'create' + ? t('cardPin.createBtn', 'Kart pin bukja dörediň') + : t('cardPin.editBtn', 'Kart pin bukja redaktirläň') + } />
) diff --git a/src/features/cardRequisites/api/cardRequisitesApi.ts b/src/features/cardRequisites/api/cardRequisitesApi.ts index 113fc6d..791df13 100644 --- a/src/features/cardRequisites/api/cardRequisitesApi.ts +++ b/src/features/cardRequisites/api/cardRequisitesApi.ts @@ -25,7 +25,7 @@ export interface CardRequisite { // Personal first_name: string last_name: string - middle_name: string + middle_name?: string birth_date: string phone: string @@ -47,7 +47,7 @@ export interface CardRequisiteListResponse { export interface CreateCardRequisitePayload { status: CardRequisiteStatus - note: string + note?: string card_type: string card_number: string card_expiry_month: string @@ -56,7 +56,7 @@ export interface CreateCardRequisitePayload { branch_id: string first_name: string last_name: string - middle_name: string + middle_name?: string birth_date: string phone: string passport_series: string @@ -102,15 +102,132 @@ function buildFormData(payload: CreateCardRequisitePayload): FormData { return fd } +// ─── Mock data ───────────────────────────────────────────────────────────────── + +const MOCK_CARD_REQUISITES: CardRequisite[] = [ + { + id: '1', + status: 'pending', + note: '', + card_type: 'UZCARD', + card_number: '8600123456789012', + card_expiry_month: '12', + card_expiry_year: '28', + province_id: '1', + branch_id: '1', + province_name: 'Toshkent', + branch_name: 'Filial 1', + first_name: 'Ali', + last_name: 'Valiyev', + middle_name: 'Akbarovich', + birth_date: '1990-05-15', + phone: '+998901234567', + passport_series: 'AA', + passport_number: '1234567', + created_at: '2025-01-15T10:30:00Z', + }, + { + id: '2', + status: 'approved', + note: 'Approved', + card_type: 'HUMO', + card_number: '9860123456789012', + card_expiry_month: '05', + card_expiry_year: '27', + province_id: '2', + branch_id: '3', + province_name: 'Samarqand', + branch_name: 'Filial 3', + first_name: 'Bobur', + last_name: 'Karimov', + middle_name: 'Rustamovich', + birth_date: '1985-08-22', + phone: '+998907654321', + passport_series: 'AB', + passport_number: '7654321', + created_at: '2025-02-20T14:00:00Z', + }, + { + id: '3', + status: 'rejected', + note: 'Hujjatlar not\'g\'ri', + card_type: 'VISA', + card_number: '4400123456789012', + card_expiry_month: '08', + card_expiry_year: '26', + province_id: '3', + branch_id: '5', + province_name: 'Buxoro', + branch_name: 'Filial 5', + first_name: 'Dilorom', + last_name: 'Rahimova', + middle_name: 'Shavkatovna', + birth_date: '1995-11-02', + phone: '+998903334455', + passport_series: 'AC', + passport_number: '1122334', + created_at: '2025-03-10T09:15:00Z', + }, + { + id: '4', + status: 'pending', + note: '', + card_type: 'UZCARD', + card_number: '5300123456789012', + card_expiry_month: '01', + card_expiry_year: '30', + province_id: '4', + branch_id: '7', + province_name: 'Farg\'ona', + branch_name: 'Filial 7', + first_name: 'Elyor', + last_name: 'Toshmatov', + middle_name: 'Olimovich', + birth_date: '2000-03-18', + phone: '+998905556677', + passport_series: 'KA', + passport_number: '9988776', + created_at: '2025-04-05T16:45:00Z', + }, + { + id: '5', + status: 'approved', + note: 'Tasdiqlangan', + card_type: 'HUMO', + card_number: '6200123456789012', + card_expiry_month: '03', + card_expiry_year: '29', + province_id: '5', + branch_id: '9', + province_name: 'Namangan', + branch_name: 'Filial 9', + first_name: 'Gulnora', + last_name: 'Abdullayeva', + middle_name: 'Anvarovna', + birth_date: '1992-07-30', + phone: '+998908889900', + passport_series: 'KB', + passport_number: '5566778', + created_at: '2025-05-12T11:30:00Z', + }, +] + // ─── API functions ──────────────────────────────────────────────────────────── export const cardRequisitesApi = { getAll: async (params?: CardRequisiteListParams): Promise => { + // Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz: + return { data: MOCK_CARD_REQUISITES, total: MOCK_CARD_REQUISITES.length, page: params?.page || 1, per_page: params?.per_page || 10 } + const { data } = await apiClient.get('/card-requisites', { params }) return data }, getById: async (id: string): Promise => { + // Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz: + const mock = MOCK_CARD_REQUISITES.find(r => r.id === id) + if (mock) return mock + const { data } = await apiClient.get(`/card-requisites/${id}`) return data }, diff --git a/src/features/cardRequisites/components/cardRequisiteForm.tsx b/src/features/cardRequisites/components/cardRequisiteForm.tsx index c210ab1..2bf13ca 100644 --- a/src/features/cardRequisites/components/cardRequisiteForm.tsx +++ b/src/features/cardRequisites/components/cardRequisiteForm.tsx @@ -1,11 +1,13 @@ -import { useEffect, useState } from 'react' +import { useState, useCallback, useMemo, 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 type { LucideIcon } from 'lucide-react' + import { FormInput } from '@/components/formInput' import { FormActions } from '@/components/formActions' -import { StepBarCards, type StepCardItem } from '@/components//stepBarV2' +import { StepBarCards, type StepCardItem } from '@/components/stepBarV2' import type { CardRequisite, CardRequisiteStatus, CreateCardRequisitePayload } from '../api/cardRequisitesApi' import { useCreateCardRequisite, useUpdateCardRequisite } from '../hooks/useCardRequisites' @@ -33,88 +35,54 @@ interface FormState { phone: string passport_series: string passport_number: string -} - -interface FileState { passport_page1: File | null passport_page2_3: File | null passport_page8_9: File | null passport_page32: File | null } -interface FormErrors { - status?: string - card_type?: string - card_number?: string - card_expiry_month?: string - card_expiry_year?: string - province_id?: string - branch_id?: string - first_name?: string - last_name?: string - birth_date?: string - phone?: string - passport_series?: string - passport_number?: string - passport_page1?: string - passport_page2_3?: string - passport_page8_9?: string - 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'], -] +type FormErrors = Partial> // ─── Constants ──────────────────────────────────────────────────────────────── const STATUS_OPTIONS = [ - { value: 'pending', label: 'Garaşylýar' }, + { value: 'pending', label: 'Garaşylýar' }, { value: 'approved', label: 'Tassyklanan' }, - { value: 'rejected', label: 'Ret edilen' }, + { value: 'rejected', label: 'Ret edilen' }, ] const CARD_TYPE_OPTIONS = [ - { value: 'altyn_asyr', label: 'Altyn Asyr' }, - { value: 'visa', label: 'Visa' }, - { value: 'mastercard', label: 'MasterCard' }, + { value: 'altyn_asyr', label: 'Altyn Asyr' }, + { value: 'visa', label: 'Visa' }, + { value: 'mastercard', label: 'MasterCard' }, ] const PASSPORT_SERIES_OPTIONS = [ - { value: 'I-MR', label: 'I-MR' }, - { value: 'II-MR', label: 'II-MR' }, - { value: 'I-LB', label: 'I-LB' }, - { value: 'II-LB', label: 'II-LB' }, + { value: 'I-MR', label: 'I-MR' }, + { value: 'II-MR', label: 'II-MR' }, + { value: 'I-LB', label: 'I-LB' }, + { value: 'II-LB', label: 'II-LB' }, { value: 'III-LB', label: 'III-LB' }, - { value: 'A', label: 'A' }, - { value: 'B', label: 'B' }, + { value: 'A', label: 'A' }, + { value: 'B', label: 'B' }, ] const PROVINCE_OPTIONS = [ { value: '1', label: 'Aşgabat' }, - { value: '2', label: 'Ahal' }, - { value: '3', label: 'Balkan' }, + { value: '2', label: 'Ahal' }, + { value: '3', label: 'Balkan' }, { value: '4', label: 'Daşoguz' }, - { value: '5', label: 'Lebap' }, - { value: '6', label: 'Mary' }, + { value: '5', label: 'Lebap' }, + { value: '6', label: 'Mary' }, ] const BRANCH_OPTIONS: Record = { '1': [{ value: '11', label: 'Köpetdag' }, { value: '12', label: 'Çandybil' }, { value: '13', label: 'Büzmeyin' }], - '2': [{ value: '21', label: 'Änew' }, { value: '22', label: 'Tejen' }], + '2': [{ value: '21', label: 'Änew' }, { value: '22', label: 'Tejen' }], '3': [{ value: '31', label: 'Balkanabat' }, { value: '32', label: 'Türkmenbaşy' }], - '4': [{ value: '41', label: 'Daşoguz ş.' }, { value: '42', label: 'Köneürgenç' }], - '5': [{ value: '51', label: 'Türkmenabat' }, { value: '52', label: 'Hazar' }], - '6': [{ value: '61', label: 'Mary ş.' }, { value: '62', label: 'Ýolöten' }, { value: '63', label: 'Şatlyk' }], + '4': [{ value: '41', label: 'Daşoguz ş.' }, { value: '42', label: 'Köneürgenç' }], + '5': [{ value: '51', label: 'Türkmenabat' }, { value: '52', label: 'Hazar' }], + '6': [{ value: '61', label: 'Mary ş.' }, { value: '62', label: 'Ýolöten' }, { value: '63', label: 'Şatlyk' }], } const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => { @@ -127,216 +95,542 @@ const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => { return { value: year, label: year } }) -const EMPTY_FORM: FormState = { - status: 'pending', - note: '', - card_type: '', - card_number: '', - card_expiry_month: '', - card_expiry_year: '', - province_id: '', - branch_id: '', - first_name: '', - last_name: '', - middle_name: '', - birth_date: '', - phone: '', - passport_series: '', - passport_number: '', +const INITIAL_STATE: FormState = { + status: 'pending', note: '', card_type: '', card_number: '', + card_expiry_month: '', card_expiry_year: '', province_id: '', branch_id: '', + first_name: '', last_name: '', middle_name: '', birth_date: '', phone: '', + passport_series: '', passport_number: '', + passport_page1: null, passport_page2_3: null, + passport_page8_9: null, passport_page32: null, } -const EMPTY_FILES: FileState = { - passport_page1: null, - passport_page2_3: null, - passport_page8_9: null, - passport_page32: null, -} - -// ─── Validation ─────────────────────────────────────────────────────────────── - -function validate( - form: FormState, - files: FileState, - mode: 'create' | 'edit', - t: (k: string, fallback: string) => string, - stepIndex?: number, -): FormErrors { - const allErrors: FormErrors = {} - - 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') - - if (mode === 'create') { - 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') +function mapToFormState(data: CardRequisite): FormState { + return { + status: data.status ?? 'pending', + note: data.note ?? '', + card_type: data.card_type ?? '', + card_number: data.card_number ?? '', + card_expiry_month: data.card_expiry_month ?? '', + card_expiry_year: data.card_expiry_year ?? '', + province_id: data.province_id ?? '', + branch_id: data.branch_id ?? '', + first_name: data.first_name ?? '', + last_name: data.last_name ?? '', + middle_name: data.middle_name ?? '', + birth_date: data.birth_date ?? '', + phone: data.phone ?? '', + passport_series: data.passport_series ?? '', + passport_number: data.passport_number ?? '', + passport_page1: null, passport_page2_3: null, + passport_page8_9: null, passport_page32: null, } - - 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 wrapper ────────────────────────────────────────────────────────── +// ─── Step definitions ───────────────────────────────────────────────────────── + +interface StepDef { + id: string + titleKey: string + titleFallback: string + subtitle: string + icon: LucideIcon + validate: (form: FormState, mode: 'create' | 'edit') => FormErrors +} + +const STEPS: StepDef[] = [ + { + id: 'card', + titleKey: 'Card', + titleFallback: 'Kart', + subtitle: 'Görnüş & lokasiýa', + icon: CreditCard, + validate: (form) => { + const e: FormErrors = {} + if (!form.status) e.status = 'Status hökmanydyr' + if (!form.card_type) e.card_type = 'Görnüşi hökmanydyr' + if (!form.card_number) e.card_number = 'Kart belgisi hökmanydyr' + if (!form.card_expiry_month) e.card_expiry_month = 'Möhleti (aý) hökmanydyr' + if (!form.card_expiry_year) e.card_expiry_year = 'Möhleti (ýyl) hökmanydyr' + if (!form.province_id) e.province_id = 'Welaýat hökmanydyr' + if (!form.branch_id) e.branch_id = 'Şahamça hökmanydyr' + return e + }, + }, + { + id: 'personal', + titleKey: 'Personal', + titleFallback: 'Şahsy', + subtitle: 'At & telefon', + icon: User, + validate: (form) => { + const e: FormErrors = {} + if (!form.first_name) e.first_name = 'Ady hökmanydyr' + if (!form.last_name) e.last_name = 'Familiýasy hökmanydyr' + if (!form.birth_date) e.birth_date = 'Doglan güni hökmanydyr' + if (!form.phone) e.phone = 'Telefon hökmanydyr' + return e + }, + }, + { + id: 'passport', + titleKey: 'Passport', + titleFallback: 'Pasport', + subtitle: 'Resminamalar', + icon: FileText, + validate: (form, mode) => { + const e: FormErrors = {} + if (!form.passport_series) e.passport_series = 'Pasport seriýasy hökmanydyr' + if (!form.passport_number) e.passport_number = 'Pasport belgisi hökmanydyr' + if (mode === 'create') { + if (!form.passport_page1) e.passport_page1 = 'Hökmanydyr' + if (!form.passport_page2_3) e.passport_page2_3 = 'Hökmanydyr' + if (!form.passport_page8_9) e.passport_page8_9 = 'Hökmanydyr' + if (!form.passport_page32) e.passport_page32 = 'Hökmanydyr' + } + return e + }, + }, +] + +// ─── 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' : '' -function Section({ title, children }: { title?: string; children: React.ReactNode }) { return ( -
+
{title && ( -
-

{title}

-
+

+ {title} +

)} -
{children}
+ {children}
) } -// ─── Component ──────────────────────────────────────────────────────────────── +// ─── Shared step content props ──────────────────────────────────────────────── + +interface StepContentProps { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void +} + +// ─── Step panels ────────────────────────────────────────────────────────────── + +function StepCard({ form, errors, set }: StepContentProps) { + const branchOptions = BRANCH_OPTIONS[form.province_id] ?? [] + + return ( +
+ + + set('status', v)} + options={STATUS_OPTIONS} + error={errors.status} + placeholder="Saýlaň" + /> + + + set('note', v)} + placeholder="Bellik..." + /> + + + + + + set('card_type', v)} + options={CARD_TYPE_OPTIONS} + placeholder="—" + error={errors.card_type} + /> + set('card_number', v)} + placeholder="Kart belgisi" + error={errors.card_number} + /> + + + + set('card_expiry_month', v)} + options={MONTH_OPTIONS} + placeholder="Saýlamak üçin basyň" + error={errors.card_expiry_month} + /> + set('card_expiry_year', v)} + options={YEAR_OPTIONS} + placeholder="Saýlamak üçin basyň" + error={errors.card_expiry_year} + /> + + + + + + { set('province_id', v); set('branch_id', '') }} + options={PROVINCE_OPTIONS} + placeholder="Aşgabat" + error={errors.province_id} + /> + + + set('branch_id', v)} + options={branchOptions} + placeholder="Saýlamak üçin basyň" + disabled={!form.province_id} + error={errors.branch_id} + /> + + +
+ ) +} + +function StepPersonal({ form, errors, set }: StepContentProps) { + return ( +
+ + + set('first_name', v)} + placeholder="Ady" error={errors.first_name} + /> + + + set('last_name', v)} + placeholder="Familiýasy" error={errors.last_name} + /> + + + set('middle_name', v)} + placeholder="Atasynyň ady" + /> + + + + + + set('birth_date', v)} + error={errors.birth_date} + /> + + + set('phone', v)} + placeholder="63 21 87 04" + error={errors.phone} + /> + + +
+ ) +} + +function StepPassport({ form, errors, set, mode, initialData }: StepContentProps & { + mode: 'create' | 'edit' + initialData?: CardRequisite +}) { + const existingFiles = + mode === 'edit' && initialData + ? [ + { url: initialData.passport_page1_url, label: 'Pasport (sahypa 1)' }, + { url: initialData.passport_page2_3_url, label: 'Pasport (2-3-nji sahypa)' }, + { url: initialData.passport_page8_9_url, label: 'Pasport (8-9 sahypa)' }, + { url: initialData.passport_page32_url, label: 'Pasport (32-nji sahypa)' }, + ].filter((f): f is { url: string; label: string } => !!f.url) + : [] + + return ( +
+ + + set('passport_series', v)} + options={PASSPORT_SERIES_OPTIONS} + placeholder="Saýlamak üçin basyň" + error={errors.passport_series} + /> + + + set('passport_number', v)} + placeholder="Pasport belgisi" + error={errors.passport_number} + /> + + + + {existingFiles.length > 0 && ( + + {existingFiles.map(({ url, label }) => ( + + + Faýly gör + + + ))} + + )} + + + + set('passport_page1', f)} + error={errors.passport_page1} + /> + + + set('passport_page2_3', f)} + error={errors.passport_page2_3} + /> + + + set('passport_page8_9', f)} + error={errors.passport_page8_9} + /> + + + set('passport_page32', f)} + error={errors.passport_page32} + /> + + +
+ ) +} + +// ─── Main Component ─────────────────────────────────────────────────────────── export function CardRequisiteForm({ mode, initialData, cardRequisiteId, }: CardRequisiteFormProps) { - const { t } = useTranslation() + const { t } = useTranslation() const navigate = useNavigate() - 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 + const [form, setForm] = useState(() => initialData ? mapToFormState(initialData) : INITIAL_STATE) + const [errors, setErrors] = useState({}) + const [currentStep, setCurrentStep] = useState(0) + const [visited, setVisited] = useState>( + () => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set(), + ) + useEffect(() => { - if (mode === 'edit' && initialData) { - setForm({ - status: initialData.status, - note: initialData.note, - card_type: initialData.card_type, - card_number: initialData.card_number, - card_expiry_month: initialData.card_expiry_month, - card_expiry_year: initialData.card_expiry_year, - province_id: initialData.province_id, - branch_id: initialData.branch_id, - first_name: initialData.first_name, - last_name: initialData.last_name, - middle_name: initialData.middle_name, - birth_date: initialData.birth_date, - phone: initialData.phone, - passport_series: initialData.passport_series, - passport_number: initialData.passport_number, - }) - } - }, [mode, initialData]) + if (initialData) setForm(mapToFormState(initialData)) + }, [initialData]) - // ── Field setters ────────────────────────────────────────────────────────── + // ── Computed step errors ─────────────────────────────────────────────────── - const setField = (field: keyof FormState) => (value: string) => { - setForm((prev) => { - const next = { ...prev, [field]: value } - if (field === 'province_id') next.branch_id = '' - return next + const stepsWithErrors = useMemo(() => { + const out = new Set() + visited.forEach((i) => { + if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i) }) - setErrors((prev) => ({ ...prev, [field]: undefined })) - } + return out + }, [form, mode, visited]) - const setFile = (field: keyof FileState) => (file: File | null) => { - setFiles((prev) => ({ ...prev, [field]: file })) - setErrors((prev) => ({ ...prev, [field]: undefined })) - } + // ── set helper ───────────────────────────────────────────────────────────── - // ── Step navigation ──────────────────────────────────────────────────────── + const set = useCallback((key: K, value: FormState[K]) => { + setForm((prev) => ({ ...prev, [key]: value })) + setErrors((prev) => ({ ...prev, [key]: undefined })) + }, []) - const updateStatus = (index: number, status: StepStatus) => { - setStepStatuses((prev) => { - const next = [...prev] - next[index] = status - return next - }) - } + const stepProps = useMemo(() => ({ form, errors, set }), [form, errors, set]) - const goToStep = (index: number) => { - updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'done') - updateStatus(index, 'active') - setCurrentStep(index) - window.scrollTo({ top: 0, behavior: 'smooth' }) - } + // ── Navigation ───────────────────────────────────────────────────────────── + + const markVisited = (i: number) => + setVisited((prev) => new Set([...prev, i])) const handleNext = () => { - const stepErrors = validate(form, files, mode, t, currentStep) - if (Object.keys(stepErrors).length > 0) { - setErrors((prev) => ({ ...prev, ...stepErrors })) - updateStatus(currentStep, 'error') + markVisited(currentStep) + const errs = STEPS[currentStep].validate(form, mode) + if (Object.keys(errs).length > 0) { + setErrors(errs) 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) + setErrors({}) + setCurrentStep(currentStep + 1) window.scrollTo({ top: 0, behavior: 'smooth' }) } - const handlePrev = () => { - const prev = currentStep - 1 - updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'idle') - updateStatus(prev, 'active') - setCurrentStep(prev) + const handleBack = () => { + markVisited(currentStep) + setErrors({}) + setCurrentStep(currentStep - 1) window.scrollTo({ top: 0, behavior: 'smooth' }) } + const handleGoTo = (i: number) => { + markVisited(currentStep) + setErrors({}) + setCurrentStep(i) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + const handleCancel = () => { + if (mode === 'create') navigate('/card-requisites') + else navigate(`/card-requisites/${cardRequisiteId}`) + } + // ── Submit ───────────────────────────────────────────────────────────────── const handleSubmit = async () => { - const allErrors = validate(form, files, mode, t) + setVisited(new Set(STEPS.map((_, i) => i))) + + const allErrors: FormErrors = {} + for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode)) + 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.')) + toast.error(t('Fix errors', 'Käbir hökmany meýdanlar doldurylan däldir.')) + for (let i = 0; i < STEPS.length; i++) { + if (Object.keys(STEPS[i].validate(form, mode)).length > 0) { + setCurrentStep(i) + break + } + } return } const payload: CreateCardRequisitePayload = { - ...(form as unknown as CreateCardRequisitePayload), - status: form.status as CardRequisiteStatus, - ...(files.passport_page1 && { passport_page1: files.passport_page1 }), - ...(files.passport_page2_3 && { passport_page2_3: files.passport_page2_3 }), - ...(files.passport_page8_9 && { passport_page8_9: files.passport_page8_9 }), - ...(files.passport_page32 && { passport_page32: files.passport_page32 }), + status: form.status as CardRequisiteStatus, + note: form.note || undefined, + card_type: form.card_type, + card_number: form.card_number, + card_expiry_month: form.card_expiry_month, + card_expiry_year: form.card_expiry_year, + province_id: form.province_id, + branch_id: form.branch_id, + first_name: form.first_name, + last_name: form.last_name, + middle_name: form.middle_name || undefined, + birth_date: form.birth_date, + phone: form.phone, + passport_series: form.passport_series, + passport_number: form.passport_number, + ...(form.passport_page1 && { passport_page1: form.passport_page1 }), + ...(form.passport_page2_3 && { passport_page2_3: form.passport_page2_3 }), + ...(form.passport_page8_9 && { passport_page8_9: form.passport_page8_9 }), + ...(form.passport_page32 && { passport_page32: form.passport_page32 }), } if (mode === 'create') { @@ -348,322 +642,59 @@ export function CardRequisiteForm({ } } - const handleCancel = () => { - if (mode === 'create') navigate('/card-requisites') - else navigate(`/card-requisites/${cardRequisiteId}`) - } + // ── StepBar items ────────────────────────────────────────────────────────── - const branchOptions = BRANCH_OPTIONS[form.province_id] ?? [] + 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', + } + }) - // ── 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 + const isLastStep = currentStep === STEPS.length - 1 // ── Render ───────────────────────────────────────────────────────────────── return (
+ - {/* ── Step Bar ─────────────────────────────────────────────────────── */} + {/* Step bar */}
- +
- {/* ── Step 0: Kart & Lokasiýa ──────────────────────────────────────── */} - {currentStep === 0 && ( - <> -
-
-
- -
- -
-
- -
-
-
- -
-
- -
-
- -
-
- -
-
-
- -
-
-
- -
-
- -
-
-
- - )} - - {/* ── Step 1: Şahsy maglumatlar ─────────────────────────────────────── */} - {currentStep === 1 && ( -
-
-
- -
-
- -
- -
- -
-
- -
-
- -
-
-
- )} - - {/* ── Step 2: Pasport & Faýllar ─────────────────────────────────────── */} + {/* Step content */} + {currentStep === 0 && } + {currentStep === 1 && } {currentStep === 2 && ( -
-
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
-
+ )} - {/* ── Form Actions ──────────────────────────────────────────────────── */} + {/* Actions */} 0 ? handleBack : undefined} prevLabel={t('Back', 'Yza')} onNext={!isLastStep ? handleNext : undefined} nextLabel={t('Next', 'Indiki')} showSubmit={isLastStep} - onSubmit={handleSubmit} + onSubmit={isLastStep ? handleSubmit : undefined} submitLabel={ mode === 'create' ? t('Create card requisite order', 'Kart rekwiziti üçin sargyt dörediň') : t('Save changes', 'Üýtgetmeleri sakla') } - className="mt-6" />
) diff --git a/src/features/orderNewCard/components/orderNewCardForm.tsx b/src/features/orderNewCard/components/orderNewCardForm.tsx index 6115608..e948c0f 100644 --- a/src/features/orderNewCard/components/orderNewCardForm.tsx +++ b/src/features/orderNewCard/components/orderNewCardForm.tsx @@ -1,7 +1,9 @@ -import { useState, useEffect } from 'react' +import { useState, useCallback, useMemo, useEffect } from 'react' import { useTranslation } from 'react-i18next' import { toast } from 'sonner' import { CreditCard, User, FileText, Upload } 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' @@ -62,26 +64,6 @@ interface FormState { } 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 ──────────────────────────────────────────────────────────── @@ -118,644 +100,500 @@ function getInitialState(data?: CardOrder): FormState { } } -// ─── Validation ─────────────────────────────────────────────────────────────── +// ─── Step definitions ───────────────────────────────────────────────────────── -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())) allErrors[field] = msg - } - - 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) 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') - } - - 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 +interface StepDef { + id: string + titleKey: string + titleFallback: string + subtitle: string + icon: LucideIcon + validate: (form: FormState, mode: 'create' | 'edit') => FormErrors } -// ─── Section wrapper ────────────────────────────────────────────────────────── +const STEPS: StepDef[] = [ + { + id: 'card', + titleKey: 'cardOrder.step.card', + titleFallback: 'Kart', + subtitle: 'Görnüş & lokasiýa', + icon: CreditCard, + validate: (form) => { + const e: FormErrors = {} + if (!form.status) e.status = 'Status — hökmany' + if (!form.issuanceReasonId) e.issuanceReasonId = 'Kartyň çykarylmagynyň sebäbi — hökmany' + if (!form.cardTypeId) e.cardTypeId = 'Kart görnüşi — hökmany' + if (!form.provinceId) e.provinceId = 'Welaýat — hökmany' + if (!form.branchId) e.branchId = 'Şahamça — hökmany' + return e + }, + }, + { + id: 'personal', + titleKey: 'cardOrder.step.personal', + titleFallback: 'Şahsy', + subtitle: 'Maglumatlar', + icon: User, + validate: (form) => { + const e: FormErrors = {} + if (!form.firstName) e.firstName = 'Ady — hökmany' + if (!form.lastName) e.lastName = 'Familiýasy — hökmany' + if (!form.birthDate) e.birthDate = 'Doglan güni — hökmany' + if (!form.phone) e.phone = 'Telefon — hökmany' + if (!form.citizenship) e.citizenship = 'Raýatlyk — hökmany' + if (!form.registeredAddress) e.registeredAddress = 'Ýazgy edilen salgy — hökmany' + if (!form.currentAddress) e.currentAddress = 'Häzirki ýaşaýyş ýeri — hökmany' + if (!form.workplace) e.workplace = 'Işleýän ýeri — hökmany' + return e + }, + }, + { + id: 'passport', + titleKey: 'cardOrder.step.passport', + titleFallback: 'Pasport', + subtitle: 'Resmi maglumat', + icon: FileText, + validate: (form) => { + const e: FormErrors = {} + if (!form.passportSeriesId) e.passportSeriesId = 'Pasport seriýasy — hökmany' + if (!form.passportNumber) e.passportNumber = 'Pasport belgisi — hökmany' + if (!form.passportIssueDate) e.passportIssueDate = 'Pasport berlen senesi — hökmany' + if (!form.passportIssuedBy) e.passportIssuedBy = 'Kim tarapyndan berildi — hökmany' + if (!form.passportBirthPlace) e.passportBirthPlace = 'Doglan ýeri — hökmany' + return e + }, + }, + { + id: 'files', + titleKey: 'cardOrder.step.files', + titleFallback: 'Faýllar', + subtitle: 'Ýüklemek & Tassyklamak', + icon: Upload, + validate: (form, mode) => { + const e: FormErrors = {} + if (mode === 'create') { + if (!form.passportPage1) e.passportPage1 = 'Pasport (sahypa 1) — hökmany' + if (!form.passportPage23) e.passportPage23 = 'Pasport (2-3-nji sahypa) — hökmany' + if (!form.passportPage89) e.passportPage89 = 'Pasport (8-9 sahypa) — hökmany' + if (!form.passportPage32) e.passportPage32 = 'Pasport (32-nji sahypa) — hökmany' + if (!form.termsAccepted) e.termsAccepted = 'Şertnama bilen razylaşmaly' + } + return e + }, + }, +] + +// ─── 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' : '' -function FormSection({ title, children }: { title?: string; children: React.ReactNode }) { return ( -
+
{title && ( -

{title}

+

+ {title} +

)} -
- {children} -
+ {children}
) } -// ─── CardOrderForm ──────────────────────────────────────────────────────────── +// ─── Shared step content props ──────────────────────────────────────────────── -export function CardOrderForm({ - mode, - initialData, - cardOrderId, - onSuccess, - onCancel, -}: CardOrderFormProps) { - const { t } = useTranslation() - const isEdit = mode === 'edit' +interface StepContentProps { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void +} - const [form, setForm] = useState(() => getInitialState(initialData)) - const [errors, setErrors] = useState({}) - const [currentStep, setCurrentStep] = useState(0) - const [stepStatuses, setStepStatuses] = useState([ - 'active', 'idle', 'idle', 'idle', - ]) +// ─── Step panels ────────────────────────────────────────────────────────────── - useEffect(() => { - if (initialData) setForm(getInitialState(initialData)) - }, [initialData]) +function StepCard({ + form, errors, set, + statusOptions, issuanceReasonOptions, cardTypeOptions, provinceOptions, branchOptions, +}: StepContentProps & { + statusOptions: SelectOption[] + issuanceReasonOptions: SelectOption[] + cardTypeOptions: SelectOption[] + provinceOptions: SelectOption[] + branchOptions: SelectOption[] +}) { + return ( +
+ + + set('status', v as CardOrderStatus)} + options={statusOptions} + placeholder="Saýlaň" + error={errors.status} + /> + set('note', v)} + placeholder="Bellik..." + rows={3} + /> + - // Lookup data - const { data: reasons = [] } = useCardIssuanceReasons() - const { data: cardTypes = [] } = useCardTypes() - const { data: provinces = [] } = useProvinces() - const { data: branches = [] } = useBranches( - form.provinceId ? Number(form.provinceId) : undefined, + +
+ set('isPaid', e.target.checked)} + className="w-4 h-4 accent-primary cursor-pointer" + /> + +
+
+
+ + + + set('issuanceReasonId', v)} + options={issuanceReasonOptions} + placeholder="Saýlamak üçin basyň" + error={errors.issuanceReasonId} + /> + + + set('cardTypeId', v)} + options={cardTypeOptions} + placeholder="Saýlamak üçin basyň" + error={errors.cardTypeId} + /> + + + + + + { set('provinceId', v); set('branchId', '') }} + options={provinceOptions} + placeholder="Saýlaň" + error={errors.provinceId} + /> + + + set('branchId', v)} + options={branchOptions} + disabled={!form.provinceId} + placeholder="Saýlamak üçin basyň" + error={errors.branchId} + /> + + +
) +} - // Mutations - const createMutation = useCreateCardOrder() - const updateMutation = useUpdateCardOrder(cardOrderId ?? '') - const isPending = createMutation.isPending || updateMutation.isPending +function StepPersonal({ form, errors, set, citizenshipOptions }: StepContentProps & { + citizenshipOptions: SelectOption[] +}) { + return ( +
+ + + set('firstName', v)} + placeholder="Ady" error={errors.firstName} + /> + + + set('lastName', v)} + placeholder="Familiýasy" error={errors.lastName} + /> + + + set('middleName', v)} + placeholder="Atasynyň ady" + /> + + - // Helpers - const set = (key: keyof FormState) => (value: string) => - setForm((f) => { - const next = { ...f, [key]: value } - setErrors((prev) => ({ ...prev, [key]: undefined })) - return next - }) + + + set('formerLastName', v)} + placeholder="Köne familiýaňyz" + /> + + + set('birthDate', v)} + error={errors.birthDate} + /> + + - const setFile = (key: keyof FormState) => (file: File | null) => { - setForm((f) => ({ ...f, [key]: file })) - setErrors((prev) => ({ ...prev, [key]: undefined })) - } + + + set('phone', v)} + error={errors.phone} + /> + + + set('phoneExtra', v)} + /> + + + set('citizenship', v)} + options={citizenshipOptions} + error={errors.citizenship} + /> + + - const toOptions = (arr: { id: number; name: string }[]): SelectOption[] => - arr.map((x) => ({ value: String(x.id), label: x.name })) + + + set('registeredAddress', v)} + placeholder="Ýazgy edilen salgyňyz" + error={errors.registeredAddress} + /> + + + set('currentAddress', v)} + placeholder="Häzirki ýaşaýyş ýeri" + error={errors.currentAddress} + /> + + - // ── Step navigation ──────────────────────────────────────────────────────── + + + set('workplace', v)} + placeholder="Işleýän ýeriňiz we wezipäňiz" + error={errors.workplace} + /> + + +
+ ) +} - const updateStatus = (index: number, status: StepStatus) => { - setStepStatuses((prev) => { - const next = [...prev] - next[index] = status - return next - }) - } +function StepPassport({ form, errors, set, passportSeriesOptions }: StepContentProps & { + passportSeriesOptions: SelectOption[] +}) { + return ( +
+ + + set('passportSeriesId', v)} + options={passportSeriesOptions} + placeholder="Saýlaň" + error={errors.passportSeriesId} + /> + + + set('passportNumber', v)} + placeholder="Pasport belgisi" + error={errors.passportNumber} + /> + + + set('passportIssueDate', v)} + error={errors.passportIssueDate} + /> + + - const goToStep = (index: number) => { - updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'done') - updateStatus(index, 'active') - setCurrentStep(index) - window.scrollTo({ top: 0, behavior: 'smooth' }) - } + + + set('passportIssuedBy', v)} + placeholder="Kim tarapyndan berildi" + error={errors.passportIssuedBy} + /> + + + set('passportBirthPlace', v)} + placeholder="Doglan ýeri (pasport)" + error={errors.passportBirthPlace} + /> + + +
+ ) +} - 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 () => { - 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 - } - - const payload = { - isPaid: form.isPaid, - status: form.status as CardOrderStatus, - note: form.note || null, - issuanceReasonId: Number(form.issuanceReasonId), - cardTypeId: Number(form.cardTypeId), - provinceId: Number(form.provinceId), - branchId: Number(form.branchId), - firstName: form.firstName, - lastName: form.lastName, - middleName: form.middleName || null, - formerLastName: form.formerLastName || null, - birthDate: form.birthDate, - phone: form.phone, - phoneExtra: form.phoneExtra || null, - citizenship: form.citizenship, - registeredAddress: form.registeredAddress, - currentAddress: form.currentAddress, - workplace: form.workplace, - passportSeriesId: Number(form.passportSeriesId), - passportNumber: form.passportNumber, - passportIssueDate: form.passportIssueDate, - passportIssuedBy: form.passportIssuedBy, - passportBirthPlace: form.passportBirthPlace, - ...(form.passportPage1 && { passportPage1: form.passportPage1 }), - ...(form.passportPage23 && { passportPage23: form.passportPage23 }), - ...(form.passportPage89 && { passportPage89: form.passportPage89 }), - ...(form.passportPage32 && { passportPage32: form.passportPage32 }), - } - - try { - if (isEdit) { - await updateMutation.mutateAsync(payload) - } else { - await createMutation.mutateAsync(payload as CreateCardOrderPayload) - } - onSuccess?.() - } catch { - // errors handled in hooks via toast - } - } - - // ── Options ──────────────────────────────────────────────────────────────── - - const statusOptions: SelectOption[] = [ - { value: 'PENDING', label: t('cardOrder.status.pending', 'Garaşylýar') }, - { value: 'APPROVED', label: t('cardOrder.status.approved', 'Tassyklandy') }, - { value: 'REJECTED', label: t('cardOrder.status.rejected', 'Ýatyryldy') }, - ] - - const citizenshipOptions: SelectOption[] = [ - { 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 ──────────────────────────────────────────────────────────────── +function StepFiles({ + form, errors, set, mode, initialData, +}: StepContentProps & { mode: 'create' | 'edit'; initialData?: CardOrder }) { + const existingFiles = + mode === 'edit' && initialData + ? [ + { url: initialData.passportFiles.page1, label: 'Pasport (sahypa 1)' }, + { url: initialData.passportFiles.page23, label: 'Pasport (2-3-nji sahypa)' }, + { url: initialData.passportFiles.page89, label: 'Pasport (8-9 sahypa)' }, + { url: initialData.passportFiles.page32, label: 'Pasport (32-nji sahypa)' }, + ].filter((f): f is { url: string; label: string } => !!f.url) + : [] return ( -
- - {/* ── 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" - /> - -
- -
-
- -
- -
-
- - -
-
- -
-
- -
-
-
- - -
-
- { - setForm((f) => ({ ...f, provinceId: v, branchId: '' })) - setErrors((prev) => ({ ...prev, provinceId: undefined, branchId: undefined })) - }} - options={toOptions(provinces)} - error={errors.provinceId} - /> -
-
- -
-
-
- + Faýly gör +
+ + ))} + )} - {/* ── Step 1: Şahsy maglumatlar ─────────────────────────────────────── */} - {currentStep === 1 && ( - -
-
- -
-
- -
- -
+ + + set('passportPage1', f)} + error={errors.passportPage1} + /> + + + set('passportPage23', f)} + error={errors.passportPage23} + /> + + + set('passportPage89', f)} + error={errors.passportPage89} + /> + + + set('passportPage32', f)} + error={errors.passportPage32} + /> + + -
- -
- -
-
- -
-
- -
- -
- -
-
- -
-
- -
-
- -
-
- -
- -
-
- )} - - {/* ── Step 2: Pasport ───────────────────────────────────────────────── */} - {currentStep === 2 && ( - -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
-
- )} - - {/* ── Step 3: Faýllar & Şertler ─────────────────────────────────────── */} - {currentStep === 3 && ( - <> - -
-
- -
-
- -
-
- -
-
- -
-
-
- - {/* Terms — only in create mode */} - {!isEdit && ( + {mode === 'create' && ( + +
{ - setForm((f) => ({ ...f, termsAccepted: !f.termsAccepted })) - setErrors((prev) => ({ ...prev, termsAccepted: undefined })) - }} + onClick={() => set('termsAccepted', !form.termsAccepted)} >
)}
- - {t('cardOrder.terms', 'Şertnama bilen razylaşýaryn (Okamak üçin bas)')} + + Şertnama bilen razylaşýaryn (Okamak üçin bas)
- )} - +
+
+ )} +
+ ) +} + +// ─── Main Component ─────────────────────────────────────────────────────────── + +export function CardOrderForm({ + mode, + initialData, + cardOrderId, + onSuccess, + onCancel, +}: CardOrderFormProps) { + const { t } = useTranslation() + + const createMutation = useCreateCardOrder() + const updateMutation = useUpdateCardOrder(cardOrderId ?? '') + const isPending = createMutation.isPending || updateMutation.isPending + + const [form, setForm] = useState(() => getInitialState(initialData)) + const [errors, setErrors] = useState({}) + const [currentStep, setCurrentStep] = useState(0) + const [visited, setVisited] = useState>( + () => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set(), + ) + + 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( + form.provinceId ? Number(form.provinceId) : undefined, + ) + + const toOptions = (arr: { id: number; name: string }[]): SelectOption[] => + arr.map((x) => ({ value: String(x.id), label: x.name })) + + const statusOptions: SelectOption[] = [ + { value: 'PENDING', label: t('cardOrder.status.pending', 'Garaşylýar') }, + { value: 'APPROVED', label: t('cardOrder.status.approved', 'Tassyklandy') }, + { value: 'REJECTED', label: t('cardOrder.status.rejected', 'Ýatyryldy') }, + ] + + const citizenshipOptions: SelectOption[] = [ + { value: 'Turkmenistan', label: t('citizenship.tm', 'Turkmenistan') }, + { value: 'Russia', label: t('citizenship.ru', 'Russiýa') }, + { value: 'Other', label: t('citizenship.other', 'Beýlekiler') }, + ] + + const passportSeriesOptions: SelectOption[] = [ + { value: '1', label: 'I' }, + { value: '2', label: 'II' }, + { value: '3', label: 'III' }, + ] + + // ── Computed step error state ────────────────────────────────────────────── + + const stepsWithErrors = useMemo(() => { + const out = new Set() + visited.forEach((i) => { + if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i) + }) + return out + }, [form, mode, visited]) + + // ── set helper ───────────────────────────────────────────────────────────── + + const set = useCallback((key: K, value: FormState[K]) => { + setForm((prev) => ({ ...prev, [key]: value })) + setErrors((prev) => ({ ...prev, [key]: undefined })) + }, []) + + const stepProps = useMemo(() => ({ form, errors, set }), [form, errors, set]) + + // ── Navigation ────────────────────────────────────────────────────────────── + + const markVisited = (i: number) => + setVisited((prev) => new Set([...prev, i])) + + const handleNext = () => { + markVisited(currentStep) + const errs = STEPS[currentStep].validate(form, mode) + if (Object.keys(errs).length > 0) { + setErrors(errs) + toast.error(t('validation.fixErrors', 'Dogry maglumat girizmegiňizi haýyş edýäris.')) + return + } + setErrors({}) + setCurrentStep(currentStep + 1) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + const handleBack = () => { + markVisited(currentStep) + setErrors({}) + setCurrentStep(currentStep - 1) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + const handleGoTo = (i: number) => { + markVisited(currentStep) + setErrors({}) + setCurrentStep(i) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + // ── Submit ───────────────────────────────────────────────────────────────── + + const handleSubmit = async () => { + setVisited(new Set(STEPS.map((_, i) => i))) + + const allErrors: FormErrors = {} + for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode)) + + if (Object.keys(allErrors).length > 0) { + setErrors(allErrors) + toast.error(t('validation.fixErrors', 'Käbir hökmany meýdanlar doldurylan däldir.')) + for (let i = 0; i < STEPS.length; i++) { + if (Object.keys(STEPS[i].validate(form, mode)).length > 0) { + setCurrentStep(i) + break + } + } + return + } + + const payload = { + isPaid: form.isPaid, + status: form.status as CardOrderStatus, + note: form.note || null, + issuanceReasonId: Number(form.issuanceReasonId), + cardTypeId: Number(form.cardTypeId), + provinceId: Number(form.provinceId), + branchId: Number(form.branchId), + firstName: form.firstName, + lastName: form.lastName, + middleName: form.middleName || null, + formerLastName: form.formerLastName || null, + birthDate: form.birthDate, + phone: form.phone, + phoneExtra: form.phoneExtra || null, + citizenship: form.citizenship, + registeredAddress: form.registeredAddress, + currentAddress: form.currentAddress, + workplace: form.workplace, + passportSeriesId: Number(form.passportSeriesId), + passportNumber: form.passportNumber, + passportIssueDate: form.passportIssueDate, + passportIssuedBy: form.passportIssuedBy, + passportBirthPlace: form.passportBirthPlace, + ...(form.passportPage1 && { passportPage1: form.passportPage1 }), + ...(form.passportPage23 && { passportPage23: form.passportPage23 }), + ...(form.passportPage89 && { passportPage89: form.passportPage89 }), + ...(form.passportPage32 && { passportPage32: form.passportPage32 }), + } + + try { + if (mode === 'edit') { + await updateMutation.mutateAsync(payload) + } else { + await createMutation.mutateAsync(payload as CreateCardOrderPayload) + } + onSuccess?.() + } catch { + // errors handled in hooks via toast + } + } + + // ── StepBar items ─────────────────────────────────────────────────────────── + + const stepBarItems: StepCardItem[] = STEPS.map((s, i) => { + const isActive = i === currentStep + const hasErrors = stepsWithErrors.has(i) + const isDone = visited.has(i) && !hasErrors + return { + id: s.id, + title: t(s.titleKey) || s.titleFallback, + subtitle: s.subtitle, + icon: s.icon, + status: isActive ? 'active' : hasErrors ? 'error' : isDone ? 'done' : 'idle', + } + }) + + const isLastStep = currentStep === STEPS.length - 1 + + // ── Render ────────────────────────────────────────────────────────────────── + + return ( +
+ + + {/* Step bar */} +
+ +
+ + {/* Step content */} + {currentStep === 0 && ( + + )} + {currentStep === 1 && ( + + )} + {currentStep === 2 && ( + + )} + {currentStep === 3 && ( + )} - {/* ── Form Actions ──────────────────────────────────────────────────── */} + {/* Actions */} 0 ? handleBack : undefined} onNext={!isLastStep ? handleNext : undefined} - nextLabel={t('common.next', 'Indiki')} showSubmit={isLastStep} - onSubmit={handleSubmit} + onSubmit={isLastStep ? handleSubmit : undefined} submitLabel={ - isEdit - ? t('common.save', 'Ýatda sakla') - : t('cardOrder.submit', 'Kart sargyt dörediň') + mode === 'create' + ? (t('cardOrder.submit') || 'Kart sargyt dörediň') + : (t('common.save') || 'Ýatda sakla') } + loadingLabel={t('common.saving') || 'Ýüklenilýär...'} + cancelLabel={t('common.cancel') || 'Ýatyr'} + prevLabel={t('common.prev') || 'Yza'} + nextLabel={t('common.next') || 'Indiki'} />
) diff --git a/src/lib/api/client.ts b/src/lib/api/client.ts index 351f70a..737af77 100644 --- a/src/lib/api/client.ts +++ b/src/lib/api/client.ts @@ -1,40 +1,79 @@ -import axios from 'axios' +import axios from "axios"; +import { useAuthStore } from "@/app/store/authStore"; -const API_BASE_URL = import.meta.env.VITE_API_URL ?? '/api' +const apiClient = axios.create({ + baseURL: import.meta.env.VITE_API_BASE_URL, + timeout: 10000, +}); -export const apiClient = axios.create({ - baseURL: API_BASE_URL, - headers: { - 'Content-Type': 'application/json', - }, - timeout: 15_000, -}) +let isRefreshing = false; +let failedQueue: any[] = []; -// Request interceptor — attach token +const processQueue = (error: any, token: string | null = null) => { + failedQueue.forEach((prom) => { + if (error) prom.reject(error); + else prom.resolve(token); + }); + failedQueue = []; +}; + +// Request Interceptor (Token ekleme) apiClient.interceptors.request.use((config) => { - const raw = localStorage.getItem('tbbank-auth') - if (raw) { - try { - const parsed = JSON.parse(raw) as { state?: { token?: string } } - const token = parsed?.state?.token - if (token) { - config.headers.Authorization = `Bearer ${token}` - } - } catch { - // ignore parse errors - } + const token = useAuthStore.getState().token; + if (token && config.headers) { + config.headers.Authorization = `Bearer ${token}`; } - return config -}) + return config; +}, (error) => Promise.reject(error)); -// Response interceptor — handle 401 +// Response Interceptor (Senior Hata Yönetimi) apiClient.interceptors.response.use( (response) => response, - (error: unknown) => { - if (axios.isAxiosError(error) && error.response?.status === 401) { - localStorage.removeItem('tbbank-auth') - window.location.replace('/login') + async (error) => { + const originalRequest = error.config; + const status = error.response?.status; + + // 1. 401 Unauthorized & Refresh Token Yönetimi + if (status === 401 && !originalRequest._retry) { + if (isRefreshing) { + return new Promise((resolve, reject) => { + failedQueue.push({ resolve, reject }); + }) + .then((token) => { + originalRequest.headers.Authorization = `Bearer ${token}`; + return apiClient(originalRequest); + }) + .catch((err) => Promise.reject(err)); + } + + originalRequest._retry = true; + isRefreshing = true; + + try { + // Sessizce yeni token almayı dene (Zustand içindeki refresh action'ı) + const newToken = await useAuthStore.getState().refreshToken(); + processQueue(null, newToken); + originalRequest.headers.Authorization = `Bearer ${newToken}`; + return apiClient(originalRequest); + } catch (refreshError) { + processQueue(refreshError, null); + // Refresh de patladıysa kullanıcıyı temizce çıkışa zorla + useAuthStore.getState().logout(); + // SPA dostu yönlendirme: Sayfa yenilemeden custom bir event veya global history ile + window.dispatchEvent(new Event("auth:unauthorized")); + return Promise.reject(refreshError); + } finally { + isRefreshing = false; + } } - return Promise.reject(error) - }, -) + + // 2. 403 Forbidden Yönetimi (Kullanıcıyı haberdar et, akışı durdur) + if (status === 403) { + window.dispatchEvent(new Event("auth:forbidden")); + } + + return Promise.reject(error); + } +); + +export default apiClient; \ No newline at end of file diff --git a/src/pages/internationalPayments/sberPaymentsView/index.tsx b/src/pages/internationalPayments/sberPaymentsView/index.tsx index fb831a4..ca9c227 100644 --- a/src/pages/internationalPayments/sberPaymentsView/index.tsx +++ b/src/pages/internationalPayments/sberPaymentsView/index.tsx @@ -1,415 +1,306 @@ -import { format } from "date-fns"; -import { - Trash2, - Edit, - Search, - Download, - Clock, - XCircle, - CheckCircle2, - AlertCircle, -} from "lucide-react"; +import { format } from 'date-fns' +import { Trash2, Edit, Search, Download, XCircle, CheckCircle2, AlertCircle } from 'lucide-react' +import { useParams, useNavigate } from 'react-router-dom' +import { Skeleton } from '@/components/ui/skeleton' +import { StatusBadge, type StatusBadgeVariant } from '@/components/ui/statusBadge' +import { InfoRow, AuditLog, type AuditRowProps } from '@/components/viewPageComponents' +import { useSberPaymentOrder, useDeleteSberPayment } from '@/features/sberPayments/hooks/useSberPayments' +import type { PaymentPaidStatus, PaymentStatus } from '@/features/sberPayments/api/sberPaymentsApi' +import { useState } from 'react' -import { - useSberPaymentOrder, - useDeleteSberPayment, -} from "@/features/sberPayments/hooks/useSberPayments"; -import type { - PaymentPaidStatus, - PaymentStatus, -} from "@/features/sberPayments/api/sberPaymentsApi"; -import { Button } from "@/components/ui/button"; -import { Spinner } from "@/components/ui/spinner"; -import { cn } from "@/lib/utils"; -import { useParams, useNavigate } from "react-router-dom"; -import { - StatusBadge, - type StatusBadgeVariant, -} from "@/components/ui/statusBadge"; -import { InfoRow, Section } from "@/components/viewPageComponents"; +// ─── Status config ──────────────────────────────────────────────────────────── const STATUS_CONFIG = { - GARASYLYYAR: { - label: "Garaşylýar", - variant: "warning" as StatusBadgeVariant, - icon: AlertCircle, - }, - KANAGATLANDYRYLAN: { - label: "Tassyklandy", - variant: "success" as StatusBadgeVariant, - icon: CheckCircle2, - }, - RET_EDILEN: { - label: "Ýatyryldy", - variant: "error" as StatusBadgeVariant, - icon: XCircle, - }, -} satisfies Record< - PaymentStatus, - { label: string; variant: StatusBadgeVariant; icon: React.ElementType } ->; + GARASYLYYAR: { label: 'Garaşylýar', variant: 'warning' as StatusBadgeVariant, icon: AlertCircle }, + KANAGATLANDYRYLAN: { label: 'Tassyklandy', variant: 'success' as StatusBadgeVariant, icon: CheckCircle2 }, + RET_EDILEN: { label: 'Ýatyryldy', variant: 'error' as StatusBadgeVariant, icon: XCircle }, +} satisfies Record const PAID_STATUS_CONFIG = { - Tolenmedik: { - label: "Tölmedi", - variant: "error" as StatusBadgeVariant, - icon: XCircle, - }, - Tolendi: { - label: "Tölendi", - variant: "success" as StatusBadgeVariant, - icon: CheckCircle2, - }, -} satisfies Record< - PaymentPaidStatus, - { label: string; variant: StatusBadgeVariant; icon: React.ElementType } ->; - -function PaymentPaidStatusBadge({ status }: { status: PaymentPaidStatus }) { - const cfg = PAID_STATUS_CONFIG[status]; - if (!cfg) - return ( - {String(status)} - ); - return ( - - ); -} + Tolenmedik: { label: 'Tölmedi', variant: 'error' as StatusBadgeVariant, icon: XCircle }, + Tolendi: { label: 'Tölendi', variant: 'success' as StatusBadgeVariant, icon: CheckCircle2 }, +} satisfies Record function PaymentStatusBadge({ status }: { status: PaymentStatus }) { - const cfg = STATUS_CONFIG[status]; - if (!cfg) - return ( - {String(status)} - ); - return ( - - ); + const cfg = STATUS_CONFIG[status] + if (!cfg) return {String(status)} + return } -// ─── Info Row Component ─────────────────────────────────────────────────────── +function PaymentPaidStatusBadge({ status }: { status: PaymentPaidStatus }) { + const cfg = PAID_STATUS_CONFIG[status] + if (!cfg) return {String(status)} + return +} +// ─── Bento primitives ───────────────────────────────────────────────────────── -// ─── Document Item Component ────────────────────────────────────────────────── +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 DocumentItem({ +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} +
+ ) +} + +// ─── Document row ───────────────────────────────────────────────────────────── + +function DocumentRow({ label, fileName, fileUrl, }: { - label: string; - fileName: string | null; - fileUrl: string | null; + label: string + fileName: string | null + fileUrl: string | null }) { + if (!fileUrl) return ( + + — + + ) + + const name = fileName ?? fileUrl.split('/').pop() ?? 'faýl' + return ( -
- - {label} - -
- {fileUrl ? ( -
- - - - {fileName} - -
- ) : ( - — - )} + + -
- ); + + ) } -// ─── View Page Component ────────────────────────────────────────────────────── +// ─── Skeleton ───────────────────────────────────────────────────────────────── + +function SberPaymentViewSkeleton() { + return ( +
+ +
+ {[...Array(4)].map((_, i) => ( +
+ + {[...Array(3)].map((_, j) => ( + + ))} +
+ ))} +
+
+ ) +} + +// ─── Page ───────────────────────────────────────────────────────────────────── export default function SberPaymentViewPage() { - const params = useParams(); - const navigate = useNavigate(); - const id = params.id as string; + const { id } = useParams<{ id: string }>() + const navigate = useNavigate() + const [historySearch, setHistorySearch] = useState('') - const { data: order, isLoading } = useSberPaymentOrder(id); - const deleteMutation = useDeleteSberPayment(); + const { data: order, isLoading } = useSberPaymentOrder(id!) + const deleteMutation = useDeleteSberPayment() const handleDelete = async () => { - if (confirm("Bu tolegi pozmak isleyanizmi?")) { - await deleteMutation.mutateAsync(id); - navigate("/sber-payments"); - } - }; - - if (isLoading) { - return ( -
- -
- ); + if (!window.confirm('Bu tolegi pozmak isleyanizmi?')) return + await deleteMutation.mutateAsync(id!) + navigate('/sber-payments') } + if (isLoading) return + if (!order) { return ( -
-

Toleg tapylmady

- +
+ Toleg tapylmady
- ); + ) } + const kabulDocs = order.documents?.slice(0, 6) ?? [] + const ugradDocs = order.documents?.slice(6) ?? [] + + const auditLogs: AuditRowProps[] = order.activityLog?.map((log) => ({ + id: log.id.split('-')[1] ?? log.id, + action: log.analysisName, + by: log.createdBy, + target: log.target, + status: log.status, + date: format(new Date(log.createdAt), 'dd/MM/yyyy, HH:mm:ss') + ' GMT+5', + })) ?? [] + return ( -
- {/* Header Actions */} -
- - +
+ + {/* ── Page header ──────────────────────────────────────────────────── */} +
+

+ Sberbank töleg: {order.id} +

+
+ + +
- {/* Status Section */} -
-
+ {/* ── Row 1: Meta + Lokasiýa ────────────────────────────────────────── */} + + - + -
-
+ - {/* Location Section */} -
-
- - -
-
+ + + + + - {/* Personal Info Section */} -
-
- - - - - -
-
+ {/* ── Row 2: Şahsy maglumatlar + Töleg ─────────────────────────────── */} + + + + + + + + - {/* Payment Info Section */} -
-
+ - -
+ + + + + + -
-
- Tolegi kabul edijinin maglumatlary -
-
-
- Pasport seriyasy -

{order.passportSeries}

-
-
- Pasport nomeri -

{order.passportNumber}

-
-
- - Ady Familiyasy Atasynyn ady - -

{order.fullName}

-
-
-
-
+ {/* ── Row 3: Kabul ediji resminamalary ─────────────────────────────── */} + + + {kabulDocs.length > 0 + ? kabulDocs.map((doc) => ( + + )) + : ( +
+ Resminamalar ýok +
+ ) + } +
+
- {/* Documents - Accepted */} -
-

- Kabul ediji talyp boyunca resminamalary -

-
- {order.documents?.slice(0, 6).map((doc) => ( - - ))} -
-
+ {/* ── Row 4: Ugradyjy resminamalary ────────────────────────────────── */} + + + {ugradDocs.length > 0 + ? ugradDocs.map((doc) => ( + + )) + : ( +
+ Resminamalar ýok +
+ ) + } +
+
- {/* Documents - Sent */} -
-

- Ugradyjy boyunca resminamalary -

-
- {order.documents - ?.slice(6) - .map((doc) => ( - + +
+
+ + setHistorySearch(e.target.value)} + placeholder="Gözlemek" + className="h-9 w-full pl-9 pr-3 rounded-md border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring" /> - )) || ( -
- Resminamalar yok
- )} -
-
- {/* Payment History */} -
-
-

- Toleg taryhy -

- -
- -
-
- - -
- -
-
-
- +
+
+
-

- Berlen kriteriyalara Toleg gabat gelmedi. -

+

Berlen kriteriýalara Töleg gabat gelmedi.

-
+ + -
- -
-
+ {/* ── Audit log ────────────────────────────────────────────────────── */} + - {/* Activity Log */} -
-
-

Ammallar

- -
- -
- {/* Table Header */} -
- ID - Analys ady - Kim tarapyndan - Analys nysany (Targets) - Analys statusy - Sene -
- - {/* Table Body */} - {order.activityLog?.length ? ( - order.activityLog.map((log) => ( -
- - {log.id.split("-")[1] ?? "45384"} - - {log.analysisName} - {log.createdBy} - {log.target} - - - {log.status} - - - - {format(new Date(log.createdAt), "dd/MM/yyyy, HH:mm:ss")}{" "} - GMT+5 - -
- )) - ) : ( -
- Ammallar yok -
- )} -
-
- ); -} + ) +} \ No newline at end of file diff --git a/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx b/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx index 23e77cc..9b15aa1 100644 --- a/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx +++ b/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx @@ -1,10 +1,7 @@ +import { useState } from 'react' import { useParams, useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' -import { useIntlPayment, useDeleteIntlPayment } from '@/features/visaMasterPayments/hooks/useVisaMasterPayments' -import type { IntlPaymentStatus } from '@/features/visaMasterPayments/api/visaMasterPaymentsApi' -import { Spinner } from '@/components/ui/spinner' -import { Button } from '@/components/ui/button' -import { Pencil, Trash2, Download, Search } from 'lucide-react' +import { Pencil, Trash2, Download, Search, AlertCircle, CheckCircle2, XCircle } from 'lucide-react' import { AlertDialog, AlertDialogAction, @@ -16,59 +13,120 @@ import { AlertDialogTitle, AlertDialogTrigger, } from '@/components/ui/alert-dialog' -import { useState } from 'react' +import { Skeleton } from '@/components/ui/skeleton' import { StatusBadge, type StatusBadgeVariant } from '@/components/ui/statusBadge' -import { InfoRow, Section } from '@/components/viewPageComponents' -// ─── Status Badge ───────────────────────────────────────────────────────────── +import { InfoRow } from '@/components/viewPageComponents' +import { useIntlPayment, useDeleteIntlPayment } from '@/features/visaMasterPayments/hooks/useVisaMasterPayments' +import type { IntlPaymentStatus } from '@/features/visaMasterPayments/api/visaMasterPaymentsApi' -const STATUS_MAP: Record = { - pending: { label: 'Garaşylýar', variant: 'warning' }, - approved: { label: 'Tassyklandy', variant: 'success' }, - rejected: { label: 'Ret edildi', variant: 'error' }, +// ─── Status config ──────────────────────────────────────────────────────────── + +const STATUS_MAP: Record = { + pending: { label: 'Garaşylýar', variant: 'warning', icon: AlertCircle }, + approved: { label: 'Tassyklandy', variant: 'success', icon: CheckCircle2 }, + rejected: { label: 'Ret edildi', variant: 'error', icon: XCircle }, } function PaymentStatusBadge({ status }: { status: IntlPaymentStatus }) { const cfg = STATUS_MAP[status] ?? STATUS_MAP.pending + return +} + +// ─── 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} +
) } - - - -// ─── DocFile row ───────────────────────────────────────────────────────────── +// ─── DocFile row ────────────────────────────────────────────────────────────── function DocFileRow({ label, url }: { label: string; url: string | null }) { if (!url) return ( -
- {label} - — -
+ + — + ) const filename = url.split('/').pop() ?? 'faýl' - const isImage = /\.(jpg|jpeg|png|gif|webp)$/i.test(url) + const isImage = /\.(jpg|jpeg|png|gif|webp)$/i.test(url) return ( -
- {label} -
+ +
{isImage && ( - {filename} )} - {filename}
+
+ ) +} + +// ─── Skeleton ───────────────────────────────────────────────────────────────── + +function IntlPaymentViewSkeleton() { + return ( +
+ +
+ {[...Array(4)].map((_, i) => ( +
+ + {[...Array(3)].map((_, j) => ( + + ))} +
+ ))} +
) } @@ -76,62 +134,62 @@ function DocFileRow({ label, url }: { label: string; url: string | null }) { // ─── Page ───────────────────────────────────────────────────────────────────── export default function IntlPaymentViewPage() { - const { id } = useParams<{ id: string }>() - const navigate = useNavigate() - const { t } = useTranslation() - - const { data, isLoading, isError } = useIntlPayment(id!) - const { mutate: deletePayment, isPending: isDeleting } = useDeleteIntlPayment() + const { id } = useParams<{ id: string }>() + const navigate = useNavigate() + const { t } = useTranslation() const [historySearch, setHistorySearch] = useState('') - if (isLoading) { - return ( -
- -
- ) - } + const { data, isLoading, isError } = useIntlPayment(id!) + const { mutate: deletePayment, isPending: isDeleting } = useDeleteIntlPayment() + + if (isLoading) return if (isError || !data) { return ( -
+
{t('common.notFound', 'Maglumat tapylmady')}
) } const KABUL_DOCS = [ - { label: 'Talypyň degişli welaýata "SBERBANK" kartyň rekwizitleri', url: data.doc_sberbank_account }, - { label: 'Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwänamasy', url: data.doc_school_enrollment }, - { label: 'Talypyň bilendiriň göçürmesi', url: data.doc_summons }, - { label: 'Talypyň degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi', url: data.doc_passport_tm }, - { label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi', url: data.doc_foreign_passport }, - { 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', url: data.doc_foreign_passport_copy }, - { label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň dowletiniň girmesiz baradaky bellenen sahypasynyň göçürmesi', url: data.doc_exit_permission }, - { label: 'Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy barada maglumatlary daşary ýurt döwletiniň ýokary okuw mekdebinden haty', url: data.doc_school_foreign_info }, - { label: 'Talypyň daşary ýurt döwletinde okaýandygy baradaky güwänamany daşary ýurt döwletiniň ýokary okuw mekdebinden haty', url: data.doc_school_departure_info }, + { label: 'Talypyň degişli welaýata "SBERBANK" kartyň rekwizitleri', url: data.doc_sberbank_account }, + { label: 'Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwänamasy', url: data.doc_school_enrollment }, + { label: 'Talypyň bilendiriň göçürmesi', url: data.doc_summons }, + { label: 'Talypyň degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi', url: data.doc_passport_tm }, + { label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi', url: data.doc_foreign_passport }, + { 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', url: data.doc_foreign_passport_copy }, + { label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň dowletiniň girmesiz baradaky bellenen sahypasynyň göçürmesi', url: data.doc_exit_permission }, + { label: 'Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy barada maglumatlary daşary ýurt döwletiniň ýokary okuw mekdebinden haty', url: data.doc_school_foreign_info }, + { label: 'Talypyň daşary ýurt döwletinde okaýandygy baradaky güwänamany daşary ýurt döwletiniň ýokary okuw mekdebinden haty', url: data.doc_school_departure_info }, ] const UPGRAD_DOCS = [ - { label: 'Upgradyý degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi', url: data.upd_doc_passport_tm }, - { label: 'Upgradyý degişli Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi', url: data.upd_doc_foreign_passport }, - { label: 'Upgradyý Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň daşary ýurt döwletinde galýandygy baradaky şaýmynyň bellenen sahypasynyň göçürmesi', url: data.upd_doc_visa }, - { label: 'Upgradyýyň we kabul edijiniň resminamalarynyň göçürmesi', url: data.upd_doc_acceptance_letter }, - { label: 'Upgradyý we kabul ediji täze 2015-nji ýyldan soňra pasportynyň seriýasy baradaky maglumatlary', url: data.upd_doc_passport_biometric }, - { label: 'Upgradyý we kabul ediji täze 2015-nji ýyldan soňra pasportynyň seriýasy baradaky göwnamasy', url: data.upd_doc_passport_old }, + { label: 'Upgradyý degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi', url: data.upd_doc_passport_tm }, + { label: 'Upgradyý degişli Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi', url: data.upd_doc_foreign_passport }, + { label: 'Upgradyý Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň daşary ýurt döwletinde galýandygy baradaky şaýmynyň bellenen sahypasynyň göçürmesi', url: data.upd_doc_visa }, + { label: 'Upgradyýyň we kabul edijiniň resminamalarynyň göçürmesi', url: data.upd_doc_acceptance_letter }, + { label: 'Upgradyý we kabul ediji täze 2015-nji ýyldan soňra pasportynyň seriýasy baradaky maglumatlary', url: data.upd_doc_passport_biometric }, + { label: 'Upgradyý we kabul ediji täze 2015-nji ýyldan soňra pasportynyň seriýasy baradaky göwnamasy', url: data.upd_doc_passport_old }, ] return ( -
- {/* Header */} -
- -
+
+ + {/* ── Page header ──────────────────────────────────────────────────── */} +
+

+ {t('intlPayment.viewTitle', 'Halkara töleg')}: {data.id} +

+
- + @@ -153,17 +211,19 @@ export default function IntlPaymentViewPage() { - + +
- {/* Status */} -
-
+ {/* ── Row 1: Meta + Ýüztuman + Lokasiýa ───────────────────────────── */} + + {data.client_label} @@ -173,125 +233,89 @@ export default function IntlPaymentViewPage() { - - {data.created_at} - - - {data.note} - -
-
+ + + - {/* Ýüztumanyň görnüşi */} -
-
- - {data.currency_type_label} - -
-
+ + + - {/* Lokasiýa */} -
-
- {data.province_label} + + {data.branch_label} -
-
+ + - {/* Şahsy maglumatlar */} -
-
- {data.passport_first_name} - {data.passport_last_name} - +{data.phone} - {data.email} - {data.home_address} -
-
- - {/* Töleg */} -
-
- - {data.payer_full_name} + {/* ── Row 2: Şahsy maglumatlar + Töleg ─────────────────────────────── */} + + + + + + +{data.phone} - - {data.payer_account_number} - -
- {/* Receiver table */} -
- - - - - - - - - - - - - - - -
- {t('intlPayment.passportSeries', 'Pasport seriýasy')} - - {t('intlPayment.passportNumber', 'Pasport nomeri')} - - {t('intlPayment.payerFullName', 'Ady Familiýasy Atasnyň ady')} -
{data.passport_series} – {data.passport_number}{data.passport_number}{data.payer_full_name}
-
-
+ + + - {/* Kabul ediji talyp boyunca resminamalar */} -
-
+ + + + + + + + + {/* ── Row 3: Kabul ediji resminamalar ──────────────────────────────── */} + + {KABUL_DOCS.map((doc, i) => ( ))} -
-
+ + - {/* Upgradyý boyunca resminamalar */} -
-
+ {/* ── Row 4: Upgradyý resminamalar ─────────────────────────────────── */} + + {UPGRAD_DOCS.map((doc, i) => ( ))} -
-
+ + - {/* Töleg taryhy */} -
-
-
- - setHistorySearch(e.target.value)} - placeholder={t('intlPayment.search', 'Gözlemek')} - className="h-9 w-full pl-9 pr-3 rounded-md border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring" - /> + {/* ── Row 5: Töleg taryhy ───────────────────────────────────────────── */} + + +
+
+ + setHistorySearch(e.target.value)} + placeholder={t('intlPayment.search', 'Gözlemek')} + className="h-9 w-full pl-9 pr-3 rounded-md border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring" + /> +
+ +
+
+ + + + + +
+

{t('intlPayment.noHistory', 'Beriilen kriteriýalara Töleg gabat gelmedi')}

+
-
-
-
- - - - - -
-

{t('intlPayment.noHistory', 'Beriilen kriteriýalara Töleg gabat gelmedi')}

-
-
+ + +
) -} +} \ No newline at end of file diff --git a/src/pages/notFoundPage/index.tsx b/src/pages/notFoundPage/index.tsx new file mode 100644 index 0000000..604d90f --- /dev/null +++ b/src/pages/notFoundPage/index.tsx @@ -0,0 +1,42 @@ +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { Button } from "@/components/ui/button"; + +export default function NotFoundPage() { + const { t } = useTranslation(); + const navigate = useNavigate(); + + return ( +
+
+

+ 404 +

+ +
+

+ {t("errors.pageNotFoundTitle")} +

+

+ {t("errors.pageNotFoundDescription")} +

+
+ +
+ + + +
+
+
+ ); +} \ No newline at end of file