added some pages

This commit is contained in:
Jelaletdin12
2026-05-07 12:21:55 +05:00
parent c2548280a2
commit c7797c3e31
61 changed files with 8309 additions and 35 deletions

View File

@@ -0,0 +1,104 @@
import {apiClient} from '@/lib/api/client'
// ─── Types ────────────────────────────────────────────────────────────────────
export interface CardBalance {
id: number
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
export interface CardBalanceListResponse {
data: CardBalance[]
total: number
page: number
per_page: number
}
export interface CreateCardBalancePayload {
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
export type UpdateCardBalancePayload = CreateCardBalancePayload
export interface CardBalanceListParams {
page?: number
per_page?: number
search?: string
}
// ─── API ─────────────────────────────────────────────────────────────────────
const MOCK_CARD_BALANCES: CardBalance[] = [
{
id: 1,
passport_series: 'AA',
passport_number: '1112223',
card_number: '8600123412341234',
card_expiry_month: '10',
card_expiry_year: '2028',
},
{
id: 2,
passport_series: 'I-MR',
passport_number: '9988776',
card_number: '9860123456789012',
card_expiry_month: '05',
card_expiry_year: '2027',
},
{
id: 3,
passport_series: 'II-LB',
passport_number: '4455667',
card_number: '4400556677889900',
card_expiry_month: '12',
card_expiry_year: '2026',
},
]
export const cardBalancesApi = {
getAll: async (params?: CardBalanceListParams): Promise<CardBalanceListResponse> => {
// Mock data kullanmak için:
return { data: MOCK_CARD_BALANCES, total: MOCK_CARD_BALANCES.length, page: params?.page || 1, per_page: params?.per_page || 25 }
const { data } = await apiClient.get('/card-balances', { params })
return data
},
getById: async (id: number): Promise<CardBalance> => {
// Mock data kullanmak için:
const mock = MOCK_CARD_BALANCES.find(b => b.id === id)
if (mock) return mock
const { data } = await apiClient.get(`/card-balances/${id}`)
return data
},
create: async (payload: CreateCardBalancePayload): Promise<CardBalance> => {
const { data } = await apiClient.post('/card-balances', payload)
return data
},
update: async (id: number, payload: UpdateCardBalancePayload): Promise<CardBalance> => {
const { data } = await apiClient.put(`/card-balances/${id}`, payload)
return data
},
delete: async (id: number): Promise<void> => {
await apiClient.delete(`/card-balances/${id}`)
},
download: async (id: number): Promise<Blob> => {
const { data } = await apiClient.get(`/card-balances/${id}/download`, {
responseType: 'blob',
})
return data
},
}

View File

@@ -0,0 +1,204 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { FormInput } from '@/components/formInput'
import { type CardBalance } from '@/features/cardBalance/api/cardBalanceApi'
import { useCreateCardBalance, useUpdateCardBalance } from '@/features/cardBalance/hooks/useCardBalance'
interface CardBalanceFormProps {
mode: 'create' | 'edit'
initialData?: CardBalance
cardBalanceId?: number
}
interface FormState {
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
interface FormErrors {
passport_series?: string
passport_number?: string
card_number?: string
card_expiry_month?: string
card_expiry_year?: string
}
// ─── Constants ────────────────────────────────────────────────────────────────
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: 'III-LB', label: 'III-LB' },
{ value: 'I-BN', label: 'I-BN' },
{ value: 'II-BN', label: 'II-BN' },
{ value: 'I-AH', label: 'I-AH' },
{ value: 'I-AS', label: 'I-AS' },
{ value: 'I-DZ', label: 'I-DZ' },
{ value: 'II-DZ', label: 'II-DZ' },
{ value: 'A', label: 'A' },
{ value: 'B', label: 'B' },
]
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
const val = String(i + 1).padStart(2, '0')
return { value: val, label: val }
})
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
const year = String(new Date().getFullYear() + i)
return { value: year, label: year }
})
const EMPTY_FORM: FormState = {
passport_series: '',
passport_number: '',
card_number: '',
card_expiry_month: '',
card_expiry_year: '',
}
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(form: FormState, t: (k: string, fallback: string) => string): FormErrors {
const errors: FormErrors = {}
if (!form.passport_series) errors.passport_series = t('Required', 'Pasport seriýasy hökmanydyr')
if (!form.passport_number) errors.passport_number = t('Required', 'Pasport belgisi hökmanydyr')
if (!form.card_number) errors.card_number = t('Required', 'Kart belgisi hökmanydyr')
if (!form.card_expiry_month) errors.card_expiry_month = t('Required', 'Möhleti (aý) hökmanydyr')
if (!form.card_expiry_year) errors.card_expiry_year = t('Required', 'Möhleti (ýyl) hökmanydyr')
return errors
}
// ─── Component ────────────────────────────────────────────────────────────────
export function CardBalanceForm({ mode, initialData, cardBalanceId }: CardBalanceFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const [form, setForm] = useState<FormState>(EMPTY_FORM)
const [errors, setErrors] = useState<FormErrors>({})
const createMutation = useCreateCardBalance()
const updateMutation = useUpdateCardBalance(cardBalanceId ?? 0)
const isPending = createMutation.isPending || updateMutation.isPending
useEffect(() => {
if (mode === 'edit' && initialData) {
setForm({
passport_series: initialData.passport_series,
passport_number: initialData.passport_number,
card_number: initialData.card_number,
card_expiry_month: initialData.card_expiry_month,
card_expiry_year: initialData.card_expiry_year,
})
}
}, [mode, initialData])
const setField = (field: keyof FormState) => (value: string) => {
setForm((prev) => ({ ...prev, [field]: value }))
if (errors[field]) setErrors((prev) => ({ ...prev, [field]: undefined }))
}
const handleSubmit = async () => {
const validationErrors = validate(form, t)
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors)
return
}
if (mode === 'create') {
await createMutation.mutateAsync(form)
navigate('/card-balances')
} else {
await updateMutation.mutateAsync(form)
navigate(`/card-balances/${cardBalanceId}`)
}
}
const handleCancel = () => {
if (mode === 'create') navigate('/card-balances')
else navigate(`/card-balances/${cardBalanceId}`)
}
return (
<div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Row 1 */}
<FormInput
type="searchable-select"
label={t('Passport series', 'Pasport seriýasy')}
value={form.passport_series}
onChange={setField('passport_series')}
options={PASSPORT_SERIES_OPTIONS}
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
error={errors.passport_series}
required
/>
<FormInput
type="text"
label={t('Passport number', 'Pasport belgisi')}
value={form.passport_number}
onChange={setField('passport_number')}
placeholder={t('Passport number', 'Pasport belgisi')}
error={errors.passport_number}
required
/>
{/* Row 2 — card number full width + 2 selects */}
<FormInput
type="text"
label={t('Card number', 'Kart belgisi')}
value={form.card_number}
onChange={setField('card_number')}
placeholder={t('Card number', 'Kart belgisi')}
error={errors.card_number}
required
/>
<div className="grid grid-cols-2 gap-3">
<FormInput
type="select"
label={t('Card expiry month', 'Kart Möhleti (aý)')}
value={form.card_expiry_month}
onChange={setField('card_expiry_month')}
options={MONTH_OPTIONS}
placeholder={t('Select', 'Saýlamak üçin basyň')}
error={errors.card_expiry_month}
required
/>
<FormInput
type="select"
label={t('Card expiry year', 'Kart Möhleti (ýyl)')}
value={form.card_expiry_year}
onChange={setField('card_expiry_year')}
options={YEAR_OPTIONS}
placeholder={t('Select', 'Saýlamak üçin basyň')}
error={errors.card_expiry_year}
required
/>
</div>
</div>
{/* Actions */}
<div className="flex justify-end gap-3 mt-6">
<Button variant="ghost" onClick={handleCancel} disabled={isPending}>
{t('Cancel', 'Ýatyr')}
</Button>
<Button onClick={handleSubmit} disabled={isPending}>
{isPending
? t('Saving...', 'Saklanýar...')
: mode === 'create'
? t('Create card balance', 'Kart galyndysy dörediň')
: t('Save changes', 'Üýtgetmeleri sakla')}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,96 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import {
cardBalancesApi,
type CardBalanceListParams,
type CreateCardBalancePayload,
type UpdateCardBalancePayload,
} from '../api/cardBalanceApi'
const QUERY_KEY = 'card-balances'
export function useCardBalances(params?: CardBalanceListParams) {
return useQuery({
queryKey: [QUERY_KEY, params],
queryFn: () => cardBalancesApi.getAll(params),
})
}
export function useCardBalance(id: number) {
return useQuery({
queryKey: [QUERY_KEY, id],
queryFn: () => cardBalancesApi.getById(id),
enabled: !!id,
})
}
export function useCreateCardBalance() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: CreateCardBalancePayload) => cardBalancesApi.create(payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card balance created successfully', 'Kart galyndysy üstünlikli döredildi'))
},
onError: () => {
toast.error(t('Failed to create card balance', 'Kart galyndysy döredilmedi'))
},
})
}
export function useUpdateCardBalance(id: number) {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: UpdateCardBalancePayload) => cardBalancesApi.update(id, payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card balance updated successfully', 'Kart galyndysy üstünlikli üýtgedildi'))
},
onError: () => {
toast.error(t('Failed to update card balance', 'Kart galyndysy üýtgedilmedi'))
},
})
}
export function useDeleteCardBalance() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (id: number) => cardBalancesApi.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card balance deleted successfully', 'Kart galyndysy üstünlikli öçürildi'))
},
onError: () => {
toast.error(t('Failed to delete card balance', 'Kart galyndysy öçürilmedi'))
},
})
}
export function useDownloadCardBalance() {
const { t } = useTranslation()
return useMutation({
mutationFn: async (id: number) => {
const blob = await cardBalancesApi.download(id)
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `card-balance-${id}.pdf`
a.click()
URL.revokeObjectURL(url)
},
onSuccess: () => {
toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi'))
},
onError: () => {
toast.error(t('Download failed', 'Ýüklemek başartmady'))
},
})
}

View File

@@ -0,0 +1,205 @@
import { apiClient } from '@/lib/api/client'
// ─── Types ────────────────────────────────────────────────────────────────────
export type CardPinStatus = 'pending' | 'approved' | 'rejected'
export interface CardPinItem {
id: string
card_type: string
card_type_label: string
card_number: string
created_at: string
province: string
province_label: string
branch: string
branch_label: string
first_name: string
last_name: string
father_name: string
birth_date: string
phone: string
status: CardPinStatus
note: string | null
passport_series: string
passport_number: string
passport_file_1: string | null
passport_file_2: string | null
passport_file_3: string | null
passport_file_4: string | null
created_by: string
created_by_label: string
}
export interface CardPinListParams {
page?: number
per_page?: number
search?: string
status?: CardPinStatus | ''
province?: string
}
export interface CardPinListResponse {
data: CardPinItem[]
meta: {
current_page: number
last_page: number
per_page: number
total: number
}
}
export interface CardPinCreatePayload {
status: CardPinStatus
note: string
card_type: string
card_number: string
province: string
branch: string
first_name: string
last_name: string
father_name: string
birth_date: string
phone: string
passport_series: string
passport_number: string
passport_file_1: File | null
passport_file_2: File | null
passport_file_3: File | null
passport_file_4: File | null
}
export type CardPinUpdatePayload = CardPinCreatePayload
// ─── API Functions ────────────────────────────────────────────────────────────
const MOCK_CARD_PINS: CardPinItem[] = [
{
id: '1',
card_type: 'altyn_asyr',
card_type_label: 'Altyn Asyr',
card_number: '8600123456789012',
created_at: '2024-05-07 10:00',
province: 'ashgabat',
province_label: 'Aşgabat',
branch: '1',
branch_label: 'Merkezi şahamça',
first_name: 'Aman',
last_name: 'Amanow',
father_name: 'Amanowiç',
birth_date: '1990-01-01',
phone: '99365123456',
status: 'pending',
note: 'Test bellik',
passport_series: 'I-MR',
passport_number: '123456',
passport_file_1: null,
passport_file_2: null,
passport_file_3: null,
passport_file_4: null,
created_by: '1',
created_by_label: 'Admin',
},
{
id: '2',
card_type: 'visa',
card_type_label: 'Visa',
card_number: '4400123456789012',
created_at: '2024-05-07 11:30',
province: 'mary',
province_label: 'Mary',
branch: '2',
branch_label: 'Mary şahamçasy',
first_name: 'Berdi',
last_name: 'Berdiyew',
father_name: 'Berdiyewiç',
birth_date: '1995-05-05',
phone: '99361112233',
status: 'approved',
note: null,
passport_series: 'I-LB',
passport_number: '654321',
passport_file_1: null,
passport_file_2: null,
passport_file_3: null,
passport_file_4: null,
created_by: '1',
created_by_label: 'Admin',
},
]
export const cardPinApi = {
list: async (params: CardPinListParams): Promise<CardPinListResponse> => {
// Mock data return
return {
data: MOCK_CARD_PINS,
meta: {
current_page: params.page || 1,
last_page: 1,
per_page: params.per_page || 25,
total: MOCK_CARD_PINS.length,
}
}
const { data } = await apiClient.get('/card-pins', { params })
return data
},
getById: async (id: string): Promise<CardPinItem> => {
const mock = MOCK_CARD_PINS.find(p => p.id === id)
if (mock) return mock
const { data } = await apiClient.get(`/card-pins/${id}`)
return data
},
create: (payload: CardPinCreatePayload): Promise<CardPinItem> => {
const form = buildFormData(payload)
return apiClient.post('/card-pins', form, {
headers: { 'Content-Type': 'multipart/form-data' },
}).then((r) => r.data)
},
update: (id: string, payload: CardPinUpdatePayload): Promise<CardPinItem> => {
const form = buildFormData(payload)
form.append('_method', 'PUT')
return apiClient.post(`/card-pins/${id}`, form, {
headers: { 'Content-Type': 'multipart/form-data' },
}).then((r) => r.data)
},
delete: (id: string): Promise<void> =>
apiClient.delete(`/card-pins/${id}`).then((r) => r.data),
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
function buildFormData(payload: CardPinCreatePayload): FormData {
const form = new FormData()
const textFields: (keyof CardPinCreatePayload)[] = [
'status', 'note', 'card_type', 'card_number',
'province', 'branch',
'first_name', 'last_name', 'father_name',
'birth_date', 'phone',
'passport_series', 'passport_number',
]
for (const key of textFields) {
const val = payload[key]
if (val !== null && val !== undefined) {
form.append(key, String(val))
}
}
const fileFields: (keyof CardPinCreatePayload)[] = [
'passport_file_1', 'passport_file_2', 'passport_file_3', 'passport_file_4',
]
for (const key of fileFields) {
const file = payload[key]
if (file instanceof File) form.append(key, file)
}
return form
}

View File

@@ -0,0 +1,416 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { FormInput } from '@/components/formInput'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import type { CardPinItem, CardPinCreatePayload } from '@/features/cardPins/api/cardPinApi'
// ─── Types ────────────────────────────────────────────────────────────────────
interface CardPinFormProps {
mode: 'create' | 'edit'
initialData?: CardPinItem
onSubmit: (payload: CardPinCreatePayload) => void
isSubmitting: boolean
}
interface FormState {
status: string
note: string
card_type: string
card_number: string
province: string
branch: string
first_name: string
last_name: string
father_name: string
birth_date: string
phone: string
passport_series: string
passport_number: string
passport_file_1: File | null
passport_file_2: File | null
passport_file_3: File | null
passport_file_4: File | null
}
type FormErrors = Partial<Record<keyof FormState, string>>
// ─── Constants ────────────────────────────────────────────────────────────────
const STATUS_OPTIONS = [
{ value: 'pending', label: 'Garaşylýar' },
{ value: 'approved', label: 'Tassyklandy' },
{ value: 'rejected', label: 'Ret edildi' },
]
// These would typically come from API — using static options as placeholder
const CARD_TYPE_OPTIONS = [
{ value: 'altyn_asyr', label: 'Altyn Asyr' },
{ value: 'visa', label: 'Visa' },
{ value: 'mastercard', label: 'MasterCard' },
]
const PASSPORT_SERIES_OPTIONS = [
{ value: 'I', label: 'I' },
{ value: 'II', label: 'II' },
{ value: 'I-MR', label: 'I-MR' },
{ value: 'II-MR',label: 'II-MR' },
]
const PROVINCE_OPTIONS = [
{ value: 'ashgabat', label: 'Aşgabat' },
{ value: 'mary', label: 'Mary' },
{ value: 'dasoguz', label: 'Daşoguz' },
{ value: 'lebap', label: 'Lebap' },
{ value: 'balkan', label: 'Balkan' },
{ value: 'ahal', label: 'Ahal' },
]
// ─── 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,
}
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(form: FormState, mode: 'create' | 'edit'): FormErrors {
const errors: FormErrors = {}
if (!form.status) errors.status = 'Status hökmany'
if (!form.card_type) errors.card_type = 'Kart görnüşi hökmany'
if (!form.card_number) errors.card_number = 'Kart belgisi hökmany'
if (!form.province) errors.province = 'Welaýat hökmany'
if (!form.branch) errors.branch = 'Şahamça hökmany'
if (!form.first_name) errors.first_name = 'Ady hökmany'
if (!form.last_name) errors.last_name = 'Familiýasy hökmany'
if (!form.birth_date) errors.birth_date = 'Doglan güni hökmany'
if (!form.phone) errors.phone = 'Telefon hökmany'
if (!form.passport_series) errors.passport_series = 'Pasport seriýasy hökmany'
if (!form.passport_number) errors.passport_number = 'Pasport belgisi hökmany'
if (mode === 'create') {
if (!form.passport_file_1) errors.passport_file_1 = 'Pasport (sahypa 1) hökmany'
if (!form.passport_file_2) errors.passport_file_2 = 'Pasport (2-3-nji sahypa) hökmany'
if (!form.passport_file_3) errors.passport_file_3 = 'Pasport (8-9 sahypa) hökmany'
if (!form.passport_file_4) errors.passport_file_4 = 'Pasport (32-nji sahypa) hökmany'
}
return errors
}
// ─── Component ────────────────────────────────────────────────────────────────
export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardPinFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const [form, setForm] = useState<FormState>(defaultState)
const [errors, setErrors] = useState<FormErrors>({})
// Hydrate form when editing
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])
const set = <K extends keyof FormState>(key: K, value: FormState[K]) => {
setForm((prev) => ({ ...prev, [key]: value }))
if (errors[key]) setErrors((prev) => ({ ...prev, [key]: undefined }))
}
const handleSubmit = () => {
const errs = validate(form, mode)
if (Object.keys(errs).length > 0) {
setErrors(errs)
return
}
onSubmit({
status: form.status as CardPinCreatePayload['status'],
note: form.note,
card_type: form.card_type,
card_number: form.card_number,
province: form.province,
branch: form.branch,
first_name: form.first_name,
last_name: form.last_name,
father_name: form.father_name,
birth_date: form.birth_date,
phone: form.phone,
passport_series: form.passport_series,
passport_number: form.passport_number,
passport_file_1: form.passport_file_1,
passport_file_2: form.passport_file_2,
passport_file_3: form.passport_file_3,
passport_file_4: form.passport_file_4,
})
}
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äň')
return (
<div className="max-w-4xl mx-auto space-y-6">
<h1 className="text-2xl font-bold text-foreground">{title}</h1>
{/* ── Status & Note ────────────────────────────────────────────────── */}
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
<FormInput
type="select"
label={t('cardPin.status', 'Status')}
value={form.status}
onChange={(v) => set('status', v)}
options={STATUS_OPTIONS}
error={errors.status}
required
/>
<FormInput
type="text"
label={t('cardPin.note', 'Bellik')}
value={form.note}
onChange={(v) => set('note', v)}
placeholder={t('cardPin.notePlaceholder', 'Bellik')}
/>
</section>
{/* ── Kart ─────────────────────────────────────────────────────────── */}
<section className="bg-card border border-border rounded-lg p-6">
<h2 className="text-base font-semibold text-foreground mb-4">
{t('cardPin.cardSection', 'Kart')}
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('cardPin.cardType', 'Kart görnüşi')}
value={form.card_type}
onChange={(v) => set('card_type', v)}
options={CARD_TYPE_OPTIONS}
error={errors.card_type}
required
/>
<FormInput
type="text"
label={t('cardPin.cardNumber', 'Kart belgisi')}
value={form.card_number}
onChange={(v) => set('card_number', v)}
placeholder={t('cardPin.cardNumberPlaceholder', 'Kart belgisi')}
error={errors.card_number}
required
/>
</div>
</section>
{/* ── Lokasiýa ─────────────────────────────────────────────────────── */}
<section className="bg-card border border-border rounded-lg p-6">
<h2 className="text-base font-semibold text-foreground mb-4">
{t('cardPin.locationSection', 'Lokasiýa')}
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('cardPin.province', 'Welaýat')}
value={form.province}
onChange={(v) => { set('province', v); set('branch', '') }}
options={PROVINCE_OPTIONS}
error={errors.province}
required
/>
<FormInput
type="searchable-select"
label={t('cardPin.branch', 'Şahamça')}
value={form.branch}
onChange={(v) => set('branch', v)}
options={[]} // Populated dynamically based on province from API
placeholder={t('cardPin.branchPlaceholder', 'Saýlamak üçin basyň')}
error={errors.branch}
required
/>
</div>
</section>
{/* ── Şahsy maglumatlar ─────────────────────────────────────────────── */}
<section className="bg-card border border-border rounded-lg p-6">
<h2 className="text-base font-semibold text-foreground mb-4">
{t('cardPin.personalSection', 'Şahsy maglumatlar')}
</h2>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<FormInput
type="text"
label={t('cardPin.firstName', 'Ady')}
value={form.first_name}
onChange={(v) => set('first_name', v)}
placeholder={t('cardPin.firstName', 'Ady')}
error={errors.first_name}
required
/>
<FormInput
type="text"
label={t('cardPin.lastName', 'Familiýasy')}
value={form.last_name}
onChange={(v) => set('last_name', v)}
placeholder={t('cardPin.lastName', 'Familiýasy')}
error={errors.last_name}
required
/>
<FormInput
type="text"
label={t('cardPin.fatherName', 'Atasynyň ady')}
value={form.father_name}
onChange={(v) => set('father_name', v)}
placeholder={t('cardPin.fatherName', 'Atasynyň ady')}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4">
<FormInput
type="date"
label={t('cardPin.birthDate', 'Doglan güni')}
value={form.birth_date}
onChange={(v) => set('birth_date', v)}
error={errors.birth_date}
required
/>
<FormInput
type="phone"
label={t('cardPin.phone', 'Telefon')}
value={form.phone}
onChange={(v) => set('phone', v)}
error={errors.phone}
required
/>
</div>
</section>
{/* ── Pasport ───────────────────────────────────────────────────────── */}
<section className="bg-card border border-border rounded-lg p-6">
<h2 className="text-base font-semibold text-foreground mb-4">
{t('cardPin.passportSection', 'Pasport')}
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
<FormInput
type="searchable-select"
label={t('cardPin.passportSeries', 'Pasport seriýasy')}
value={form.passport_series}
onChange={(v) => set('passport_series', v)}
options={PASSPORT_SERIES_OPTIONS}
error={errors.passport_series}
required
/>
<FormInput
type="text"
label={t('cardPin.passportNumber', 'Pasport belgisi')}
value={form.passport_number}
onChange={(v) => set('passport_number', v)}
placeholder={t('cardPin.passportNumber', 'Pasport belgisi')}
error={errors.passport_number}
required
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="file"
label={t('cardPin.passportFile1', 'Pasport (sahypa 1)')}
onFileChange={(f) => set('passport_file_1', f)}
fileValue={form.passport_file_1}
accept="image/*,.pdf"
error={errors.passport_file_1}
required={mode === 'create'}
/>
<FormInput
type="file"
label={t('cardPin.passportFile2', 'Pasport (2-3-nji sahypa)')}
onFileChange={(f) => set('passport_file_2', f)}
fileValue={form.passport_file_2}
accept="image/*,.pdf"
error={errors.passport_file_2}
required={mode === 'create'}
/>
<FormInput
type="file"
label={t('cardPin.passportFile3', 'Pasport (8-9 sahypa)')}
onFileChange={(f) => set('passport_file_3', f)}
fileValue={form.passport_file_3}
accept="image/*,.pdf"
error={errors.passport_file_3}
required={mode === 'create'}
/>
<FormInput
type="file"
label={t('cardPin.passportFile4', 'Pasport (32-nji sahypa)')}
onFileChange={(f) => set('passport_file_4', f)}
fileValue={form.passport_file_4}
accept="image/*,.pdf"
error={errors.passport_file_4}
required={mode === 'create'}
/>
</div>
</section>
{/* ── Actions ───────────────────────────────────────────────────────── */}
<div className="flex items-center justify-end gap-3 pb-6">
<Button
type="button"
variant="outline"
onClick={() => navigate('/card-pins')}
disabled={isSubmitting}
>
{t('common.cancel', 'Ýatyr')}
</Button>
<Button
type="button"
onClick={handleSubmit}
disabled={isSubmitting}
className="min-w-[180px]"
>
{isSubmitting ? (
<Spinner className="size-4" />
) : (
submitLabel
)}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,86 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import { cardPinApi, type CardPinListParams, type CardPinCreatePayload, type CardPinUpdatePayload } from '../api/cardPinApi'
export const CARD_PIN_KEYS = {
all: ['card-pins'] as const,
lists: () => [...CARD_PIN_KEYS.all, 'list'] as const,
list: (p: CardPinListParams) => [...CARD_PIN_KEYS.lists(), p] as const,
detail: (id: string) => [...CARD_PIN_KEYS.all, 'detail', id] as const,
}
// ─── List ─────────────────────────────────────────────────────────────────────
export function useCardPins(params: CardPinListParams) {
return useQuery({
queryKey: CARD_PIN_KEYS.list(params),
queryFn: () => cardPinApi.list(params),
placeholderData: (prev) => prev,
})
}
// ─── Detail ───────────────────────────────────────────────────────────────────
export function useCardPin(id: string) {
return useQuery({
queryKey: CARD_PIN_KEYS.detail(id),
queryFn: () => cardPinApi.getById(id),
enabled: !!id,
})
}
// ─── Create ───────────────────────────────────────────────────────────────────
export function useCreateCardPin() {
const qc = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: CardPinCreatePayload) => cardPinApi.create(payload),
onSuccess: () => {
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
toast.success(t('cardPin.createSuccess', 'Kart pin bukja döredildi'))
},
onError: () => {
toast.error(t('cardPin.createError', 'Döretmek başartmady'))
},
})
}
// ─── Update ───────────────────────────────────────────────────────────────────
export function useUpdateCardPin(id: string) {
const qc = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: CardPinUpdatePayload) => cardPinApi.update(id, payload),
onSuccess: () => {
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.detail(id) })
toast.success(t('cardPin.updateSuccess', 'Kart pin bukja üýtgedildi'))
},
onError: () => {
toast.error(t('cardPin.updateError', 'Üýtgetmek başartmady'))
},
})
}
// ─── Delete ───────────────────────────────────────────────────────────────────
export function useDeleteCardPin() {
const qc = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (id: string) => cardPinApi.delete(id),
onSuccess: () => {
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
toast.success(t('cardPin.deleteSuccess', 'Kart pin bukja pozuldy'))
},
onError: () => {
toast.error(t('cardPin.deleteError', 'Pozmak başartmady'))
},
})
}

View File

@@ -0,0 +1,142 @@
import {apiClient} from '@/lib/api/client'
// ─── Types ────────────────────────────────────────────────────────────────────
export type CardRequisiteStatus = 'pending' | 'approved' | 'rejected'
export interface CardRequisite {
id: string
status: CardRequisiteStatus
note: string
created_at: string
// Card
card_type: string
card_number: string
card_expiry_month: string
card_expiry_year: string
// Location
province_id: string
branch_id: string
province_name?: string
branch_name?: string
// Personal
first_name: string
last_name: string
middle_name: string
birth_date: string
phone: string
// Passport
passport_series: string
passport_number: string
passport_page1_url?: string
passport_page2_3_url?: string
passport_page8_9_url?: string
passport_page32_url?: string
}
export interface CardRequisiteListResponse {
data: CardRequisite[]
total: number
page: number
per_page: number
}
export interface CreateCardRequisitePayload {
status: CardRequisiteStatus
note: 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
middle_name: string
birth_date: string
phone: string
passport_series: string
passport_number: string
passport_page1?: File
passport_page2_3?: File
passport_page8_9?: File
passport_page32?: File
}
export type UpdateCardRequisitePayload = CreateCardRequisitePayload
export interface CardRequisiteListParams {
page?: number
per_page?: number
search?: string
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
function buildFormData(payload: CreateCardRequisitePayload): FormData {
const fd = new FormData()
const textFields: (keyof Omit<
CreateCardRequisitePayload,
'passport_page1' | 'passport_page2_3' | 'passport_page8_9' | 'passport_page32'
>)[] = [
'status', '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',
]
textFields.forEach((key) => {
const val = payload[key]
if (val !== undefined && val !== null) fd.append(key, val)
})
if (payload.passport_page1) fd.append('passport_page1', payload.passport_page1)
if (payload.passport_page2_3) fd.append('passport_page2_3', payload.passport_page2_3)
if (payload.passport_page8_9) fd.append('passport_page8_9', payload.passport_page8_9)
if (payload.passport_page32) fd.append('passport_page32', payload.passport_page32)
return fd
}
// ─── API functions ────────────────────────────────────────────────────────────
export const cardRequisitesApi = {
getAll: async (params?: CardRequisiteListParams): Promise<CardRequisiteListResponse> => {
const { data } = await apiClient.get('/card-requisites', { params })
return data
},
getById: async (id: string): Promise<CardRequisite> => {
const { data } = await apiClient.get(`/card-requisites/${id}`)
return data
},
create: async (payload: CreateCardRequisitePayload): Promise<CardRequisite> => {
const { data } = await apiClient.post('/card-requisites', buildFormData(payload), {
headers: { 'Content-Type': 'multipart/form-data' },
})
return data
},
update: async (id: string, payload: UpdateCardRequisitePayload): Promise<CardRequisite> => {
const { data } = await apiClient.post(`/card-requisites/${id}`, buildFormData(payload), {
headers: { 'Content-Type': 'multipart/form-data' },
})
return data
},
delete: async (id: string): Promise<void> => {
await apiClient.delete(`/card-requisites/${id}`)
},
download: async (id: string): Promise<Blob> => {
const { data } = await apiClient.get(`/card-requisites/${id}/download`, {
responseType: 'blob',
})
return data
},
}

View File

@@ -0,0 +1,501 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { FormInput } from '@/components/formInput'
import type { CardRequisite, CardRequisiteStatus, CreateCardRequisitePayload } from '../api/cardRequisitesApi'
import { useCreateCardRequisite, useUpdateCardRequisite } from '../hooks/useCardRequisites'
// ─── Types ────────────────────────────────────────────────────────────────────
interface CardRequisiteFormProps {
mode: 'create' | 'edit'
initialData?: CardRequisite
cardRequisiteId?: string
}
interface FormState {
status: string
note: 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
middle_name: string
birth_date: string
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
}
// ─── Constants ────────────────────────────────────────────────────────────────
const STATUS_OPTIONS = [
{ value: 'pending', label: 'Garaşylýar' },
{ value: 'approved', label: 'Tassyklanan' },
{ value: 'rejected', label: 'Ret edilen' },
]
const CARD_TYPE_OPTIONS = [
{ 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: 'III-LB', label: 'III-LB' },
{ 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: '4', label: 'Daşoguz' },
{ value: '5', label: 'Lebap' },
{ value: '6', label: 'Mary' },
]
const BRANCH_OPTIONS: Record<string, { value: string; label: string }[]> = {
'1': [{ value: '11', label: 'Köpetdag' }, { value: '12', label: 'Çandybil' }, { value: '13', label: 'Büzmeyin' }],
'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' }],
}
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
const val = String(i + 1).padStart(2, '0')
return { value: val, label: val }
})
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
const year = String(new Date().getFullYear() + 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 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,
): FormErrors {
const errors: FormErrors = {}
if (!form.status) errors.status = t('Status is required', 'Status hökmanydyr')
if (!form.card_type) errors.card_type = t('Card type is required', 'Görnüşi hökmanydyr')
if (!form.card_number) errors.card_number = t('Card number is required', 'Kart belgisi hökmanydyr')
if (!form.card_expiry_month) errors.card_expiry_month = t('Expiry month is required', 'Möhleti (aý) hökmanydyr')
if (!form.card_expiry_year) errors.card_expiry_year = t('Expiry year is required', 'Möhleti (ýyl) hökmanydyr')
if (!form.province_id) errors.province_id = t('Province is required', 'Welaýat hökmanydyr')
if (!form.branch_id) errors.branch_id = t('Branch is required', 'Şahamça hökmanydyr')
if (!form.first_name) errors.first_name = t('First name is required', 'Ady hökmanydyr')
if (!form.last_name) errors.last_name = t('Last name is required', 'Familiýasy hökmanydyr')
if (!form.birth_date) errors.birth_date = t('Birth date is required', 'Doglan güni hökmanydyr')
if (!form.phone) errors.phone = t('Phone is required', 'Telefon hökmanydyr')
if (!form.passport_series) errors.passport_series = t('Passport series is required', 'Pasport seriýasy hökmanydyr')
if (!form.passport_number) errors.passport_number = t('Passport number is required', 'Pasport belgisi hökmanydyr')
// Files only required on create
if (mode === 'create') {
if (!files.passport_page1) errors.passport_page1 = t('Required', 'Hökmanydyr')
if (!files.passport_page2_3) errors.passport_page2_3 = t('Required', 'Hökmanydyr')
if (!files.passport_page8_9) errors.passport_page8_9 = t('Required', 'Hökmanydyr')
if (!files.passport_page32) errors.passport_page32 = t('Required', 'Hökmanydyr')
}
return errors
}
// ─── Section header ───────────────────────────────────────────────────────────
function SectionTitle({ children }: { children: React.ReactNode }) {
return (
<h2 className="text-base font-semibold text-foreground mt-6 mb-3">{children}</h2>
)
}
// ─── Component ────────────────────────────────────────────────────────────────
export function CardRequisiteForm({
mode,
initialData,
cardRequisiteId,
}: CardRequisiteFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const [form, setForm] = useState<FormState>(EMPTY_FORM)
const [files, setFiles] = useState<FileState>(EMPTY_FILES)
const [errors, setErrors] = useState<FormErrors>({})
const createMutation = useCreateCardRequisite()
const updateMutation = useUpdateCardRequisite(cardRequisiteId ?? '')
const isPending = createMutation.isPending || updateMutation.isPending
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])
const setField = (field: keyof FormState) => (value: string) => {
setForm((prev) => {
const next = { ...prev, [field]: value }
// Reset branch when province changes
if (field === 'province_id') next.branch_id = ''
return next
})
if (errors[field as keyof FormErrors])
setErrors((prev) => ({ ...prev, [field]: undefined }))
}
const setFile = (field: keyof FileState) => (file: File | null) => {
setFiles((prev) => ({ ...prev, [field]: file }))
if (errors[field as keyof FormErrors])
setErrors((prev) => ({ ...prev, [field]: undefined }))
}
const handleSubmit = async () => {
const validationErrors = validate(form, files, mode, t)
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors)
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 }),
}
if (mode === 'create') {
await createMutation.mutateAsync(payload)
navigate('/card-requisites')
} else {
await updateMutation.mutateAsync(payload)
navigate(`/card-requisites/${cardRequisiteId}`)
}
}
const handleCancel = () => {
if (mode === 'create') navigate('/card-requisites')
else navigate(`/card-requisites/${cardRequisiteId}`)
}
const branchOptions = BRANCH_OPTIONS[form.province_id] ?? []
return (
<div className="space-y-0">
{/* ── General ── */}
<div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormInput
type="select"
label={t('Status', 'Status')}
value={form.status}
onChange={setField('status')}
options={STATUS_OPTIONS}
error={errors.status}
required
/>
<FormInput
type="text"
label={t('Note', 'Bellik')}
value={form.note}
onChange={setField('note')}
placeholder={t('Note', 'Bellik')}
/>
</div>
</div>
{/* ── Kart ── */}
<SectionTitle>{t('Card', 'Kart')}</SectionTitle>
<div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<FormInput
type="select"
label={t('Card type', 'Görnüşi')}
value={form.card_type}
onChange={setField('card_type')}
options={CARD_TYPE_OPTIONS}
placeholder="—"
error={errors.card_type}
required
/>
<FormInput
type="text"
label={t('Card number', 'Kart belgisi')}
value={form.card_number}
onChange={setField('card_number')}
placeholder={t('Card number', 'Kart belgisi')}
error={errors.card_number}
required
/>
<FormInput
type="select"
label={t('Card expiry month', 'Kart Möhleti (aý)')}
value={form.card_expiry_month}
onChange={setField('card_expiry_month')}
options={MONTH_OPTIONS}
placeholder={t('Select', 'Saýlamak üçin basyň')}
error={errors.card_expiry_month}
required
/>
<FormInput
type="select"
label={t('Card expiry year', 'Kart Möhleti (ýyl)')}
value={form.card_expiry_year}
onChange={setField('card_expiry_year')}
options={YEAR_OPTIONS}
placeholder={t('Select', 'Saýlamak üçin basyň')}
error={errors.card_expiry_year}
required
/>
</div>
</div>
{/* ── Lokasiýa ── */}
<SectionTitle>{t('Location', 'Lokasiýa')}</SectionTitle>
<div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormInput
type="select"
label={t('Province', 'Welaýat')}
value={form.province_id}
onChange={setField('province_id')}
options={PROVINCE_OPTIONS}
placeholder={t('Ashgabat', 'Aşgabat')}
error={errors.province_id}
required
/>
<FormInput
type="searchable-select"
label={t('Branch', 'Şahamça')}
value={form.branch_id}
onChange={setField('branch_id')}
options={branchOptions}
placeholder={t('Select', 'Saýlamak üçin basyň')}
error={errors.branch_id}
disabled={!form.province_id}
required
/>
</div>
</div>
{/* ── Şahsy maglumatlar ── */}
<SectionTitle>{t('Personal information', 'Şahsy maglumatlar')}</SectionTitle>
<div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<FormInput
type="text"
label={t('First name', 'Ady')}
value={form.first_name}
onChange={setField('first_name')}
placeholder={t('First name', 'Ady')}
error={errors.first_name}
required
/>
<FormInput
type="text"
label={t('Last name', 'Familiýasy')}
value={form.last_name}
onChange={setField('last_name')}
placeholder={t('Last name', 'Familiýasy')}
error={errors.last_name}
required
/>
<FormInput
type="text"
label={t("Father's name", 'Atasynyň ady')}
value={form.middle_name}
onChange={setField('middle_name')}
placeholder={t("Father's name", 'Atasynyň ady')}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
<FormInput
type="date"
label={t('Birth date', 'Doglan güni')}
value={form.birth_date}
onChange={setField('birth_date')}
error={errors.birth_date}
required
/>
<FormInput
type="phone"
label={t('Phone', 'Telefon')}
value={form.phone}
onChange={setField('phone')}
placeholder="63 21 87 04"
error={errors.phone}
required
/>
</div>
</div>
{/* ── Pasport ── */}
<SectionTitle>{t('Passport', 'Pasport')}</SectionTitle>
<div className="rounded-lg border border-border bg-card p-6 space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('Passport series', 'Pasport seriýasy')}
value={form.passport_series}
onChange={setField('passport_series')}
options={PASSPORT_SERIES_OPTIONS}
placeholder={t('Select', 'Saýlamak üçin basyň')}
error={errors.passport_series}
required
/>
<FormInput
type="text"
label={t('Passport number', 'Pasport belgisi')}
value={form.passport_number}
onChange={setField('passport_number')}
placeholder={t('Passport number', 'Pasport belgisi')}
error={errors.passport_number}
required
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormInput
type="file"
label={t('Passport (page 1)', 'Pasport (sahypa 1)')}
accept="image/*,.pdf"
fileValue={files.passport_page1}
onFileChange={setFile('passport_page1')}
error={errors.passport_page1}
required={mode === 'create'}
/>
<FormInput
type="file"
label={t('Passport (pages 2-3)', 'Pasport (2-3-nji sahypa)')}
accept="image/*,.pdf"
fileValue={files.passport_page2_3}
onFileChange={setFile('passport_page2_3')}
error={errors.passport_page2_3}
required={mode === 'create'}
/>
<FormInput
type="file"
label={t('Passport (pages 8-9)', 'Pasport (8-9 sahypa)')}
accept="image/*,.pdf"
fileValue={files.passport_page8_9}
onFileChange={setFile('passport_page8_9')}
error={errors.passport_page8_9}
required={mode === 'create'}
/>
<FormInput
type="file"
label={t('Passport (page 32)', 'Pasport (32-nji sahypa)')}
accept="image/*,.pdf"
fileValue={files.passport_page32}
onFileChange={setFile('passport_page32')}
error={errors.passport_page32}
required={mode === 'create'}
/>
</div>
</div>
{/* ── Actions ── */}
<div className="flex justify-end gap-3 mt-6">
<Button variant="ghost" onClick={handleCancel} disabled={isPending}>
{t('Cancel', 'Ýatyr')}
</Button>
<Button onClick={handleSubmit} disabled={isPending}>
{isPending
? t('Saving...', 'Saklanýar...')
: mode === 'create'
? t('Create card requisite order', 'Kart rekwiziti üçin sargyt dörediň')
: t('Save changes', 'Üýtgetmeleri sakla')}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,108 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import {
cardRequisitesApi,
type CardRequisiteListParams,
type CreateCardRequisitePayload,
type UpdateCardRequisitePayload,
} from '../api/cardRequisitesApi'
const QUERY_KEY = 'card-requisites'
// ─── List ─────────────────────────────────────────────────────────────────────
export function useCardRequisites(params?: CardRequisiteListParams) {
return useQuery({
queryKey: [QUERY_KEY, params],
queryFn: () => cardRequisitesApi.getAll(params),
})
}
// ─── Single ───────────────────────────────────────────────────────────────────
export function useCardRequisite(id: string) {
return useQuery({
queryKey: [QUERY_KEY, id],
queryFn: () => cardRequisitesApi.getById(id),
enabled: !!id,
})
}
// ─── Create ───────────────────────────────────────────────────────────────────
export function useCreateCardRequisite() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: CreateCardRequisitePayload) => cardRequisitesApi.create(payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card requisite created successfully', 'Kart rekwiziti üstünlikli döredildi'))
},
onError: () => {
toast.error(t('Failed to create card requisite', 'Kart rekwiziti döredilmedi'))
},
})
}
// ─── Update ───────────────────────────────────────────────────────────────────
export function useUpdateCardRequisite(id: string) {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: UpdateCardRequisitePayload) => cardRequisitesApi.update(id, payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card requisite updated successfully', 'Kart rekwiziti üstünlikli üýtgedildi'))
},
onError: () => {
toast.error(t('Failed to update card requisite', 'Kart rekwiziti üýtgedilmedi'))
},
})
}
// ─── Delete ───────────────────────────────────────────────────────────────────
export function useDeleteCardRequisite() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (id: string) => cardRequisitesApi.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card requisite deleted successfully', 'Kart rekwiziti üstünlikli öçürildi'))
},
onError: () => {
toast.error(t('Failed to delete card requisite', 'Kart rekwiziti öçürilmedi'))
},
})
}
// ─── Download ─────────────────────────────────────────────────────────────────
export function useDownloadCardRequisite() {
const { t } = useTranslation()
return useMutation({
mutationFn: async (id: string) => {
const blob = await cardRequisitesApi.download(id)
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `card-requisite-${id}.pdf`
a.click()
URL.revokeObjectURL(url)
},
onSuccess: () => {
toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi'))
},
onError: () => {
toast.error(t('Download failed', 'Ýüklemek başartmady'))
},
})
}

View File

@@ -0,0 +1,120 @@
import {apiClient} from '@/lib/api/client'
// ─── Types ────────────────────────────────────────────────────────────────────
export interface CardTransaction {
id: number
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
export interface CardTransactionListResponse {
data: CardTransaction[]
total: number
page: number
per_page: number
}
export interface CreateCardTransactionPayload {
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
export type UpdateCardTransactionPayload = CreateCardTransactionPayload
export interface CardTransactionListParams {
page?: number
per_page?: number
search?: string
}
// ─── API functions ────────────────────────────────────────────────────────────
const MOCK_CARD_TRANSACTIONS: CardTransaction[] = [
{
id: 1,
passport_series: 'AA',
passport_number: '1234567',
card_number: '8600123456789012',
card_expiry_month: '12',
card_expiry_year: '28',
},
{
id: 2,
passport_series: 'AB',
passport_number: '7654321',
card_number: '9860123456789012',
card_expiry_month: '05',
card_expiry_year: '27',
},
{
id: 3,
passport_series: 'AC',
passport_number: '1122334',
card_number: '4400123456789012',
card_expiry_month: '08',
card_expiry_year: '26',
},
{
id: 4,
passport_series: 'KA',
passport_number: '9988776',
card_number: '5300123456789012',
card_expiry_month: '01',
card_expiry_year: '30',
},
{
id: 5,
passport_series: 'KB',
passport_number: '5566778',
card_number: '6200123456789012',
card_expiry_month: '03',
card_expiry_year: '29',
},
]
export const cardTransactionsApi = {
getAll: async (params?: CardTransactionListParams): Promise<CardTransactionListResponse> => {
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz:
return { data: MOCK_CARD_TRANSACTIONS, total: MOCK_CARD_TRANSACTIONS.length, page: params?.page || 1, per_page: params?.per_page || 10 }
const { data } = await apiClient.get('/card-transactions', { params })
return data
},
getById: async (id: number): Promise<CardTransaction> => {
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz:
const mock = MOCK_CARD_TRANSACTIONS.find(t => t.id === id)
if (mock) return mock
const { data } = await apiClient.get(`/card-transactions/${id}`)
return data
},
create: async (payload: CreateCardTransactionPayload): Promise<CardTransaction> => {
const { data } = await apiClient.post('/card-transactions', payload)
return data
},
update: async (id: number, payload: UpdateCardTransactionPayload): Promise<CardTransaction> => {
const { data } = await apiClient.put(`/card-transactions/${id}`, payload)
return data
},
delete: async (id: number): Promise<void> => {
await apiClient.delete(`/card-transactions/${id}`)
},
download: async (id: number): Promise<Blob> => {
const { data } = await apiClient.get(`/card-transactions/${id}/download`, {
responseType: 'blob',
})
return data
},
}

View File

@@ -0,0 +1,218 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { FormInput } from '@/components/formInput'
import type { CardTransaction } from '../api/cardTransactionsApi'
import { useCreateCardTransaction, useUpdateCardTransaction } from '../hooks/useCardTransactions'
// ─── Types ────────────────────────────────────────────────────────────────────
interface CardTransactionFormProps {
mode: 'create' | 'edit'
initialData?: CardTransaction
cardTransactionId?: number
}
interface FormState {
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
interface FormErrors {
passport_series?: string
passport_number?: string
card_number?: string
card_expiry_month?: string
card_expiry_year?: string
}
// ─── Constants ────────────────────────────────────────────────────────────────
const PASSPORT_SERIES_OPTIONS = [
{ 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' },
]
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
const val = String(i + 1).padStart(2, '0')
return { value: val, label: val }
})
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
const year = String(new Date().getFullYear() + i)
return { value: year, label: year }
})
const EMPTY_FORM: FormState = {
passport_series: '',
passport_number: '',
card_number: '',
card_expiry_month: '',
card_expiry_year: '',
}
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(form: FormState, t: (k: string, fallback: string) => string): FormErrors {
const errors: FormErrors = {}
if (!form.passport_series)
errors.passport_series = t('Passport series is required', 'Pasport seriýasy hökmanydyr')
if (!form.passport_number)
errors.passport_number = t('Passport number is required', 'Pasport belgisi hökmanydyr')
if (!form.card_number)
errors.card_number = t('Card number is required', 'Kart belgisi hökmanydyr')
if (!form.card_expiry_month)
errors.card_expiry_month = t('Expiry month is required', 'Möhleti (aý) hökmanydyr')
if (!form.card_expiry_year)
errors.card_expiry_year = t('Expiry year is required', 'Möhleti (ýyl) hökmanydyr')
return errors
}
// ─── Component ────────────────────────────────────────────────────────────────
export function CardTransactionForm({
mode,
initialData,
cardTransactionId,
}: CardTransactionFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const [form, setForm] = useState<FormState>(EMPTY_FORM)
const [errors, setErrors] = useState<FormErrors>({})
const createMutation = useCreateCardTransaction()
const updateMutation = useUpdateCardTransaction(cardTransactionId ?? 0)
const isPending = createMutation.isPending || updateMutation.isPending
// Populate form when editing
useEffect(() => {
if (mode === 'edit' && initialData) {
setForm({
passport_series: initialData.passport_series,
passport_number: initialData.passport_number,
card_number: initialData.card_number,
card_expiry_month: initialData.card_expiry_month,
card_expiry_year: initialData.card_expiry_year,
})
}
}, [mode, initialData])
const setField = (field: keyof FormState) => (value: string) => {
setForm((prev) => ({ ...prev, [field]: value }))
if (errors[field]) setErrors((prev) => ({ ...prev, [field]: undefined }))
}
const handleSubmit = async () => {
const validationErrors = validate(form, t)
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors)
return
}
if (mode === 'create') {
await createMutation.mutateAsync(form)
navigate('/card-transactions')
} else {
await updateMutation.mutateAsync(form)
navigate(`/card-transactions/${cardTransactionId}`)
}
}
const handleCancel = () => {
if (mode === 'create') {
navigate('/card-transactions')
} else {
navigate(`/card-transactions/${cardTransactionId}`)
}
}
return (
<div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Passport Series */}
<FormInput
type="searchable-select"
label={t('Passport series', 'Pasport seriýasy')}
value={form.passport_series}
onChange={setField('passport_series')}
options={PASSPORT_SERIES_OPTIONS}
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
error={errors.passport_series}
required
/>
{/* Passport Number */}
<FormInput
type="text"
label={t('Passport number', 'Pasport belgisi')}
value={form.passport_number}
onChange={setField('passport_number')}
placeholder={t('Passport number', 'Pasport belgisi')}
error={errors.passport_number}
required
/>
{/* Card Number */}
<FormInput
type="text"
label={t('Card number', 'Kart belgisi')}
value={form.card_number}
onChange={setField('card_number')}
placeholder={t('Card number', 'Kart belgisi')}
error={errors.card_number}
required
/>
{/* Expiry Month + Year side by side */}
<div className="grid grid-cols-2 gap-3">
<FormInput
type="select"
label={t('Card expiry month', 'Kart Möhleti (aý)')}
value={form.card_expiry_month}
onChange={setField('card_expiry_month')}
options={MONTH_OPTIONS}
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
error={errors.card_expiry_month}
required
/>
<FormInput
type="select"
label={t('Card expiry year', 'Kart Möhleti (ýyl)')}
value={form.card_expiry_year}
onChange={setField('card_expiry_year')}
options={YEAR_OPTIONS}
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
error={errors.card_expiry_year}
required
/>
</div>
</div>
{/* Actions */}
<div className="flex justify-end gap-3 mt-6">
<Button variant="ghost" onClick={handleCancel} disabled={isPending}>
{t('Cancel', 'Ýatyr')}
</Button>
<Button onClick={handleSubmit} disabled={isPending}>
{isPending
? t('Saving...', 'Saklanýar...')
: mode === 'create'
? t('Create card transaction', 'Kart herekedi dörediň')
: t('Save changes', 'Üýtgetmeleri sakla')}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,110 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import {
cardTransactionsApi,
type CardTransactionListParams,
type CreateCardTransactionPayload,
type UpdateCardTransactionPayload,
} from '../api/cardTransactionsApi'
const QUERY_KEY = 'card-transactions'
// ─── List ─────────────────────────────────────────────────────────────────────
export function useCardTransactions(params?: CardTransactionListParams) {
return useQuery({
queryKey: [QUERY_KEY, params],
queryFn: () => cardTransactionsApi.getAll(params),
})
}
// ─── Single ───────────────────────────────────────────────────────────────────
export function useCardTransaction(id: number) {
return useQuery({
queryKey: [QUERY_KEY, id],
queryFn: () => cardTransactionsApi.getById(id),
enabled: !!id,
})
}
// ─── Create ───────────────────────────────────────────────────────────────────
export function useCreateCardTransaction() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: CreateCardTransactionPayload) =>
cardTransactionsApi.create(payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card transaction created successfully', 'Kart herekedi üstünlikli döredildi'))
},
onError: () => {
toast.error(t('Failed to create card transaction', 'Kart herekedi döredilmedi'))
},
})
}
// ─── Update ───────────────────────────────────────────────────────────────────
export function useUpdateCardTransaction(id: number) {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: UpdateCardTransactionPayload) =>
cardTransactionsApi.update(id, payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card transaction updated successfully', 'Kart herekedi üstünlikli üýtgedildi'))
},
onError: () => {
toast.error(t('Failed to update card transaction', 'Kart herekedi üýtgedilmedi'))
},
})
}
// ─── Delete ───────────────────────────────────────────────────────────────────
export function useDeleteCardTransaction() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (id: number) => cardTransactionsApi.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card transaction deleted successfully', 'Kart herekedi üstünlikli öçürildi'))
},
onError: () => {
toast.error(t('Failed to delete card transaction', 'Kart herekedi öçürilmedi'))
},
})
}
// ─── Download ─────────────────────────────────────────────────────────────────
export function useDownloadCardTransaction() {
const { t } = useTranslation()
return useMutation({
mutationFn: async (id: number) => {
const blob = await cardTransactionsApi.download(id)
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `card-transaction-${id}.pdf`
a.click()
URL.revokeObjectURL(url)
},
onSuccess: () => {
toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi'))
},
onError: () => {
toast.error(t('Download failed', 'Ýüklemek başartmady'))
},
})
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,425 @@
// ─── Enums / Unions ───────────────────────────────────────────────────────────
export type CardOrderStatus = 'PENDING' | 'APPROVED' | 'REJECTED'
export type CardOrderSortField =
| 'id'
| 'createdAt'
| 'status'
| 'welayat'
| 'sahamca'
// ─── Lookup entities ──────────────────────────────────────────────────────────
export interface CardIssuanceReason {
id: number
name: string
}
export interface CardType {
id: number
name: string
}
export interface Province {
id: number
name: string
}
export interface Branch {
id: number
name: string
provinceId: number
}
// ─── Passport ────────────────────────────────────────────────────────────────
export interface PassportFiles {
page1: string | null // URL
page23: string | null
page89: string | null
page32: string | null
}
// ─── Card Order ───────────────────────────────────────────────────────────────
export interface CardOrder {
id: string
createdAt: string // ISO datetime string
isPaid: boolean
status: CardOrderStatus
note: string | null
createdBy: string // user display name
// Card
issuanceReasonId: number
issuanceReasonName: string
cardTypeId: number
cardTypeName: string
// Location
provinceId: number
provinceName: string
branchId: number
branchName: string
// Personal info
firstName: string
lastName: string
middleName: string | null
formerLastName: string | null
birthDate: string // yyyy-MM-dd
phone: string
phoneExtra: string | null
citizenship: string
registeredAddress: string
currentAddress: string
workplace: string
// Passport
passportSeriesId: number
passportSeriesName: string
passportNumber: string
passportIssueDate: string // yyyy-MM-dd
passportIssuedBy: string
passportBirthPlace: string
passportFiles: PassportFiles
}
// ─── List item (lighter shape for table rows) ─────────────────────────────────
export interface CardOrderListItem {
id: string
createdAt: string
issuanceReasonName: string
cardTypeName: string
provinceName: string
branchName: string
firstName: string
lastName: string
status: CardOrderStatus
}
// ─── Pagination ───────────────────────────────────────────────────────────────
export interface PaginatedResponse<T> {
data: T[]
totalCount: number
page: number
perPage: number
totalPages: number
}
// ─── API Payloads ─────────────────────────────────────────────────────────────
export interface CardOrderFilters {
search?: string
status?: CardOrderStatus | ''
provinceId?: number | ''
branchId?: number | ''
page?: number
perPage?: number
}
export interface CreateCardOrderPayload {
isPaid: boolean
status: CardOrderStatus
note: string | null
issuanceReasonId: number
cardTypeId: number
provinceId: number
branchId: number
firstName: string
lastName: string
middleName: string | null
formerLastName: string | null
birthDate: string
phone: string
phoneExtra: string | null
citizenship: string
registeredAddress: string
currentAddress: string
workplace: string
passportSeriesId: number
passportNumber: string
passportIssueDate: string
passportIssuedBy: string
passportBirthPlace: string
passportPage1: File
passportPage23: File
passportPage89: File
passportPage32: File
}
export interface UpdateCardOrderPayload extends Partial<CreateCardOrderPayload> {}
import {apiClient} from '@/lib/api/client'
// ─── Mock Data ────────────────────────────────────────────────────────────────
const USE_MOCK = true
const MOCK_REASONS: CardIssuanceReason[] = [
{ id: 1, name: 'Möhleti gutardy' },
{ id: 2, name: 'Täze kart açmak' },
{ id: 3, name: 'Kartyň ýitmegi' },
{ id: 4, name: 'Adyň üýtgemegi' },
]
const MOCK_TYPES: CardType[] = [
{ id: 1, name: 'Altyn Asyr' },
{ id: 2, name: 'Maşgala' },
{ id: 3, name: 'Goýum' },
{ id: 4, name: 'Milli' },
]
const MOCK_PROVINCES: Province[] = [
{ id: 1, name: 'Aşgabat ş.' },
{ id: 2, name: 'Ahal' },
{ id: 3, name: 'Balkan' },
{ id: 4, name: 'Daşoguz' },
{ id: 5, name: 'Lebap' },
{ id: 6, name: 'Mary' },
]
const MOCK_BRANCHES: Branch[] = [
{ id: 1, name: 'Aşgabat Baş şahamça', provinceId: 1 },
{ id: 2, name: 'Köpetdag şahamçasy', provinceId: 1 },
{ id: 3, name: 'Abadan şahamçasy', provinceId: 2 },
{ id: 4, name: 'Balkanabat şahamçasy', provinceId: 3 },
{ id: 5, name: 'Mary şahamçasy', provinceId: 6 },
]
const MOCK_ORDERS: CardOrder[] = [
{
id: 'CRD-10254',
createdAt: '2026-05-01T10:00:00Z',
isPaid: true,
status: 'APPROVED',
note: 'Hemme zat ýerinde',
createdBy: 'Jumaýew Aman',
issuanceReasonId: 2,
issuanceReasonName: 'Täze kart açmak',
cardTypeId: 1,
cardTypeName: 'Altyn Asyr',
provinceId: 1,
provinceName: 'Aşgabat ş.',
branchId: 1,
branchName: 'Aşgabat Baş şahamça',
firstName: 'Berdi',
lastName: 'Myradow',
middleName: 'Gurbanowiç',
formerLastName: null,
birthDate: '1995-04-12',
phone: '+99365123456',
phoneExtra: null,
citizenship: 'Türkmenistan',
registeredAddress: 'Aşgabat, Magtymguly şaýoly 12',
currentAddress: 'Aşgabat, Magtymguly şaýoly 12',
workplace: 'TDB, IT hünärmen',
passportSeriesId: 1,
passportSeriesName: 'I-AS',
passportNumber: '123456',
passportIssueDate: '2015-05-20',
passportIssuedBy: 'Aşgabat ş. Polisiýa müdirligi',
passportBirthPlace: 'Aşgabat',
passportFiles: {
page1: 'https://placehold.co/600x400?text=Passport+P1',
page23: 'https://placehold.co/600x400?text=Passport+P23',
page89: 'https://placehold.co/600x400?text=Passport+P89',
page32: 'https://placehold.co/600x400?text=Passport+P32',
},
},
{
id: 'CRD-10255',
createdAt: '2026-05-02T14:30:00Z',
isPaid: false,
status: 'PENDING',
note: null,
createdBy: 'Saparow Batyr',
issuanceReasonId: 1,
issuanceReasonName: 'Möhleti gutardy',
cardTypeId: 2,
cardTypeName: 'Maşgala',
provinceId: 6,
provinceName: 'Mary',
branchId: 5,
branchName: 'Mary şahamçasy',
firstName: 'Gyzylgül',
lastName: 'Annageldiýewa',
middleName: 'Begliýewna',
formerLastName: 'Saparowa',
birthDate: '1998-08-25',
phone: '+99361987654',
phoneExtra: '+99312444234',
citizenship: 'Türkmenistan',
registeredAddress: 'Mary ş., Gurbansoltan eje köç. 45',
currentAddress: 'Mary ş., Gurbansoltan eje köç. 45',
workplace: 'Mekdep müdiri',
passportSeriesId: 2,
passportSeriesName: 'I-MR',
passportNumber: '654321',
passportIssueDate: '2018-10-10',
passportIssuedBy: 'Mary w. Polisiýa müdirligi',
passportBirthPlace: 'Mary',
passportFiles: {
page1: 'https://placehold.co/600x400?text=Passport+P1',
page23: 'https://placehold.co/600x400?text=Passport+P23',
page89: 'https://placehold.co/600x400?text=Passport+P89',
page32: 'https://placehold.co/600x400?text=Passport+P32',
},
},
]
// ─── Card Orders CRUD ─────────────────────────────────────────────────────────
export async function fetchCardOrders(
filters: CardOrderFilters,
): Promise<PaginatedResponse<CardOrderListItem>> {
if (USE_MOCK) {
await new Promise((r) => setTimeout(r, 500))
const list: CardOrderListItem[] = MOCK_ORDERS.map((o) => ({
id: o.id,
createdAt: o.createdAt,
issuanceReasonName: o.issuanceReasonName,
cardTypeName: o.cardTypeName,
provinceName: o.provinceName,
branchName: o.branchName,
firstName: o.firstName,
lastName: o.lastName,
status: o.status,
}))
return {
data: list,
totalCount: list.length,
page: filters.page ?? 1,
perPage: filters.perPage ?? 25,
totalPages: 1,
}
}
const params = new URLSearchParams()
if (filters.search) params.set('search', filters.search)
if (filters.status) params.set('status', filters.status)
if (filters.provinceId) params.set('provinceId', String(filters.provinceId))
if (filters.branchId) params.set('branchId', String(filters.branchId))
params.set('page', String(filters.page ?? 1))
params.set('perPage', String(filters.perPage ?? 25))
const { data } = await apiClient.get<PaginatedResponse<CardOrderListItem>>(
`/card-orders?${params.toString()}`,
)
return data
}
export async function fetchCardOrderById(id: string): Promise<CardOrder> {
if (USE_MOCK) {
await new Promise((r) => setTimeout(r, 500))
const order = MOCK_ORDERS.find((o) => o.id === id) || MOCK_ORDERS[0]
return { ...order, id }
}
const { data } = await apiClient.get<CardOrder>(`/card-orders/${id}`)
return data
}
export async function createCardOrder(
payload: CreateCardOrderPayload,
): Promise<CardOrder> {
if (USE_MOCK) {
await new Promise((r) => setTimeout(r, 1000))
return { ...MOCK_ORDERS[0], id: `CRD-${Math.floor(Math.random() * 10000)}` }
}
const formData = buildFormData(payload)
const { data } = await apiClient.post<CardOrder>('/card-orders', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
return data
}
export async function updateCardOrder(
id: string,
payload: UpdateCardOrderPayload,
): Promise<CardOrder> {
if (USE_MOCK) {
await new Promise((r) => setTimeout(r, 1000))
return { ...MOCK_ORDERS[0], id }
}
const formData = buildFormData(payload)
const { data } = await apiClient.put<CardOrder>(`/card-orders/${id}`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
return data
}
export async function deleteCardOrder(id: string): Promise<void> {
if (USE_MOCK) {
await new Promise((r) => setTimeout(r, 500))
return
}
await apiClient.delete(`/card-orders/${id}`)
}
// ─── Lookup lists ─────────────────────────────────────────────────────────────
export async function fetchCardIssuanceReasons(): Promise<CardIssuanceReason[]> {
if (USE_MOCK) return MOCK_REASONS
const { data } = await apiClient.get<CardIssuanceReason[]>('/settings/card/reasons')
return data
}
export async function fetchCardTypes(): Promise<CardType[]> {
if (USE_MOCK) return MOCK_TYPES
const { data } = await apiClient.get<CardType[]>('/settings/card/types')
return data
}
export async function fetchProvinces(): Promise<Province[]> {
if (USE_MOCK) return MOCK_PROVINCES
const { data } = await apiClient.get<Province[]>('/settings/location/districts')
return data
}
export async function fetchBranches(provinceId?: number): Promise<Branch[]> {
if (USE_MOCK) {
if (!provinceId) return MOCK_BRANCHES
return MOCK_BRANCHES.filter((b) => b.provinceId === provinceId)
}
const params = provinceId ? `?provinceId=${provinceId}` : ''
const { data } = await apiClient.get<Branch[]>(`/settings/location/branches${params}`)
return data
}
// ─── Helper ───────────────────────────────────────────────────────────────────
function buildFormData(
payload: CreateCardOrderPayload | UpdateCardOrderPayload,
): FormData {
const fd = new FormData()
const fileKeys = new Set([
'passportPage1',
'passportPage23',
'passportPage89',
'passportPage32',
])
for (const [key, value] of Object.entries(payload)) {
if (value === undefined) continue
if (fileKeys.has(key) && value instanceof File) {
fd.append(key, value)
} else if (value === null) {
fd.append(key, '')
} else {
fd.append(key, String(value))
}
}
return fd
}

View File

@@ -0,0 +1,619 @@
import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { FormInput } from '@/components/formInput'
import { Button } from '@/components/ui/button'
import type { SelectOption } from '@/components/formInput'
import type {
CardOrder,
CardOrderStatus,
CreateCardOrderPayload,
} from '../api/orderNewCardApi'
import {
useCardIssuanceReasons,
useCardTypes,
useProvinces,
useBranches,
useCreateCardOrder,
useUpdateCardOrder,
} from '../hooks/useOrderNewCard'
// ─── Types ────────────────────────────────────────────────────────────────────
interface CardOrderFormProps {
mode: 'create' | 'edit'
initialData?: CardOrder
cardOrderId?: string
onSuccess?: () => void
onCancel?: () => void
}
interface FormState {
isPaid: boolean
status: CardOrderStatus | ''
note: string
issuanceReasonId: string
cardTypeId: string
provinceId: string
branchId: string
firstName: string
lastName: string
middleName: string
formerLastName: string
birthDate: string
phone: string
phoneExtra: string
citizenship: string
registeredAddress: string
currentAddress: string
workplace: string
passportSeriesId: string
passportNumber: string
passportIssueDate: string
passportIssuedBy: string
passportBirthPlace: string
passportPage1: File | null
passportPage23: File | null
passportPage89: File | null
passportPage32: File | null
termsAccepted: boolean
}
type FormErrors = Partial<Record<keyof FormState, string>>
// ─── Initial state ────────────────────────────────────────────────────────────
function getInitialState(data?: CardOrder): FormState {
return {
isPaid: data?.isPaid ?? false,
status: data?.status ?? '',
note: data?.note ?? '',
issuanceReasonId: data?.issuanceReasonId ? String(data.issuanceReasonId) : '',
cardTypeId: data?.cardTypeId ? String(data.cardTypeId) : '',
provinceId: data?.provinceId ? String(data.provinceId) : '',
branchId: data?.branchId ? String(data.branchId) : '',
firstName: data?.firstName ?? '',
lastName: data?.lastName ?? '',
middleName: data?.middleName ?? '',
formerLastName: data?.formerLastName ?? '',
birthDate: data?.birthDate ?? '',
phone: data?.phone ?? '',
phoneExtra: data?.phoneExtra ?? '',
citizenship: data?.citizenship ?? 'Turkmenistan',
registeredAddress: data?.registeredAddress ?? '',
currentAddress: data?.currentAddress ?? '',
workplace: data?.workplace ?? '',
passportSeriesId: data?.passportSeriesId ? String(data.passportSeriesId) : '',
passportNumber: data?.passportNumber ?? '',
passportIssueDate: data?.passportIssueDate ?? '',
passportIssuedBy: data?.passportIssuedBy ?? '',
passportBirthPlace:data?.passportBirthPlace?? '',
passportPage1: null,
passportPage23: null,
passportPage89: null,
passportPage32: null,
termsAccepted: false,
}
}
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(form: FormState, mode: 'create' | 'edit', t: (k: string, fb: string) => string): FormErrors {
const errors: FormErrors = {}
const req = (field: keyof FormState, msg: string) => {
const v = form[field]
if (!v || (typeof v === 'string' && !v.trim())) errors[field] = msg
}
req('status', t('validation.required', 'Bu meýdan hökmanydyr'))
req('issuanceReasonId', t('validation.required', 'Bu meýdan hökmanydyr'))
req('cardTypeId', t('validation.required', 'Bu meýdan hökmanydyr'))
req('provinceId', t('validation.required', 'Bu meýdan hökmanydyr'))
req('branchId', t('validation.required', 'Bu meýdan hökmanydyr'))
req('firstName', t('validation.required', 'Bu meýdan hökmanydyr'))
req('lastName', t('validation.required', 'Bu meýdan hökmanydyr'))
req('birthDate', t('validation.required', 'Bu meýdan hökmanydyr'))
req('phone', t('validation.required', 'Bu meýdan hökmanydyr'))
req('citizenship', t('validation.required', 'Bu meýdan hökmanydyr'))
req('registeredAddress', t('validation.required', 'Bu meýdan hökmanydyr'))
req('currentAddress', t('validation.required', 'Bu meýdan hökmanydyr'))
req('workplace', t('validation.required', 'Bu meýdan hökmanydyr'))
req('passportSeriesId', t('validation.required', 'Bu meýdan hökmanydyr'))
req('passportNumber', t('validation.required', 'Bu meýdan hökmanydyr'))
req('passportIssueDate', t('validation.required', 'Bu meýdan hökmanydyr'))
req('passportIssuedBy', t('validation.required', 'Bu meýdan hökmanydyr'))
req('passportBirthPlace',t('validation.required', 'Bu meýdan hökmanydyr'))
if (mode === 'create') {
if (!form.passportPage1) errors.passportPage1 = t('validation.required', 'Bu meýdan hökmanydyr')
if (!form.passportPage23) errors.passportPage23 = t('validation.required', 'Bu meýdan hökmanydyr')
if (!form.passportPage89) errors.passportPage89 = t('validation.required', 'Bu meýdan hökmanydyr')
if (!form.passportPage32) errors.passportPage32 = t('validation.required', 'Bu meýdan hökmanydyr')
if (!form.termsAccepted) errors.termsAccepted = t('validation.terms', 'Şertnama bilen razylaşmaly')
}
return errors
}
// ─── Section wrapper ──────────────────────────────────────────────────────────
function FormSection({ title, children }: { title?: string; children: React.ReactNode }) {
return (
<div className="mb-6">
{title && (
<h3 className="text-base font-semibold text-foreground mb-3">{title}</h3>
)}
<div className="bg-card border border-border rounded-xl p-5 space-y-4">
{children}
</div>
</div>
)
}
// ─── CardOrderForm ────────────────────────────────────────────────────────────
export function CardOrderForm({
mode,
initialData,
cardOrderId,
onSuccess,
onCancel,
}: CardOrderFormProps) {
const { t } = useTranslation()
const isEdit = mode === 'edit'
const [form, setForm] = useState<FormState>(() => getInitialState(initialData))
const [errors, setErrors] = useState<FormErrors>({})
const [touched, setTouched] = useState(false)
// Reset form when initialData loads (edit mode)
useEffect(() => {
if (initialData) setForm(getInitialState(initialData))
}, [initialData])
// Lookup data
const { data: reasons = [] } = useCardIssuanceReasons()
const { data: cardTypes = [] } = useCardTypes()
const { data: provinces = [] } = useProvinces()
const { data: branches = [] } = useBranches(
form.provinceId ? Number(form.provinceId) : undefined,
)
// Mutations
const createMutation = useCreateCardOrder()
const updateMutation = useUpdateCardOrder(cardOrderId ?? '')
const isPending = createMutation.isPending || updateMutation.isPending
// Helpers
const set = (key: keyof FormState) => (value: string) =>
setForm((f) => ({ ...f, [key]: value }))
const setFile = (key: keyof FormState) => (file: File | null) =>
setForm((f) => ({ ...f, [key]: file }))
const toOptions = (arr: { id: number; name: string }[]): SelectOption[] =>
arr.map((x) => ({ value: String(x.id), label: x.name }))
// Validate on every change if user has already submitted once
useEffect(() => {
if (touched) setErrors(validate(form, mode, t))
}, [form, touched, mode])
// ── Submit ─────────────────────────────────────────────────────────────────
const handleSubmit = async () => {
setTouched(true)
const errs = validate(form, mode, t)
if (Object.keys(errs).length > 0) {
setErrors(errs)
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
}
}
// ── Status 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') },
]
// ── Render ────────────────────────────────────────────────────────────────
return (
<div>
{/* ── Status section ── */}
<FormSection>
<div className="flex items-center gap-2 mb-1">
<input
id="isPaid"
type="checkbox"
checked={form.isPaid}
onChange={(e) => setForm((f) => ({ ...f, isPaid: e.target.checked }))}
className="w-4 h-4 accent-primary cursor-pointer"
/>
<label
htmlFor="isPaid"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider cursor-pointer select-none"
>
{t('cardOrder.field.isPaid', 'Tölenen')}
</label>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="select"
label={t('cardOrder.field.status', 'Status')}
required
value={form.status}
onChange={set('status')}
options={statusOptions}
placeholder={t('common.selectPlaceholder', 'Saýlamak üçin basyň')}
error={errors.status}
/>
<FormInput
type="textarea"
label={t('cardOrder.field.note', 'Bellik')}
value={form.note}
onChange={set('note')}
placeholder={t('cardOrder.field.note', 'Bellik')}
rows={2}
/>
</div>
</FormSection>
{/* ── Kart ── */}
<FormSection title={t('cardOrder.section.card', 'Kart')}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('cardOrder.field.issuanceReason', 'Kartyň çykarylmagynyň sebäbi')}
required
value={form.issuanceReasonId}
onChange={set('issuanceReasonId')}
options={toOptions(reasons)}
error={errors.issuanceReasonId}
/>
<FormInput
type="searchable-select"
label={t('cardOrder.field.cardType', 'Kart görnüşi')}
required
value={form.cardTypeId}
onChange={set('cardTypeId')}
options={toOptions(cardTypes)}
error={errors.cardTypeId}
/>
</div>
</FormSection>
{/* ── Lokasiýa ── */}
<FormSection title={t('cardOrder.section.location', 'Lokasiýa')}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="select"
label={t('cardOrder.field.province', 'Welaýat')}
required
value={form.provinceId}
onChange={(v) => {
setForm((f) => ({ ...f, provinceId: v, branchId: '' }))
}}
options={toOptions(provinces)}
error={errors.provinceId}
/>
<FormInput
type="searchable-select"
label={t('cardOrder.field.branch', 'Şahamça')}
required
value={form.branchId}
onChange={set('branchId')}
options={toOptions(branches)}
disabled={!form.provinceId}
error={errors.branchId}
/>
</div>
</FormSection>
{/* ── Şahsy maglumatlar ── */}
<FormSection title={t('cardOrder.section.personal', 'Şahsy maglumatlar')}>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<FormInput
label={t('cardOrder.field.firstName', 'Ady')}
required
value={form.firstName}
onChange={set('firstName')}
placeholder={t('cardOrder.field.firstName', 'Ady')}
error={errors.firstName}
/>
<FormInput
label={t('cardOrder.field.lastName', 'Familiýasy')}
required
value={form.lastName}
onChange={set('lastName')}
placeholder={t('cardOrder.field.lastName', 'Familiýasy')}
error={errors.lastName}
/>
<FormInput
label={t('cardOrder.field.middleName', 'Atasynyn ady')}
value={form.middleName}
onChange={set('middleName')}
placeholder={t('cardOrder.field.middleName', 'Atasynyn ady')}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
label={t('cardOrder.field.formerLastName', 'Köne familiýaňyz (eger üýtgän bolsa)')}
value={form.formerLastName}
onChange={set('formerLastName')}
placeholder={t('cardOrder.field.formerLastName', 'Köne familiýaňyz (eger üýtgän bolsa)')}
/>
<FormInput
type="date"
label={t('cardOrder.field.birthDate', 'Doglan güni')}
required
value={form.birthDate}
onChange={set('birthDate')}
error={errors.birthDate}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<FormInput
type="phone"
label={t('cardOrder.field.phone', 'Telefon')}
required
value={form.phone}
onChange={set('phone')}
error={errors.phone}
/>
<FormInput
type="phone"
label={t('cardOrder.field.phoneExtra', 'Telefon goşmaça')}
value={form.phoneExtra}
onChange={set('phoneExtra')}
/>
<FormInput
type="select"
label={t('cardOrder.field.citizenship', 'Raýatlyk')}
required
value={form.citizenship}
onChange={set('citizenship')}
options={citizenshipOptions}
error={errors.citizenship}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
label={t('cardOrder.field.registeredAddress', 'Ýazgy edilen salgyňyz')}
required
value={form.registeredAddress}
onChange={set('registeredAddress')}
placeholder={t('cardOrder.field.registeredAddress', 'Ýazgy edilen salgyňyz')}
error={errors.registeredAddress}
/>
<FormInput
label={t('cardOrder.field.currentAddress', 'Häzirki ýaşaýyş ýeri')}
required
value={form.currentAddress}
onChange={set('currentAddress')}
placeholder={t('cardOrder.field.currentAddress', 'Häzirki ýaşaýyş ýeri')}
error={errors.currentAddress}
/>
</div>
<FormInput
label={t('cardOrder.field.workplace', 'Işleýän ýeriňiz we wezipäňiz')}
required
value={form.workplace}
onChange={set('workplace')}
placeholder={t('cardOrder.field.workplace', 'Işleýän ýeriňiz we wezipäňiz')}
error={errors.workplace}
/>
</FormSection>
{/* ── Pasport ── */}
<FormSection title={t('cardOrder.section.passport', 'Pasport')}>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<FormInput
type="select"
label={t('cardOrder.field.passportSeries', 'Pasport seriýasy')}
required
value={form.passportSeriesId}
onChange={set('passportSeriesId')}
options={[
{ value: '1', label: 'I' },
{ value: '2', label: 'II' },
{ value: '3', label: 'III' },
]}
error={errors.passportSeriesId}
/>
<FormInput
label={t('cardOrder.field.passportNumber', 'Pasport belgisi')}
required
value={form.passportNumber}
onChange={set('passportNumber')}
placeholder={t('cardOrder.field.passportNumber', 'Pasport belgisi')}
error={errors.passportNumber}
/>
<FormInput
type="date"
label={t('cardOrder.field.passportIssueDate', 'Pasport berlen senesi')}
required
value={form.passportIssueDate}
onChange={set('passportIssueDate')}
error={errors.passportIssueDate}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
label={t('cardOrder.field.passportIssuedBy', 'Kim tarapyndan berildi')}
required
value={form.passportIssuedBy}
onChange={set('passportIssuedBy')}
placeholder={t('cardOrder.field.passportIssuedBy', 'Kim tarapyndan berildi')}
error={errors.passportIssuedBy}
/>
<FormInput
label={t('cardOrder.field.passportBirthPlace', 'Doglan ýeri (pasport)')}
required
value={form.passportBirthPlace}
onChange={set('passportBirthPlace')}
placeholder={t('cardOrder.field.passportBirthPlace', 'Doglan ýeri (pasport)')}
error={errors.passportBirthPlace}
/>
</div>
</FormSection>
{/* ── Pasport faýýlar ── */}
<FormSection title={t('cardOrder.section.passportFiles', 'Pasport faýýlar')}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="file"
label={t('cardOrder.field.passportPage1', 'Pasport (sahypa 1)')}
required
accept="image/*,.pdf"
fileValue={form.passportPage1}
onFileChange={setFile('passportPage1')}
error={errors.passportPage1}
/>
<FormInput
type="file"
label={t('cardOrder.field.passportPage23', 'Pasport (2-3-nji sahypa)')}
required
accept="image/*,.pdf"
fileValue={form.passportPage23}
onFileChange={setFile('passportPage23')}
error={errors.passportPage23}
/>
<FormInput
type="file"
label={t('cardOrder.field.passportPage89', 'Pasport (8-9 sahypa)')}
required
accept="image/*,.pdf"
fileValue={form.passportPage89}
onFileChange={setFile('passportPage89')}
error={errors.passportPage89}
/>
<FormInput
type="file"
label={t('cardOrder.field.passportPage32', 'Pasport (32-nji sahypa)')}
required
accept="image/*,.pdf"
fileValue={form.passportPage32}
onFileChange={setFile('passportPage32')}
error={errors.passportPage32}
/>
</div>
</FormSection>
{/* ── Terms ── */}
{!isEdit && (
<div
className={`flex items-center gap-3 p-3 rounded-lg mb-6 cursor-pointer transition-colors
${errors.termsAccepted
? 'bg-destructive/10 border border-destructive/30'
: 'bg-primary/5 border border-primary/20'
}`}
onClick={() => setForm((f) => ({ ...f, termsAccepted: !f.termsAccepted }))}
>
<div className={`w-5 h-5 rounded flex items-center justify-center shrink-0 transition-colors
${form.termsAccepted ? 'bg-primary text-primary-foreground' : 'border border-border bg-background'}`}
>
{form.termsAccepted && (
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M2 6L5 9L10 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
)}
</div>
<span className={`text-sm font-medium ${errors.termsAccepted ? 'text-destructive' : 'text-primary'}`}>
{t('cardOrder.terms', 'Şertnama bilen razylaşýaryn (Okamak üçin bas)')}
</span>
</div>
)}
{/* ── Actions ── */}
<div className="flex items-center justify-end gap-3">
{onCancel && (
<Button
variant="outline"
onClick={onCancel}
disabled={isPending}
>
{t('common.cancel', 'Ýatyr')}
</Button>
)}
<Button
onClick={handleSubmit}
disabled={isPending}
className="min-w-[160px]"
>
{isPending
? t('common.saving', 'Saklanylýar...')
: isEdit
? t('common.save', 'Ýatda sakla')
: t('cardOrder.submit', 'Kart sargyt dörediň')
}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,155 @@
import { Link } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import type { ColumnDef } from '@/components/dataTable'
import type { CardOrderListItem, CardOrderStatus } from '../api/orderNewCardApi'
// ─── Status badge ─────────────────────────────────────────────────────────────
const STATUS_CONFIG: Record<
CardOrderStatus,
{ label: string; className: string }
> = {
PENDING: {
label: 'Garaşylýar',
className:
'inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-bold tracking-wide ' +
'bg-amber-500/10 text-amber-400 border border-amber-500/20',
},
APPROVED: {
label: 'Tassyklandy',
className:
'inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-bold tracking-wide ' +
'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20',
},
REJECTED: {
label: 'Ýatyryldy',
className:
'inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-bold tracking-wide ' +
'bg-red-500/10 text-red-400 border border-red-500/20',
},
}
function StatusBadge({ status }: { status: CardOrderStatus }) {
const cfg = STATUS_CONFIG[status]
const icons: Record<CardOrderStatus, string> = {
PENDING: '⏳',
APPROVED: '✓',
REJECTED: '✕',
}
return (
<span className={cfg.className}>
<span className="text-[10px]">{icons[status]}</span>
{cfg.label}
</span>
)
}
// ─── Coloured text helper ─────────────────────────────────────────────────────
function HighlightText({
value,
variant,
}: {
value: string
variant: 'teal' | 'cyan' | 'muted'
}) {
const cls =
variant === 'teal' ? 'text-teal-400 font-semibold' :
variant === 'cyan' ? 'text-cyan-400 font-semibold' :
'text-muted-foreground'
return <span className={cls}>{value}</span>
}
// ─── useCardOrderColumns ──────────────────────────────────────────────────────
export function useCardOrderColumns(): ColumnDef<CardOrderListItem>[] {
const { t } = useTranslation()
return [
{
accessorKey: 'id',
header: t('cardOrder.col.id', 'ID'),
cell: ({ row }) => (
<Link
to={`/order-new-card/${row.original.id}`}
className="font-mono text-xs text-primary hover:underline"
>
{row.original.id}
</Link>
),
size: 130,
},
{
accessorKey: 'issuanceReasonName',
header: t('cardOrder.col.reason', 'Sebäp'),
cell: ({ row }) => (
<span className="text-sm text-foreground">
{row.original.issuanceReasonName}
</span>
),
},
{
accessorKey: 'createdAt',
header: t('cardOrder.col.createdAt', 'Döredilen wagty'),
cell: ({ row }) => (
<span className="text-sm text-muted-foreground whitespace-nowrap">
{row.original.createdAt}
</span>
),
size: 160,
},
{
accessorKey: 'cardTypeName',
header: t('cardOrder.col.cardType', 'Görnüşi'),
cell: ({ row }) => {
const isAltyn = row.original.cardTypeName === 'Altyn Asyr'
return (
<HighlightText
value={row.original.cardTypeName}
variant={isAltyn ? 'cyan' : 'teal'}
/>
)
},
},
{
accessorKey: 'provinceName',
header: t('cardOrder.col.province', 'Welaýat'),
cell: ({ row }) => (
<span className="text-sm text-foreground">{row.original.provinceName}</span>
),
},
{
accessorKey: 'branchName',
header: t('cardOrder.col.branch', 'Şahamça'),
cell: ({ row }) => {
const specialBranches = [
'Köpetdag', 'Türkmenabat', 'Türkmenbaşy',
'Seýdi', 'Çandybil', 'Balkan', 'Baş bank',
]
const isSpecial = specialBranches.includes(row.original.branchName)
return (
<HighlightText
value={row.original.branchName}
variant={isSpecial ? 'cyan' : 'muted'}
/>
)
},
},
{
id: 'fullName',
header: t('cardOrder.col.name', 'Ady'),
cell: ({ row }) => (
<span className="text-sm text-foreground">
{row.original.lastName} {row.original.firstName}
</span>
),
},
{
accessorKey: 'status',
header: t('cardOrder.col.status', 'Status'),
cell: ({ row }) => <StatusBadge status={row.original.status} />,
size: 130,
},
]
}

View File

@@ -0,0 +1,150 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import {
fetchCardOrders,
fetchCardOrderById,
createCardOrder,
updateCardOrder,
deleteCardOrder,
fetchCardIssuanceReasons,
fetchCardTypes,
fetchProvinces,
fetchBranches,
} from '../api/orderNewCardApi'
import type {
CardOrderFilters,
CreateCardOrderPayload,
UpdateCardOrderPayload,
} from '../api/orderNewCardApi'
// ─── Query keys ───────────────────────────────────────────────────────────────
export const cardOrderKeys = {
all: ['card-orders'] as const,
lists: () => [...cardOrderKeys.all, 'list'] as const,
list: (f: CardOrderFilters) => [...cardOrderKeys.lists(), f] as const,
details: () => [...cardOrderKeys.all, 'detail'] as const,
detail: (id: string) => [...cardOrderKeys.details(), id] as const,
reasons: ['card-order-reasons'] as const,
types: ['card-order-types'] as const,
provinces: ['provinces'] as const,
branches: (provinceId?: number) => ['branches', provinceId] as const,
}
// ─── List ─────────────────────────────────────────────────────────────────────
export function useCardOrders(filters: CardOrderFilters) {
return useQuery({
queryKey: cardOrderKeys.list(filters),
queryFn: () => fetchCardOrders(filters),
placeholderData: (prev) => prev,
})
}
// ─── Single ───────────────────────────────────────────────────────────────────
export function useCardOrderById(id: string) {
return useQuery({
queryKey: cardOrderKeys.detail(id),
queryFn: () => fetchCardOrderById(id),
enabled: Boolean(id),
})
}
// ─── Create ───────────────────────────────────────────────────────────────────
export function useCreateCardOrder() {
const { t } = useTranslation()
const qc = useQueryClient()
return useMutation({
mutationFn: (payload: CreateCardOrderPayload) => createCardOrder(payload),
onSuccess: () => {
qc.invalidateQueries({ queryKey: cardOrderKeys.lists() })
toast.success(t('cardOrder.createSuccess', 'Kart sargyt üstünlikli döredildi'))
},
onError: () => {
toast.error(t('cardOrder.createError', 'Kart sargyt döredilende ýalňyşlyk ýüze çykdy'))
},
})
}
// ─── Update ───────────────────────────────────────────────────────────────────
export function useUpdateCardOrder(id: string) {
const { t } = useTranslation()
const qc = useQueryClient()
return useMutation({
mutationFn: (payload: UpdateCardOrderPayload) => updateCardOrder(id, payload),
onSuccess: (updated) => {
qc.invalidateQueries({ queryKey: cardOrderKeys.lists() })
qc.setQueryData(cardOrderKeys.detail(id), updated)
toast.success(t('cardOrder.updateSuccess', 'Kart sargyt üstünlikli täzelendi'))
},
onError: () => {
toast.error(t('cardOrder.updateError', 'Kart sargyt täzelende ýalňyşlyk ýüze çykdy'))
},
})
}
// ─── Delete ───────────────────────────────────────────────────────────────────
export function useDeleteCardOrder() {
const { t } = useTranslation()
const qc = useQueryClient()
return useMutation({
mutationFn: (id: string) => deleteCardOrder(id),
onSuccess: (_, id) => {
qc.invalidateQueries({ queryKey: cardOrderKeys.lists() })
qc.removeQueries({ queryKey: cardOrderKeys.detail(id) })
toast.success(t('cardOrder.deleteSuccess', 'Kart sargyt üstünlikli pozuldy'))
},
onError: () => {
toast.error(t('cardOrder.deleteError', 'Kart sargyt pozulanda ýalňyşlyk ýüze çykdy'))
},
})
}
// ─── Lookup hooks ─────────────────────────────────────────────────────────────
export function useCardIssuanceReasons() {
return useQuery({
queryKey: cardOrderKeys.reasons,
queryFn: fetchCardIssuanceReasons,
staleTime: Infinity,
})
}
export function useCardTypes() {
return useQuery({
queryKey: cardOrderKeys.types,
queryFn: fetchCardTypes,
staleTime: Infinity,
})
}
export function useProvinces() {
return useQuery({
queryKey: cardOrderKeys.provinces,
queryFn: fetchProvinces,
staleTime: Infinity,
})
}
export function useBranches(provinceId?: number) {
return useQuery({
queryKey: cardOrderKeys.branches(provinceId),
queryFn: () => fetchBranches(provinceId),
enabled: provinceId !== undefined && provinceId !== 0,
staleTime: Infinity,
})
}

View File

@@ -0,0 +1,244 @@
import { apiClient } from '@/lib/api/client'
// ─── Types ────────────────────────────────────────────────────────────────────
export type IntlPaymentStatus = 'pending' | 'approved' | 'rejected'
export type CurrencyType = 'visa' | 'mastercard'
export interface IntlPaymentItem {
id: string
client_id: string
client_label: string
currency_type: CurrencyType
currency_type_label: string
created_at: string
province: string
province_label: string
branch: string
branch_label: string
status: IntlPaymentStatus
note: string | null
// Şahsy maglumatlar
passport_first_name: string
passport_last_name: string
phone: string
email: string | null
home_address: string | null
// Töleg upgradyjynyň maglumatlary
passport_series: string
passport_number: string
payer_full_name: string
payer_account_number: string
// Töleg kabul edijiniň maglumatlary
receiver_info: string
// Kabul ediji talyp boyunca resminamalar (9 sany)
doc_sberbank_account: string | null // file url
doc_school_enrollment: string | null
doc_summons: string | null
doc_passport_tm: string | null
doc_foreign_passport: string | null
doc_foreign_passport_copy: string | null
doc_exit_permission: string | null
doc_school_foreign_info: string | null
doc_school_departure_info: string | null
// Upgradyý boyunca resminamalar (6 sany)
upd_doc_passport_tm: string | null
upd_doc_foreign_passport: string | null
upd_doc_visa: string | null
upd_doc_acceptance_letter: string | null
upd_doc_passport_biometric: string | null
upd_doc_passport_old: string | null
created_by: string
created_by_label: string
}
export interface IntlPaymentListParams {
page?: number
per_page?: number
search?: string
status?: IntlPaymentStatus | ''
month?: string
province?: string
}
export interface IntlPaymentListResponse {
data: IntlPaymentItem[]
meta: {
current_page: number
last_page: number
per_page: number
total: number
}
}
export type IntlPaymentCreatePayload = {
client_id: string
status: IntlPaymentStatus
note: string
currency_type: CurrencyType
province: string
branch: string
passport_first_name: string
passport_last_name: string
phone: string
email: string
home_address: string
passport_series: string
passport_number: string
payer_full_name: string
payer_account_number: string
receiver_info: string
// kabul ediji docs
doc_sberbank_account: File | null
doc_school_enrollment: File | null
doc_summons: File | null
doc_passport_tm: File | null
doc_foreign_passport: File | null
doc_foreign_passport_copy: File | null
doc_exit_permission: File | null
doc_school_foreign_info: File | null
doc_school_departure_info: File | null
// upgradyý docs
upd_doc_passport_tm: File | null
upd_doc_foreign_passport: File | null
upd_doc_visa: File | null
upd_doc_acceptance_letter: File | null
upd_doc_passport_biometric: File | null
upd_doc_passport_old: File | null
}
export type IntlPaymentUpdatePayload = IntlPaymentCreatePayload
// ─── API Functions ────────────────────────────────────────────────────────────
const MOCK_INTL_PAYMENTS: IntlPaymentItem[] = [
{
id: '1',
client_id: '1',
client_label: 'Jelaletdin',
currency_type: 'visa',
currency_type_label: 'Visa',
created_at: '2024-05-07 12:00',
province: 'ashgabat',
province_label: 'Aşgabat',
branch: '1',
branch_label: 'Merkezi şahamça',
status: 'pending',
note: 'Test sargyt',
passport_first_name: 'Aman',
passport_last_name: 'Amanow',
phone: '99365123456',
email: 'aman@example.com',
home_address: 'Aşgabat ş., Magtymguly şaýoly 1',
passport_series: 'I-MR',
passport_number: '123456',
payer_full_name: 'Aman Amanow',
payer_account_number: '1234567890123456',
receiver_info: 'Test Receiver',
doc_sberbank_account: null,
doc_school_enrollment: null,
doc_summons: null,
doc_passport_tm: null,
doc_foreign_passport: null,
doc_foreign_passport_copy: null,
doc_exit_permission: null,
doc_school_foreign_info: null,
doc_school_departure_info: null,
upd_doc_passport_tm: null,
upd_doc_foreign_passport: null,
upd_doc_visa: null,
upd_doc_acceptance_letter: null,
upd_doc_passport_biometric: null,
upd_doc_passport_old: null,
created_by: '1',
created_by_label: 'Admin',
},
]
export const intlPaymentApi = {
list: async (params: IntlPaymentListParams): Promise<IntlPaymentListResponse> => {
return {
data: MOCK_INTL_PAYMENTS,
meta: {
current_page: params.page || 1,
last_page: 1,
per_page: params.per_page || 25,
total: MOCK_INTL_PAYMENTS.length,
}
}
const { data } = await apiClient.get('/intl-payments/visa-master', { params })
return data
},
getById: async (id: string): Promise<IntlPaymentItem> => {
const mock = MOCK_INTL_PAYMENTS.find(p => p.id === id)
if (mock) return mock
const { data } = await apiClient.get(`/intl-payments/visa-master/${id}`)
return data
},
create: (payload: IntlPaymentCreatePayload): Promise<IntlPaymentItem> => {
const form = buildFormData(payload)
return apiClient
.post('/intl-payments/visa-master', form, {
headers: { 'Content-Type': 'multipart/form-data' },
})
.then((r) => r.data)
},
update: (id: string, payload: IntlPaymentUpdatePayload): Promise<IntlPaymentItem> => {
const form = buildFormData(payload)
form.append('_method', 'PUT')
return apiClient
.post(`/intl-payments/visa-master/${id}`, form, {
headers: { 'Content-Type': 'multipart/form-data' },
})
.then((r) => r.data)
},
delete: (id: string): Promise<void> =>
apiClient.delete(`/intl-payments/visa-master/${id}`).then((r) => r.data),
}
// ─── Helper ───────────────────────────────────────────────────────────────────
const TEXT_FIELDS: (keyof IntlPaymentCreatePayload)[] = [
'client_id', 'status', 'note', 'currency_type', 'province', 'branch',
'passport_first_name', 'passport_last_name', 'phone', 'email', 'home_address',
'passport_series', 'passport_number', 'payer_full_name', 'payer_account_number',
'receiver_info',
]
const FILE_FIELDS: (keyof IntlPaymentCreatePayload)[] = [
'doc_sberbank_account', 'doc_school_enrollment', 'doc_summons',
'doc_passport_tm', 'doc_foreign_passport', 'doc_foreign_passport_copy',
'doc_exit_permission', 'doc_school_foreign_info', 'doc_school_departure_info',
'upd_doc_passport_tm', 'upd_doc_foreign_passport', 'upd_doc_visa',
'upd_doc_acceptance_letter', 'upd_doc_passport_biometric', 'upd_doc_passport_old',
]
function buildFormData(payload: IntlPaymentCreatePayload): FormData {
const form = new FormData()
for (const key of TEXT_FIELDS) {
const val = payload[key]
if (val !== null && val !== undefined) form.append(key, String(val))
}
for (const key of FILE_FIELDS) {
const file = payload[key]
if (file instanceof File) form.append(key, file)
}
return form
}

View File

@@ -0,0 +1,463 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { FormInput } from '@/components/formInput'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import type { IntlPaymentItem, IntlPaymentCreatePayload, IntlPaymentStatus, CurrencyType } from '../api/visaMasterPaymentsApi'
// ─── Types ────────────────────────────────────────────────────────────────────
interface IntlPaymentFormProps {
mode: 'create' | 'edit'
initialData?: IntlPaymentItem
onSubmit: (payload: IntlPaymentCreatePayload) => void
isSubmitting: boolean
}
type FileKey =
| 'doc_sberbank_account' | 'doc_school_enrollment' | 'doc_summons'
| 'doc_passport_tm' | 'doc_foreign_passport' | 'doc_foreign_passport_copy'
| 'doc_exit_permission' | 'doc_school_foreign_info' | 'doc_school_departure_info'
| 'upd_doc_passport_tm' | 'upd_doc_foreign_passport' | 'upd_doc_visa'
| 'upd_doc_acceptance_letter' | 'upd_doc_passport_biometric' | 'upd_doc_passport_old'
interface FormState {
client_id: string
status: string
note: string
currency_type: string
province: string
branch: string
passport_first_name: string
passport_last_name: string
phone: string
email: string
home_address: string
passport_series: string
passport_number: string
payer_full_name: string
payer_account_number: string
receiver_info: string
doc_sberbank_account: File | null
doc_school_enrollment: File | null
doc_summons: File | null
doc_passport_tm: File | null
doc_foreign_passport: File | null
doc_foreign_passport_copy: File | null
doc_exit_permission: File | null
doc_school_foreign_info: File | null
doc_school_departure_info: File | null
upd_doc_passport_tm: File | null
upd_doc_foreign_passport: File | null
upd_doc_visa: File | null
upd_doc_acceptance_letter: File | null
upd_doc_passport_biometric: File | null
upd_doc_passport_old: File | null
}
type FormErrors = Partial<Record<keyof FormState, string>>
// ─── Constants ────────────────────────────────────────────────────────────────
const STATUS_OPTIONS = [
{ value: 'pending', label: 'Garaşylýar' },
{ value: 'approved', label: 'Tassyklandy' },
{ value: 'rejected', label: 'Ret edildi' },
]
const CURRENCY_OPTIONS = [
{ value: 'visa', label: 'Visa' },
{ value: 'mastercard', label: 'MasterCard' },
]
const PASSPORT_SERIES_OPTIONS = [
{ value: 'I', label: 'I' },
{ value: 'II', label: 'II' },
{ value: 'I-MR', label: 'I-MR' },
{ value: 'II-MR', label: 'II-MR' },
]
const PROVINCE_OPTIONS = [
{ value: 'ashgabat', label: 'Aşgabat' },
{ value: 'ahal', label: 'Ahal' },
{ value: 'mary', label: 'Mary' },
{ value: 'dasoguz', label: 'Daşoguz' },
{ value: 'lebap', label: 'Lebap' },
{ value: 'balkan', label: 'Balkan' },
]
// Kabul ediji docs — 9 sany
const KABUL_DOCS: { key: FileKey; label: string }[] = [
{ key: 'doc_sberbank_account', label: 'Talypyň degişli welaýata "SBERBANK" kartyň rekwizitleri' },
{ key: 'doc_school_enrollment', label: 'Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwänamasy' },
{ key: 'doc_summons', label: 'Talypyň bilendiriň göçürmesi' },
{ key: 'doc_passport_tm', label: 'Talypyň degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi' },
{ key: 'doc_foreign_passport', label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi' },
{ key: 'doc_foreign_passport_copy',label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň daşary ýurtda galan döwründe bakýan döwleti baradaky bellenen sahypasynyň göçürmesi' },
{ key: 'doc_exit_permission', label: 'Talypyň Türkmenistandan çykmak — we Türkmenistana girmek üçin pasportynyň dowletiniň girmesiz baradaky bellenen (goşmaç şaýmynyň) bellenen sahypasynyň göçürmesi' },
{ key: 'doc_school_foreign_info', label: 'Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy barada doly takyk dil ulgaýynda takyk dil maglumatly sebäpleri daşary ýurt döwletiniň ýokary okuw mekdebinden haty' },
{ key: 'doc_school_departure_info',label: 'Talypyň daşary ýurt döwletinde döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwänamany döwlet dili maglumatlaryny talabap doly takyk dil ulgaýynda talaby daşary ýurt döwletiniň ýokary okuw mekdebinden haty' },
]
// Upgradyý docs — 6 sany
const UPGRAD_DOCS: { key: FileKey; label: string }[] = [
{ key: 'upd_doc_passport_tm', label: 'Upgradyý degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi' },
{ key: 'upd_doc_foreign_passport', label: 'Upgradyý degişli Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi' },
{ key: 'upd_doc_visa', label: 'Upgradyý Türkmenistandan — çykmak we Türkmenistana girmek üçin pasportynyň daşary ýurt döwletinde galýandygy we daşary ýurt döwleti baradaky şaýmynyň bellenen sahypasynyň göçürmesi' },
{ key: 'upd_doc_acceptance_letter', label: 'Upgradyýyň we kabul edijiniň Batalyý töräre garyşdyryjy resminamalarynyň göçürmesi' },
{ key: 'upd_doc_passport_biometric', label: 'Upgradyý we kabul ediji täze 2015-nji ýyldan soňra Türkmenistanyň raýatynyň pasportynyň tässy göreli alan bolsa, osta üstü görli 1 pasportynyň seriýasy baradaky maglumatlary' },
{ key: 'upd_doc_passport_old', label: 'Upgradyý we kabul ediji täze 2015-nji ýyldan soňra Türkmenistanyň raýatynyň pasportynyň köp göreli alanlar soňra birleşi göreli alan bolsa, biri miwe möhüründen doglan doglan ata-enelerden biriniň alan pasportynyň seriýasy baradaky göwnamasy' },
]
// ─── Default state ────────────────────────────────────────────────────────────
const defaultState: FormState = {
client_id: '', status: 'pending', note: '',
currency_type: '', province: '', branch: '',
passport_first_name: '', passport_last_name: '',
phone: '', email: '', home_address: '',
passport_series: '', passport_number: '',
payer_full_name: '', payer_account_number: '',
receiver_info: '',
doc_sberbank_account: null, doc_school_enrollment: null,
doc_summons: null, doc_passport_tm: null,
doc_foreign_passport: null, doc_foreign_passport_copy: null,
doc_exit_permission: null, doc_school_foreign_info: null,
doc_school_departure_info: null,
upd_doc_passport_tm: null, upd_doc_foreign_passport: null,
upd_doc_visa: null, upd_doc_acceptance_letter: null,
upd_doc_passport_biometric: null, upd_doc_passport_old: null,
}
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(form: FormState): FormErrors {
const errors: FormErrors = {}
if (!form.client_id) errors.client_id = 'Ulanyjy hökmany'
if (!form.status) errors.status = 'Status hökmany'
if (!form.currency_type) errors.currency_type = 'Ýüztumanyň görnüşi hökmany'
if (!form.province) errors.province = 'Welaýat hökmany'
if (!form.branch) errors.branch = 'Şahamça hökmany'
if (!form.passport_first_name) errors.passport_first_name = 'Ady hökmany'
if (!form.passport_last_name) errors.passport_last_name = 'Familiýasy hökmany'
if (!form.phone) errors.phone = 'Telefon hökmany'
if (!form.passport_series) errors.passport_series = 'Pasport seriýasy hökmany'
if (!form.passport_number) errors.passport_number = 'Pasport nomeri hökmany'
if (!form.payer_full_name) errors.payer_full_name = 'Ady Familiýasy Atasnyň ady hökmany'
if (!form.payer_account_number)errors.payer_account_number= 'Goşun hasaby hökmany'
if (!form.receiver_info) errors.receiver_info = 'Töleg kabul edijiniň maglumatlary hökmany'
return errors
}
// ─── Section wrapper ──────────────────────────────────────────────────────────
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
{title && (
<h2 className="text-base font-semibold text-foreground">{title}</h2>
)}
{children}
</section>
)
}
// ─── Component ────────────────────────────────────────────────────────────────
export function IntlPaymentForm({ mode, initialData, onSubmit, isSubmitting }: IntlPaymentFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const [form, setForm] = useState<FormState>(defaultState)
const [errors, setErrors] = useState<FormErrors>({})
useEffect(() => {
if (mode === 'edit' && initialData) {
setForm({
client_id: initialData.client_id,
status: initialData.status,
note: initialData.note ?? '',
currency_type: initialData.currency_type,
province: initialData.province,
branch: initialData.branch,
passport_first_name: initialData.passport_first_name,
passport_last_name: initialData.passport_last_name,
phone: initialData.phone,
email: initialData.email ?? '',
home_address: initialData.home_address ?? '',
passport_series: initialData.passport_series,
passport_number: initialData.passport_number,
payer_full_name: initialData.payer_full_name,
payer_account_number: initialData.payer_account_number,
receiver_info: initialData.receiver_info,
doc_sberbank_account: null, doc_school_enrollment: null,
doc_summons: null, doc_passport_tm: null,
doc_foreign_passport: null, doc_foreign_passport_copy: null,
doc_exit_permission: null, doc_school_foreign_info: null,
doc_school_departure_info: null,
upd_doc_passport_tm: null, upd_doc_foreign_passport: null,
upd_doc_visa: null, upd_doc_acceptance_letter: null,
upd_doc_passport_biometric: null, upd_doc_passport_old: null,
})
}
}, [mode, initialData])
const set = <K extends keyof FormState>(key: K, value: FormState[K]) => {
setForm((prev) => ({ ...prev, [key]: value }))
if (errors[key]) setErrors((prev) => ({ ...prev, [key]: undefined }))
}
const handleSubmit = () => {
const errs = validate(form)
if (Object.keys(errs).length > 0) {
setErrors(errs)
return
}
onSubmit({
...form,
status: form.status as IntlPaymentStatus,
currency_type: form.currency_type as CurrencyType,
})
}
const title = mode === 'create'
? t('intlPayment.createTitle', 'Visa/Master tölegler (talyplar üçin) dörediň')
: t('intlPayment.editTitle', 'Visa/Master tölegler (talyplar üçin) redaktirläň')
const submitLabel = mode === 'create'
? t('intlPayment.createBtn', 'Visa/Master tölegler (talyplar üçin) dörediň')
: t('intlPayment.editBtn', 'Visa/Master tölegler (talyplar üçin) redaktirläň')
return (
<div className="max-w-4xl mx-auto space-y-6">
<h1 className="text-2xl font-bold text-foreground">{title}</h1>
{/* ── Status ────────────────────────────────────────────────────────── */}
<Section title="">
<FormInput
type="searchable-select"
label={t('intlPayment.client', 'Ulanyjy')}
value={form.client_id}
onChange={(v) => set('client_id', v)}
options={[]} // Fetched from clients API
placeholder="Saýlamak üçin basyň"
error={errors.client_id}
required
/>
<FormInput
type="select"
label={t('intlPayment.status', 'Status')}
value={form.status}
onChange={(v) => set('status', v)}
options={STATUS_OPTIONS}
error={errors.status}
required
/>
<FormInput
type="textarea"
label={t('intlPayment.note', 'Bellik')}
value={form.note}
onChange={(v) => set('note', v)}
placeholder="Bellik"
rows={2}
/>
</Section>
{/* ── Ýüztumanyň görnüşi ───────────────────────────────────────────── */}
<Section title={t('intlPayment.currencySection', 'Ýüztumanyň görnüşi')}>
<FormInput
type="select"
label={t('intlPayment.currencyType', 'Ýüztumanyň görnüşi')}
value={form.currency_type}
onChange={(v) => set('currency_type', v)}
options={CURRENCY_OPTIONS}
error={errors.currency_type}
required
/>
</Section>
{/* ── Lokasiýa ─────────────────────────────────────────────────────── */}
<Section title={t('intlPayment.locationSection', 'Lokasiýa')}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('intlPayment.province', 'Welaýat')}
value={form.province}
onChange={(v) => { set('province', v); set('branch', '') }}
options={PROVINCE_OPTIONS}
error={errors.province}
required
/>
<FormInput
type="searchable-select"
label={t('intlPayment.branch', 'Şahamça')}
value={form.branch}
onChange={(v) => set('branch', v)}
options={[]} // Fetched from branches API filtered by province
placeholder="Saýlamak üçin basyň"
error={errors.branch}
required
/>
</div>
</Section>
{/* ── Şahsy maglumatlar ─────────────────────────────────────────────── */}
<Section title={t('intlPayment.personalSection', 'Şahsy maglumatlar')}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('intlPayment.passportLastName', 'Pasportdaky familýa')}
value={form.passport_last_name}
onChange={(v) => set('passport_last_name', v)}
options={[]}
placeholder="Pasportdaky familýa"
error={errors.passport_last_name}
required
/>
<FormInput
type="text"
label={t('intlPayment.passportFirstName', 'Pasportdaky ady')}
value={form.passport_first_name}
onChange={(v) => set('passport_first_name', v)}
placeholder="Pasportdaky ady"
error={errors.passport_first_name}
required
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="phone"
label={t('intlPayment.phone', 'Telefon')}
value={form.phone}
onChange={(v) => set('phone', v)}
error={errors.phone}
required
/>
<FormInput
type="email"
label={t('intlPayment.email', 'E-poçta')}
value={form.email}
onChange={(v) => set('email', v)}
placeholder="E-poçta"
/>
</div>
<FormInput
type="text"
label={t('intlPayment.homeAddress', 'Häzirki ýaşyş ýeri')}
value={form.home_address}
onChange={(v) => set('home_address', v)}
placeholder="Häzirki ýaşyş ýeri"
/>
</Section>
{/* ── Töleg upgradyjynyň maglumatlary ──────────────────────────────── */}
<Section title={t('intlPayment.payerSection', 'Töleg upgradyjynyň maglumatlary')}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('intlPayment.passportSeries', 'Pasport seriýasy')}
value={form.passport_series}
onChange={(v) => set('passport_series', v)}
options={PASSPORT_SERIES_OPTIONS}
error={errors.passport_series}
required
/>
<FormInput
type="text"
label={t('intlPayment.passportNumber', 'Pasport nomeri')}
value={form.passport_number}
onChange={(v) => set('passport_number', v)}
placeholder="Pasport nomeri"
error={errors.passport_number}
required
/>
</div>
<FormInput
type="text"
label={t('intlPayment.payerFullName', 'Ady Familiýasy Atasnyň ady')}
value={form.payer_full_name}
onChange={(v) => set('payer_full_name', v)}
placeholder="Ady Familiýasy Atasnyň ady"
error={errors.payer_full_name}
required
/>
<FormInput
type="text"
label={t('intlPayment.payerAccount', 'Goşun hasaby')}
value={form.payer_account_number}
onChange={(v) => set('payer_account_number', v)}
placeholder="Goşun hasaby"
error={errors.payer_account_number}
required
/>
</Section>
{/* ── Töleg kabul edijiniň maglumatlary ────────────────────────────── */}
<Section title={t('intlPayment.receiverSection', 'Töleg kabul edijiniň maglumatlary')}>
<FormInput
type="textarea"
label={t('intlPayment.receiverInfo', 'Saňa ger')}
value={form.receiver_info}
onChange={(v) => set('receiver_info', v)}
placeholder="Saňa ger"
rows={3}
error={errors.receiver_info}
required
/>
</Section>
{/* ── Kabul ediji talyp boyunca resminamalar ────────────────────────── */}
<Section title={t('intlPayment.kabulDocsSection', 'Kabul ediji talyp boyunca resminamalar')}>
<div className="space-y-4">
{KABUL_DOCS.map(({ key, label }) => (
<FormInput
key={key}
type="file"
label={label}
onFileChange={(f) => set(key, f)}
fileValue={form[key] as File | null}
accept="image/*,.pdf"
/>
))}
</div>
</Section>
{/* ── Upgradyý boyunca resminamalar ─────────────────────────────────── */}
<Section title={t('intlPayment.upgradDocsSection', 'Upgradyý boyunca resminamalar')}>
<div className="space-y-4">
{UPGRAD_DOCS.map(({ key, label }) => (
<FormInput
key={key}
type="file"
label={label}
onFileChange={(f) => set(key, f)}
fileValue={form[key] as File | null}
accept="image/*,.pdf"
/>
))}
</div>
</Section>
{/* ── Actions ───────────────────────────────────────────────────────── */}
<div className="flex items-center justify-end gap-3 pb-6">
<Button
type="button"
variant="outline"
onClick={() => navigate('/intl-payments/visa-master')}
disabled={isSubmitting}
>
{t('common.cancel', 'Ýatyr')}
</Button>
<Button
type="button"
onClick={handleSubmit}
disabled={isSubmitting}
className="min-w-[240px]"
>
{isSubmitting ? <Spinner className="size-4" /> : submitLabel}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,78 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import {
intlPaymentApi,
type IntlPaymentListParams,
type IntlPaymentCreatePayload,
type IntlPaymentUpdatePayload,
} from '../api/visaMasterPaymentsApi'
export const INTL_PAYMENT_KEYS = {
all: ['intl-payments-visa'] as const,
lists: () => [...INTL_PAYMENT_KEYS.all, 'list'] as const,
list: (p: IntlPaymentListParams) => [...INTL_PAYMENT_KEYS.lists(), p] as const,
detail: (id: string) => [...INTL_PAYMENT_KEYS.all, 'detail', id] as const,
}
export function useIntlPayments(params: IntlPaymentListParams) {
return useQuery({
queryKey: INTL_PAYMENT_KEYS.list(params),
queryFn: () => intlPaymentApi.list(params),
placeholderData: (prev) => prev,
})
}
export function useIntlPayment(id: string) {
return useQuery({
queryKey: INTL_PAYMENT_KEYS.detail(id),
queryFn: () => intlPaymentApi.getById(id),
enabled: !!id,
})
}
export function useCreateIntlPayment() {
const qc = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: IntlPaymentCreatePayload) => intlPaymentApi.create(payload),
onSuccess: () => {
qc.invalidateQueries({ queryKey: INTL_PAYMENT_KEYS.lists() })
toast.success(t('intlPayment.createSuccess', 'Töleg döredildi'))
},
onError: () => {
toast.error(t('intlPayment.createError', 'Döretmek başartmady'))
},
})
}
export function useUpdateIntlPayment(id: string) {
const qc = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: IntlPaymentUpdatePayload) => intlPaymentApi.update(id, payload),
onSuccess: () => {
qc.invalidateQueries({ queryKey: INTL_PAYMENT_KEYS.lists() })
qc.invalidateQueries({ queryKey: INTL_PAYMENT_KEYS.detail(id) })
toast.success(t('intlPayment.updateSuccess', 'Töleg üýtgedildi'))
},
onError: () => {
toast.error(t('intlPayment.updateError', 'Üýtgetmek başartmady'))
},
})
}
export function useDeleteIntlPayment() {
const qc = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (id: string) => intlPaymentApi.delete(id),
onSuccess: () => {
qc.invalidateQueries({ queryKey: INTL_PAYMENT_KEYS.lists() })
toast.success(t('intlPayment.deleteSuccess', 'Töleg pozuldy'))
},
onError: () => {
toast.error(t('intlPayment.deleteError', 'Pozmak başartmady'))
},
})
}