added some pages
This commit is contained in:
1 parent
c2548280a2
commit
c7797c3e31
61 files changed
+8309
-35
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
]
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user