started connect with api
This commit is contained in:
@@ -1,425 +1,132 @@
|
||||
// ─── 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
|
||||
}
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── 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
|
||||
id: number;
|
||||
uniqueId: string;
|
||||
cardStateId: number;
|
||||
cardTypeId: number;
|
||||
region: string;
|
||||
branchId: number;
|
||||
customerName: string;
|
||||
customerSurname: string;
|
||||
customerPatronicName: string;
|
||||
bornAt: string | null;
|
||||
oldSurname: string | null;
|
||||
citizenship: string;
|
||||
passportSerie: string;
|
||||
passportId: string;
|
||||
passportGivenAt: string | null;
|
||||
passportGivenBy: string;
|
||||
bornPlace: string;
|
||||
jobLocation: string;
|
||||
passportAddress: string;
|
||||
realAddress: string;
|
||||
phone: string;
|
||||
phoneAdditional: string;
|
||||
status: string;
|
||||
passportOne: string;
|
||||
passportTwo: string;
|
||||
passportThree: string;
|
||||
passportFour: string;
|
||||
notes: string;
|
||||
userId: number;
|
||||
paid: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ─── 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
|
||||
export interface CardOrderListResponse {
|
||||
count: number;
|
||||
cardOrders: CardOrder[];
|
||||
}
|
||||
|
||||
// ─── Pagination ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[]
|
||||
totalCount: number
|
||||
page: number
|
||||
perPage: number
|
||||
totalPages: number
|
||||
export interface CardOrderListParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
// ─── Filter params ──────────────────────────────────────────────────────────
|
||||
status?: string;
|
||||
branch_id?: string;
|
||||
user_id?: string;
|
||||
card_state_id?: string;
|
||||
card_type_id?: string;
|
||||
region?: string;
|
||||
}
|
||||
|
||||
// ─── 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
|
||||
bornAt: string;
|
||||
bornPlace: string;
|
||||
branchId: number;
|
||||
cardStateId: number;
|
||||
cardTypeId: number;
|
||||
citizenship: string;
|
||||
customerName: string;
|
||||
customerPatronicName: string;
|
||||
customerSurname: string;
|
||||
jobLocation: string;
|
||||
notes: string;
|
||||
oldSurname: string;
|
||||
paid: boolean;
|
||||
passportAddress: string;
|
||||
passportFour: string;
|
||||
passportGivenAt: string;
|
||||
passportGivenBy: string;
|
||||
passportId: string;
|
||||
passportOne: string;
|
||||
passportSerie: string;
|
||||
passportThree: string;
|
||||
passportTwo: string;
|
||||
phone: string;
|
||||
phoneAdditional: string;
|
||||
realAddress: string;
|
||||
region: string;
|
||||
status: string;
|
||||
uniqueId: string;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export interface UpdateCardOrderPayload extends Partial<CreateCardOrderPayload> {}
|
||||
export type UpdateCardOrderPayload = CreateCardOrderPayload;
|
||||
|
||||
import apiClient from '@/lib/api/client'
|
||||
// ─── Card Order CRUD ──────────────────────────────────────────────────────────
|
||||
|
||||
// ─── 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',
|
||||
export async function fetchCardOrders(params: CardOrderListParams = {}, signal?: AbortSignal): Promise<CardOrderListResponse> {
|
||||
const { page, limit, search, status, branch_id, user_id, card_state_id, card_type_id, region } = params;
|
||||
const { data } = await apiClient.get<CardOrderListResponse>("/card-orders", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
search: search || undefined,
|
||||
status: status || undefined,
|
||||
branch_id: branch_id || undefined,
|
||||
user_id: user_id || undefined,
|
||||
card_state_id: card_state_id || undefined,
|
||||
card_type_id: card_type_id || undefined,
|
||||
region: region || undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
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
|
||||
signal,
|
||||
});
|
||||
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 fetchCardOrderById(id: number): Promise<CardOrder> {
|
||||
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 createCardOrder(payload: CreateCardOrderPayload): Promise<CardOrder> {
|
||||
const { data } = await apiClient.post<CardOrder>("/card-orders", payload);
|
||||
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 updateCardOrder(id: number, payload: UpdateCardOrderPayload): Promise<CardOrder> {
|
||||
const { data } = await apiClient.put<CardOrder>(`/card-orders/${id}`, payload);
|
||||
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}`)
|
||||
export async function deleteCardOrder(id: number): Promise<void> {
|
||||
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
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { toast } from "sonner";
|
||||
import { CreditCard, User, FileText, Upload } from "lucide-react";
|
||||
import { CreditCard, User, FileText, MapPin } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
@@ -11,16 +11,8 @@ import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { SelectOption } from "@/components/formInput";
|
||||
import type { CardOrder, CardOrderStatus, CreateCardOrderPayload } from "../api/orderNewCardApi";
|
||||
import {
|
||||
useCardIssuanceReasons,
|
||||
useCardTypes,
|
||||
useProvinces,
|
||||
useBranches,
|
||||
useCreateCardOrder,
|
||||
useUpdateCardOrder,
|
||||
} from "../hooks/useOrderNewCard";
|
||||
import type { CardOrder } from "../api/orderNewCardApi";
|
||||
import { useCreateCard, useUpdateCard } from "../hooks/useOrderNewCard";
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/orderNewCard.schema";
|
||||
import type { OrderNewCardFormData } from "../schemas/orderNewCard.schema";
|
||||
|
||||
@@ -53,7 +45,7 @@ interface StepDef {
|
||||
subtitleKey: string;
|
||||
subtitleFallback: string;
|
||||
icon: LucideIcon;
|
||||
validate: (form: OrderNewCardFormData, mode: "create" | "edit") => FlatErrors;
|
||||
validate: (form: OrderNewCardFormData) => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
@@ -64,7 +56,7 @@ const STEPS: StepDef[] = [
|
||||
subtitleKey: "orderNewCardForm.steps.card.subtitle",
|
||||
subtitleFallback: "Görnüş & lokasiýa",
|
||||
icon: CreditCard,
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
validate: (form) => validateStep(0, form),
|
||||
},
|
||||
{
|
||||
id: "personal",
|
||||
@@ -73,7 +65,7 @@ const STEPS: StepDef[] = [
|
||||
subtitleKey: "orderNewCardForm.steps.personal.subtitle",
|
||||
subtitleFallback: "Maglumatlar",
|
||||
icon: User,
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
validate: (form) => validateStep(1, form),
|
||||
},
|
||||
{
|
||||
id: "passport",
|
||||
@@ -82,16 +74,16 @@ const STEPS: StepDef[] = [
|
||||
subtitleKey: "orderNewCardForm.steps.passport.subtitle",
|
||||
subtitleFallback: "Resmi maglumat",
|
||||
icon: FileText,
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
validate: (form) => validateStep(2, form),
|
||||
},
|
||||
{
|
||||
id: "files",
|
||||
titleKey: "cardOrder.step.files",
|
||||
titleFallback: "Faýllar",
|
||||
subtitleKey: "orderNewCardForm.steps.files.subtitle",
|
||||
subtitleFallback: "Ýüklemek & Tassyklamak",
|
||||
icon: Upload,
|
||||
validate: (form, mode) => validateStep(3, form, mode),
|
||||
id: "contact",
|
||||
titleKey: "cardOrder.step.contact",
|
||||
titleFallback: "Kontakt",
|
||||
subtitleKey: "orderNewCardForm.steps.contact.subtitle",
|
||||
subtitleFallback: "Salgy & Bellik",
|
||||
icon: MapPin,
|
||||
validate: (form) => validateStep(3, form),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -106,119 +98,113 @@ interface StepContentProps {
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
|
||||
function StepCard({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
statusOptions,
|
||||
issuanceReasonOptions,
|
||||
cardTypeOptions,
|
||||
provinceOptions,
|
||||
branchOptions,
|
||||
}: StepContentProps & {
|
||||
statusOptions: SelectOption[];
|
||||
issuanceReasonOptions: SelectOption[];
|
||||
cardTypeOptions: SelectOption[];
|
||||
provinceOptions: SelectOption[];
|
||||
branchOptions: SelectOption[];
|
||||
}) {
|
||||
function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
const STATUS_OPTIONS = useMemo(
|
||||
() => [
|
||||
{ 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") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("loanOrderForm.labels.status") || "Status"}
|
||||
label={t("cardOrder.field.status", "Status")}
|
||||
required
|
||||
value={form.status}
|
||||
onChange={(v) => set("status", v as CardOrderStatus)}
|
||||
options={statusOptions}
|
||||
onChange={(v) => set("status", v)}
|
||||
options={STATUS_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.status}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.uniqueId", "Sargyt belgisi")}
|
||||
required
|
||||
value={form.uniqueId}
|
||||
onChange={(v) => set("uniqueId", v)}
|
||||
placeholder={t("cardOrder.field.uniqueId", "Sargyt belgisi")}
|
||||
error={errors.uniqueId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
id="paid"
|
||||
type="checkbox"
|
||||
checked={form.paid}
|
||||
onChange={(e) => set("paid", e.target.checked)}
|
||||
className="w-4 h-4 accent-primary cursor-pointer"
|
||||
/>
|
||||
<label
|
||||
htmlFor="paid"
|
||||
className="text-xs font-semibold text-muted-foreground uppercase tracking-wider cursor-pointer select-none"
|
||||
>
|
||||
{t("cardOrder.field.paid", "Tölenen")}
|
||||
</label>
|
||||
</div>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t("Note") || "Bellik"}
|
||||
value={form.note}
|
||||
onChange={(v) => set("note", v)}
|
||||
label={t("cardOrder.field.notes", "Bellik")}
|
||||
value={form.notes}
|
||||
onChange={(v) => set("notes", v)}
|
||||
placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."}
|
||||
rows={3}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
id="isPaid"
|
||||
type="checkbox"
|
||||
checked={form.isPaid}
|
||||
onChange={(e) => set("isPaid", e.target.checked)}
|
||||
className="w-4 h-4 accent-primary cursor-pointer"
|
||||
/>
|
||||
<label
|
||||
htmlFor="isPaid"
|
||||
className="text-xs font-semibold text-muted-foreground uppercase tracking-wider cursor-pointer select-none"
|
||||
>
|
||||
{t("orderNewCardForm.isPaid") || "Tölenen"}
|
||||
</label>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Kart maglumatlary"}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("Reason for issuing the card") || "Kartyň çykarylmagynyň sebäbi"}
|
||||
required
|
||||
value={form.issuanceReasonId}
|
||||
onChange={(v) => set("issuanceReasonId", v)}
|
||||
options={issuanceReasonOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.issuanceReasonId}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("Card type") || "Kart görnüşi"}
|
||||
type="number"
|
||||
label={t("cardOrder.field.cardTypeId", "Kart görnüşi ID")}
|
||||
required
|
||||
value={form.cardTypeId}
|
||||
onChange={(v) => set("cardTypeId", v)}
|
||||
options={cardTypeOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
placeholder={t("cardOrder.field.cardTypeId", "Kart görnüşi ID")}
|
||||
error={errors.cardTypeId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Region") || "Welaýat"}
|
||||
type="number"
|
||||
label={t("cardOrder.field.cardStateId", "Kart ýagdaýy ID")}
|
||||
required
|
||||
value={form.provinceId}
|
||||
onChange={(v) => {
|
||||
set("provinceId", v);
|
||||
set("branchId", "");
|
||||
}}
|
||||
options={provinceOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.provinceId}
|
||||
value={form.cardStateId}
|
||||
onChange={(v) => set("cardStateId", v)}
|
||||
placeholder={t("cardOrder.field.cardStateId", "Kart ýagdaýy ID")}
|
||||
error={errors.cardStateId}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
|
||||
<BentoCard title={t("cardPinForm.titles.location") || "Lokasiýa"}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("Branch") || "Şahamça"}
|
||||
type="text"
|
||||
label={t("cardOrder.field.region", "Sebit")}
|
||||
required
|
||||
value={form.region}
|
||||
onChange={(v) => set("region", v)}
|
||||
placeholder={t("cardOrder.field.region", "Sebit")}
|
||||
error={errors.region}
|
||||
/>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("cardOrder.field.branchId", "Şahamça ID")}
|
||||
required
|
||||
value={form.branchId}
|
||||
onChange={(v) => set("branchId", v)}
|
||||
options={branchOptions}
|
||||
disabled={!form.provinceId}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
placeholder={t("cardOrder.field.branchId", "Şahamça ID")}
|
||||
error={errors.branchId}
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -227,69 +213,39 @@ function StepCard({
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
citizenshipOptions,
|
||||
}: StepContentProps & {
|
||||
citizenshipOptions: SelectOption[];
|
||||
}) {
|
||||
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Name") || "Ady"}
|
||||
label={t("cardOrder.field.customerName", "Ady")}
|
||||
required
|
||||
value={form.firstName}
|
||||
onChange={(v) => set("firstName", v)}
|
||||
placeholder={t("Name") || "Ady"}
|
||||
error={errors.firstName}
|
||||
value={form.customerName}
|
||||
onChange={(v) => set("customerName", v)}
|
||||
placeholder={t("cardOrder.field.customerName", "Ady")}
|
||||
error={errors.customerName}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Surname") || "Familiýasy"}
|
||||
label={t("cardOrder.field.customerSurname", "Familiýasy")}
|
||||
required
|
||||
value={form.lastName}
|
||||
onChange={(v) => set("lastName", v)}
|
||||
placeholder={t("Surname") || "Familiýasy"}
|
||||
error={errors.lastName}
|
||||
value={form.customerSurname}
|
||||
onChange={(v) => set("customerSurname", v)}
|
||||
placeholder={t("cardOrder.field.customerSurname", "Familiýasy")}
|
||||
error={errors.customerSurname}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Patronic name") || "Atasynyň ady"}
|
||||
value={form.middleName}
|
||||
onChange={(v) => set("middleName", v)}
|
||||
placeholder={t("Patronic name") || "Atasynyň ady"}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Old surname (if changed)") || "Köne familiýaňyz (eger üýtgän bolsa)"}
|
||||
value={form.formerLastName}
|
||||
onChange={(v) => set("formerLastName", v)}
|
||||
placeholder={t("orderNewCardForm.placeholders.formerLastName") || "Köne familiýaňyz"}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("Date of birth") || "Doglan güni"}
|
||||
required
|
||||
value={form.birthDate}
|
||||
onChange={(v) => set("birthDate", v)}
|
||||
error={errors.birthDate}
|
||||
label={t("cardOrder.field.customerPatronicName", "Atasynyň ady")}
|
||||
value={form.customerPatronicName}
|
||||
onChange={(v) => set("customerPatronicName", v)}
|
||||
placeholder={t("cardOrder.field.customerPatronicName", "Atasynyň ady")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -297,32 +253,103 @@ function StepPersonal({
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone"
|
||||
label={t("Phone") || "Telefon"}
|
||||
type="text"
|
||||
label={t("cardOrder.field.oldSurname", "Köne familiýaňyz (eger üýtgän bolsa)")}
|
||||
value={form.oldSurname}
|
||||
onChange={(v) => set("oldSurname", v)}
|
||||
placeholder={t("cardOrder.field.oldSurname", "Köne familiýa")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("cardOrder.field.bornAt", "Doglan güni")}
|
||||
value={form.bornAt}
|
||||
onChange={(v) => set("bornAt", v)}
|
||||
error={errors.bornAt}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.bornPlace", "Doglan ýeri")}
|
||||
value={form.bornPlace}
|
||||
onChange={(v) => set("bornPlace", v)}
|
||||
placeholder={t("cardOrder.field.bornPlace", "Doglan ýeri")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.citizenship", "Raýatlyk")}
|
||||
required
|
||||
value={form.citizenship}
|
||||
onChange={(v) => set("citizenship", v)}
|
||||
placeholder={t("cardOrder.field.citizenship", "Raýatlyk")}
|
||||
error={errors.citizenship}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.phone", "Telefon")}
|
||||
required
|
||||
value={form.phone}
|
||||
onChange={(v) => set("phone", v)}
|
||||
placeholder={t("cardOrder.field.phone", "Telefon")}
|
||||
error={errors.phone}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone"
|
||||
label={t("Phone Additional") || "Telefon goşmaça"}
|
||||
value={form.phoneExtra}
|
||||
onChange={(v) => set("phoneExtra", v)}
|
||||
error={errors.phoneExtra}
|
||||
type="text"
|
||||
label={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")}
|
||||
value={form.phoneAdditional}
|
||||
onChange={(v) => set("phoneAdditional", v)}
|
||||
placeholder={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportSerie", "Pasport seriýasy")}
|
||||
required
|
||||
value={form.passportSerie}
|
||||
onChange={(v) => set("passportSerie", v)}
|
||||
placeholder={t("cardOrder.field.passportSerie", "Pasport seriýasy")}
|
||||
error={errors.passportSerie}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Citizenship") || "Raýatlyk"}
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportId", "Pasport belgisi")}
|
||||
required
|
||||
value={form.citizenship}
|
||||
onChange={(v) => set("citizenship", v)}
|
||||
options={citizenshipOptions}
|
||||
error={errors.citizenship}
|
||||
value={form.passportId}
|
||||
onChange={(v) => set("passportId", v)}
|
||||
placeholder={t("cardOrder.field.passportId", "Pasport belgisi")}
|
||||
error={errors.passportId}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("cardOrder.field.passportGivenAt", "Pasport berlen senesi")}
|
||||
value={form.passportGivenAt}
|
||||
onChange={(v) => set("passportGivenAt", v)}
|
||||
error={errors.passportGivenAt}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -331,23 +358,85 @@ function StepPersonal({
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("orderNewCardForm.labels.registeredAddress") || "Ýazgy edilen salgyňyz"}
|
||||
required
|
||||
value={form.registeredAddress}
|
||||
onChange={(v) => set("registeredAddress", v)}
|
||||
placeholder={t("orderNewCardForm.labels.registeredAddress") || "Ýazgy edilen salgyňyz"}
|
||||
error={errors.registeredAddress}
|
||||
label={t("cardOrder.field.passportGivenBy", "Kim tarapyndan berildi")}
|
||||
value={form.passportGivenBy}
|
||||
onChange={(v) => set("passportGivenBy", v)}
|
||||
placeholder={t("cardOrder.field.passportGivenBy", "Kim tarapyndan berildi")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("orderNewCardForm.labels.currentAddress") || "Häzirki ýaşaýyş ýeri"}
|
||||
required
|
||||
value={form.currentAddress}
|
||||
onChange={(v) => set("currentAddress", v)}
|
||||
placeholder={t("orderNewCardForm.labels.currentAddress") || "Häzirki ýaşaýyş ýeri"}
|
||||
error={errors.currentAddress}
|
||||
label={t("cardOrder.field.passportAddress", "Pasport salgysy")}
|
||||
value={form.passportAddress}
|
||||
onChange={(v) => set("passportAddress", v)}
|
||||
placeholder={t("cardOrder.field.passportAddress", "Pasport salgysy")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={4}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportOne", "Pasport 1")}
|
||||
value={form.passportOne}
|
||||
onChange={(v) => set("passportOne", v)}
|
||||
placeholder={t("cardOrder.field.passportOne", "Pasport 1")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportTwo", "Pasport 2")}
|
||||
value={form.passportTwo}
|
||||
onChange={(v) => set("passportTwo", v)}
|
||||
placeholder={t("cardOrder.field.passportTwo", "Pasport 2")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportThree", "Pasport 3")}
|
||||
value={form.passportThree}
|
||||
onChange={(v) => set("passportThree", v)}
|
||||
placeholder={t("cardOrder.field.passportThree", "Pasport 3")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportFour", "Pasport 4")}
|
||||
value={form.passportFour}
|
||||
onChange={(v) => set("passportFour", v)}
|
||||
placeholder={t("cardOrder.field.passportFour", "Pasport 4")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepContact({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.realAddress", "Hakyky ýaşaýyş ýeri")}
|
||||
value={form.realAddress}
|
||||
onChange={(v) => set("realAddress", v)}
|
||||
placeholder={t("cardOrder.field.realAddress", "Hakyky ýaşaýyş ýeri")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.jobLocation", "Işleýän ýeri we wezipäňiz")}
|
||||
value={form.jobLocation}
|
||||
onChange={(v) => set("jobLocation", v)}
|
||||
placeholder={t("cardOrder.field.jobLocation", "Işleýän ýeri")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -355,13 +444,13 @@ function StepPersonal({
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("orderNewCardForm.labels.workplace") || "Işleýän ýeriňiz we wezipäňiz"}
|
||||
type="number"
|
||||
label={t("cardOrder.field.userId", "Ulanyjy ID")}
|
||||
required
|
||||
value={form.workplace}
|
||||
onChange={(v) => set("workplace", v)}
|
||||
placeholder={t("orderNewCardForm.labels.workplace") || "Işleýän ýeriňiz we wezipäňiz"}
|
||||
error={errors.workplace}
|
||||
value={form.userId}
|
||||
onChange={(v) => set("userId", v)}
|
||||
placeholder={t("cardOrder.field.userId", "Ulanyjy ID")}
|
||||
error={errors.userId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -369,198 +458,14 @@ function StepPersonal({
|
||||
);
|
||||
}
|
||||
|
||||
function StepPassport({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
passportSeriesOptions,
|
||||
}: StepContentProps & {
|
||||
passportSeriesOptions: SelectOption[];
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Passport serie") || "Pasport seriýasy"}
|
||||
required
|
||||
value={form.passportSeriesId}
|
||||
onChange={(v) => set("passportSeriesId", v)}
|
||||
options={passportSeriesOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.passportSeriesId}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Passport id") || "Pasport belgisi"}
|
||||
required
|
||||
value={form.passportNumber}
|
||||
onChange={(v) => set("passportNumber", v)}
|
||||
placeholder={t("Passport id") || "Pasport belgisi"}
|
||||
error={errors.passportNumber}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("Passport date of issue") || "Pasport berlen senesi"}
|
||||
required
|
||||
value={form.passportIssueDate}
|
||||
onChange={(v) => set("passportIssueDate", v)}
|
||||
error={errors.passportIssueDate}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Passport given by") || "Kim tarapyndan berildi"}
|
||||
required
|
||||
value={form.passportIssuedBy}
|
||||
onChange={(v) => set("passportIssuedBy", v)}
|
||||
placeholder={t("Passport given by") || "Kim tarapyndan berildi"}
|
||||
error={errors.passportIssuedBy}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Born place (passport)") || "Doglan ýeri (pasport)"}
|
||||
required
|
||||
value={form.passportBirthPlace}
|
||||
onChange={(v) => set("passportBirthPlace", v)}
|
||||
placeholder={t("Born place (passport)") || "Doglan ýeri (pasport)"}
|
||||
error={errors.passportBirthPlace}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepFiles({ form, errors, set, t, mode, initialData }: StepContentProps & { mode: "create" | "edit"; initialData?: CardOrder }) {
|
||||
const existingFiles =
|
||||
mode === "edit" && initialData
|
||||
? [
|
||||
{ url: initialData.passportFiles.page1, label: t("Passport (page 1)") || "Pasport (sahypa 1)" },
|
||||
{ url: initialData.passportFiles.page23, label: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)" },
|
||||
{ url: initialData.passportFiles.page89, label: t("Passport (page 8-9)") || "Pasport (8-9 sahypa)" },
|
||||
{ url: initialData.passportFiles.page32, label: t("Passport (page 32)") || "Pasport (32-nji sahypa)" },
|
||||
].filter((f): f is { url: string; label: string } => !!f.url)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{existingFiles.length > 0 && (
|
||||
<BentoGrid cols={4}>
|
||||
{existingFiles.map(({ url, label }) => (
|
||||
<BentoCard key={label} title={label}>
|
||||
<a href={url} target="_blank" rel="noopener noreferrer" className="text-xs text-primary underline truncate block">
|
||||
{t("loanOrderForm.fileLabels.viewFile") || "Faýly gör"}
|
||||
</a>
|
||||
</BentoCard>
|
||||
))}
|
||||
</BentoGrid>
|
||||
)}
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={
|
||||
mode === "edit"
|
||||
? t("loanOrderForm.fileLabels.replacePage1") || "Pasport (sahypa 1) (çalyşmak)"
|
||||
: t("Passport (page 1)") || "Pasport (sahypa 1)"
|
||||
}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passportPage1}
|
||||
onFileChange={(f) => set("passportPage1", f)}
|
||||
error={errors.passportPage1}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={
|
||||
mode === "edit"
|
||||
? t("loanOrderForm.fileLabels.replacePage23") || "Pasport (2-3-nji sahypa) (çalyşmak)"
|
||||
: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)"
|
||||
}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passportPage23}
|
||||
onFileChange={(f) => set("passportPage23", f)}
|
||||
error={errors.passportPage23}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={t("Passport (page 8-9)") || "Pasport (8-9 sahypa)"}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passportPage89}
|
||||
onFileChange={(f) => set("passportPage89", f)}
|
||||
error={errors.passportPage89}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={t("Passport (page 32)") || "Pasport (32-nji sahypa)"}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passportPage32}
|
||||
onFileChange={(f) => set("passportPage32", f)}
|
||||
error={errors.passportPage32}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{mode === "create" && (
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<div
|
||||
className={`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-colors
|
||||
${errors.termsAccepted ? "bg-destructive/10 border border-destructive/30" : "bg-primary/5 border border-primary/20"}`}
|
||||
onClick={() => set("termsAccepted", !form.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("I accept terms of contract") || "Şertnama bilen razylaşýaryn (Okamak üçin bas)"}
|
||||
</span>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateCardOrder();
|
||||
const updateMutation = useUpdateCardOrder(initialData?.id ?? "");
|
||||
const createMutation = useCreateCard();
|
||||
const updateMutation = useUpdateCard(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
@@ -579,42 +484,16 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>()));
|
||||
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(new Set());
|
||||
|
||||
// ── Lookup data ────────────────────────────────────────────────────────────
|
||||
|
||||
const { data: reasons = [] } = useCardIssuanceReasons();
|
||||
const { data: cardTypes = [] } = useCardTypes();
|
||||
const { data: provinces = [] } = useProvinces();
|
||||
const { data: branches = [] } = useBranches(form.provinceId ? Number(form.provinceId) : undefined);
|
||||
|
||||
const toOptions = (arr: { id: number; name: string }[]): SelectOption[] => arr.map((x) => ({ value: String(x.id), label: x.name }));
|
||||
|
||||
const statusOptions: SelectOption[] = [
|
||||
{ value: "PENDING", label: t("cardOrder.status.pending", "Garaşylýar") },
|
||||
{ value: "APPROVED", label: t("cardOrder.status.approved", "Tassyklandy") },
|
||||
{ value: "REJECTED", label: t("cardOrder.status.rejected", "Ýatyryldy") },
|
||||
];
|
||||
|
||||
const citizenshipOptions: SelectOption[] = [
|
||||
{ value: "Turkmenistan", label: t("citizenship.tm", "Turkmenistan") },
|
||||
{ value: "Russia", label: t("citizenship.ru", "Russiýa") },
|
||||
{ value: "Other", label: t("citizenship.other", "Beýlekiler") },
|
||||
];
|
||||
|
||||
const passportSeriesOptions: SelectOption[] = [
|
||||
{ value: "1", label: "I" },
|
||||
{ value: "2", label: "II" },
|
||||
{ value: "3", label: "III" },
|
||||
];
|
||||
|
||||
// ── Computed step error state ──────────────────────────────────────────────
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
const out = new Set<number>();
|
||||
visited.forEach((i) => {
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i);
|
||||
if (Object.keys(STEPS[i].validate(form)).length > 0) out.add(i);
|
||||
});
|
||||
return out;
|
||||
}, [form, mode, visited]);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [form, visited, i18n.language]);
|
||||
|
||||
// ── set helper ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -626,14 +505,19 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const currentStepErrors = useMemo(
|
||||
() => (submittedSteps.has(currentStep) ? STEPS[currentStep].validate(form, mode) : {}),
|
||||
[currentStep, form, mode, submittedSteps],
|
||||
);
|
||||
const allSubmittedErrors = useMemo(() => {
|
||||
const result: FlatErrors = {};
|
||||
for (const stepIdx of submittedSteps) {
|
||||
Object.assign(result, STEPS[stepIdx].validate(form));
|
||||
}
|
||||
return result;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [form, submittedSteps, i18n.language]);
|
||||
|
||||
const errors = useMemo(() => {
|
||||
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>);
|
||||
return { ...fromRHF, ...currentStepErrors };
|
||||
}, [rhfErrors, currentStepErrors]);
|
||||
return { ...fromRHF, ...allSubmittedErrors };
|
||||
}, [rhfErrors, allSubmittedErrors]);
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t]);
|
||||
|
||||
@@ -646,7 +530,7 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
const handleNext = () => {
|
||||
markVisited(currentStep);
|
||||
markSubmitted(currentStep);
|
||||
const errs = STEPS[currentStep].validate(form, mode);
|
||||
const errs = STEPS[currentStep].validate(form);
|
||||
if (Object.keys(errs).length > 0) {
|
||||
Object.entries(errs).forEach(([key, msg]) => {
|
||||
setError(key as keyof OrderNewCardFormData, { type: "manual", message: msg });
|
||||
@@ -681,7 +565,7 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
setSubmittedSteps(new Set(STEPS.map((_, i) => i)));
|
||||
|
||||
const allErrors: FlatErrors = {};
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode));
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form));
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
Object.entries(allErrors).forEach(([key, msg]) => {
|
||||
@@ -689,7 +573,7 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
});
|
||||
toast.error(t("validation.fixErrors", "Käbir hökmany meýdanlar doldurylan däldir."));
|
||||
for (let i = 0; i < STEPS.length; i++) {
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) {
|
||||
if (Object.keys(STEPS[i].validate(form)).length > 0) {
|
||||
setCurrentStep(i);
|
||||
break;
|
||||
}
|
||||
@@ -703,7 +587,7 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
if (mode === "edit") {
|
||||
await updateMutation.mutateAsync(payload);
|
||||
} else {
|
||||
await createMutation.mutateAsync(payload as CreateCardOrderPayload);
|
||||
await createMutation.mutateAsync(payload);
|
||||
}
|
||||
navigate("/order-new-card");
|
||||
} catch {
|
||||
@@ -733,12 +617,10 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-2xl font-bold text-foreground">
|
||||
{mode === "create" ? t("cardOrder.createTitle") || "Täze karz orderi" : t("cardOrder.editTitle") || "Karz orderini üýtget"}
|
||||
{mode === "create" ? t("cardOrder.createTitle", "Täze kart sargydy") : t("cardOrder.editTitle", "Kart sargydyny üýtget")}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{mode === "create"
|
||||
? t("loanOrders.createDescription") || "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň."
|
||||
: t("loanOrders.editDescription") || "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň."}
|
||||
{t("loanOrders.createDescription", "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.")}
|
||||
</p>
|
||||
{/* Step bar */}
|
||||
<div className="bg-card border border-border rounded-xl p-3 overflow-x-auto">
|
||||
@@ -746,19 +628,10 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
</div>
|
||||
|
||||
{/* Step content */}
|
||||
{currentStep === 0 && (
|
||||
<StepCard
|
||||
{...stepProps}
|
||||
statusOptions={statusOptions}
|
||||
issuanceReasonOptions={toOptions(reasons)}
|
||||
cardTypeOptions={toOptions(cardTypes)}
|
||||
provinceOptions={toOptions(provinces)}
|
||||
branchOptions={toOptions(branches)}
|
||||
/>
|
||||
)}
|
||||
{currentStep === 1 && <StepPersonal {...stepProps} citizenshipOptions={citizenshipOptions} />}
|
||||
{currentStep === 2 && <StepPassport {...stepProps} passportSeriesOptions={passportSeriesOptions} />}
|
||||
{currentStep === 3 && <StepFiles {...stepProps} mode={mode} initialData={initialData} />}
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
||||
{currentStep === 2 && <StepPassport {...stepProps} />}
|
||||
{currentStep === 3 && <StepContact {...stepProps} />}
|
||||
|
||||
{/* Actions */}
|
||||
<FormActions
|
||||
@@ -768,11 +641,11 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? doSubmit : undefined}
|
||||
submitLabel={mode === "create" ? t("cardOrder.submit") || "Kart sargyt dörediň" : t("common.save") || "Ýatda sakla"}
|
||||
loadingLabel={t("common.saving") || "Ýüklenilýär..."}
|
||||
cancelLabel={t("common.cancel") || "Ýatyr"}
|
||||
prevLabel={t("common.prev") || "Yza"}
|
||||
nextLabel={t("common.next") || "Indiki"}
|
||||
submitLabel={mode === "create" ? t("cardOrder.submit", "Kart sargyt dörediň") : t("common.save", "Ýatda sakla")}
|
||||
loadingLabel={t("common.saving", "Ýüklenilýär...")}
|
||||
cancelLabel={t("common.cancel", "Ýatyr")}
|
||||
prevLabel={t("common.prev", "Yza")}
|
||||
nextLabel={t("common.next", "Indiki")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -780,28 +653,34 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
|
||||
function mapInitial(data: CardOrder): Partial<OrderNewCardFormData> {
|
||||
return {
|
||||
isPaid: data.isPaid,
|
||||
uniqueId: data.uniqueId,
|
||||
status: data.status,
|
||||
note: data.note ?? "",
|
||||
issuanceReasonId: String(data.issuanceReasonId),
|
||||
cardTypeId: String(data.cardTypeId),
|
||||
provinceId: String(data.provinceId),
|
||||
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,
|
||||
registeredAddress: data.registeredAddress,
|
||||
currentAddress: data.currentAddress,
|
||||
workplace: data.workplace,
|
||||
passportSeriesId: String(data.passportSeriesId),
|
||||
passportNumber: data.passportNumber,
|
||||
passportIssueDate: data.passportIssueDate,
|
||||
passportIssuedBy: data.passportIssuedBy,
|
||||
passportBirthPlace: data.passportBirthPlace,
|
||||
paid: data.paid,
|
||||
cardStateId: String(data.cardStateId ?? ""),
|
||||
cardTypeId: String(data.cardTypeId ?? ""),
|
||||
region: data.region ?? "",
|
||||
branchId: String(data.branchId ?? ""),
|
||||
customerName: data.customerName,
|
||||
customerSurname: data.customerSurname,
|
||||
customerPatronicName: data.customerPatronicName ?? "",
|
||||
oldSurname: data.oldSurname ?? "",
|
||||
bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "",
|
||||
bornPlace: data.bornPlace ?? "",
|
||||
citizenship: data.citizenship ?? "",
|
||||
phone: data.phone ?? "",
|
||||
phoneAdditional: data.phoneAdditional ?? "",
|
||||
passportSerie: data.passportSerie,
|
||||
passportId: data.passportId,
|
||||
passportOne: data.passportOne ?? "",
|
||||
passportTwo: data.passportTwo ?? "",
|
||||
passportThree: data.passportThree ?? "",
|
||||
passportFour: data.passportFour ?? "",
|
||||
passportGivenAt: data.passportGivenAt ? data.passportGivenAt.slice(0, 10) : "",
|
||||
passportGivenBy: data.passportGivenBy ?? "",
|
||||
passportAddress: data.passportAddress ?? "",
|
||||
realAddress: data.realAddress ?? "",
|
||||
jobLocation: data.jobLocation ?? "",
|
||||
userId: String(data.userId ?? ""),
|
||||
notes: data.notes ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,138 +1,87 @@
|
||||
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'
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import { fetchCardOrders, fetchCardOrderById, createCardOrder, updateCardOrder, deleteCardOrder } from "../api/orderNewCardApi";
|
||||
import type { CardOrderListParams, 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,
|
||||
}
|
||||
all: ["card-orders"] as const,
|
||||
lists: () => [...cardOrderKeys.all, "list"] as const,
|
||||
list: (p: CardOrderListParams) => [...cardOrderKeys.lists(), p] as const,
|
||||
details: () => [...cardOrderKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...cardOrderKeys.details(), id] as const,
|
||||
};
|
||||
|
||||
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardOrders(filters: CardOrderFilters) {
|
||||
export function useCards(params?: CardOrderListParams) {
|
||||
const debouncedSearch = useDebouncedValue(params?.search ?? "");
|
||||
const queryParams: CardOrderListParams = { ...(params ?? {}), search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: cardOrderKeys.list(filters),
|
||||
queryFn: () => fetchCardOrders(filters),
|
||||
queryKey: cardOrderKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => fetchCardOrders(queryParams, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Single ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardOrderById(id: string) {
|
||||
export function useCardById(id: number) {
|
||||
return useQuery({
|
||||
queryKey: cardOrderKeys.detail(id),
|
||||
queryFn: () => fetchCardOrderById(id),
|
||||
enabled: Boolean(id),
|
||||
})
|
||||
queryFn: () => fetchCardOrderById(id),
|
||||
enabled: Boolean(id),
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCardOrder() {
|
||||
const { t } = useTranslation()
|
||||
const qc = useQueryClient()
|
||||
export function useCreateCard() {
|
||||
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'))
|
||||
qc.invalidateQueries({ queryKey: cardOrderKeys.all });
|
||||
toast.success(t("cardOrder.createSuccess", "Kart sargydy üstünlikli döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCardOrder(id: string) {
|
||||
const { t } = useTranslation()
|
||||
const qc = useQueryClient()
|
||||
export function useUpdateCard(id: number) {
|
||||
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'))
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: cardOrderKeys.all });
|
||||
toast.success(t("cardOrder.updateSuccess", "Kart sargydy üstünlikli täzelendi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCardOrder() {
|
||||
const { t } = useTranslation()
|
||||
const qc = useQueryClient()
|
||||
export function useDeleteCard() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => deleteCardOrder(id),
|
||||
mutationFn: (id: number) => 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'))
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: cardOrderKeys.all });
|
||||
toast.success(t("cardOrder.deleteSuccess", "Kart sargydy üstünlikli pozuldy"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── 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,
|
||||
})
|
||||
}
|
||||
@@ -1,122 +1,72 @@
|
||||
import { z } from "zod";
|
||||
import i18next from "i18next";
|
||||
import type { CardOrderStatus } from "../api/orderNewCardApi";
|
||||
import type { CreateCardOrderPayload } from "../api/orderNewCardApi";
|
||||
|
||||
const fileRequired = z.custom<File>((val) => val instanceof File, "validation.requiredFile");
|
||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
||||
const optional = () => z.string().default("");
|
||||
|
||||
export const orderNewCardFormSchema = z.object({
|
||||
isPaid: z.boolean(),
|
||||
uniqueId: z.string().min(1, "validation.required"),
|
||||
status: z.string().min(1, "validation.required"),
|
||||
note: z.string().optional(),
|
||||
issuanceReasonId: z.string().min(1, "validation.required"),
|
||||
paid: z.boolean(),
|
||||
cardStateId: z.string().min(1, "validation.required"),
|
||||
cardTypeId: z.string().min(1, "validation.required"),
|
||||
provinceId: z.string().min(1, "validation.required"),
|
||||
region: z.string().min(1, "validation.required"),
|
||||
branchId: z.string().min(1, "validation.required"),
|
||||
firstName: z.string().min(1, "validation.required"),
|
||||
lastName: z.string().min(1, "validation.required"),
|
||||
middleName: z.string().optional(),
|
||||
formerLastName: z.string().optional(),
|
||||
birthDate: z.string().min(1, "validation.required"),
|
||||
phone: z
|
||||
.string()
|
||||
.min(1, "validation.required")
|
||||
.refine(
|
||||
(val) => {
|
||||
const digits = val.replace(/\D/g, "");
|
||||
return digits.length === 8;
|
||||
},
|
||||
{ message: "validation.invalidPhone" },
|
||||
)
|
||||
.refine(
|
||||
(val) => {
|
||||
const digits = val.replace(/\D/g, "");
|
||||
const prefix = digits.slice(0, 2);
|
||||
return VALID_PHONE_PREFIXES.includes(prefix);
|
||||
},
|
||||
{ message: "validation.invalidPhonePrefix" },
|
||||
),
|
||||
phoneExtra: z
|
||||
.string()
|
||||
.refine(
|
||||
(val) => {
|
||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
||||
const digits = val.replace(/\D/g, "");
|
||||
return digits.length === 8;
|
||||
},
|
||||
{ message: "validation.invalidPhone" },
|
||||
)
|
||||
.refine(
|
||||
(val) => {
|
||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
||||
const digits = val.replace(/\D/g, "");
|
||||
return VALID_PHONE_PREFIXES.includes(digits.slice(0, 2));
|
||||
},
|
||||
{ message: "validation.invalidPhonePrefix" },
|
||||
)
|
||||
.optional(),
|
||||
customerName: z.string().min(1, "validation.required"),
|
||||
customerSurname: z.string().min(1, "validation.required"),
|
||||
customerPatronicName: optional(),
|
||||
oldSurname: optional(),
|
||||
bornAt: optional(),
|
||||
bornPlace: optional(),
|
||||
citizenship: z.string().min(1, "validation.required"),
|
||||
registeredAddress: z.string().min(1, "validation.required"),
|
||||
currentAddress: z.string().min(1, "validation.required"),
|
||||
workplace: z.string().min(1, "validation.required"),
|
||||
passportSeriesId: z.string().min(1, "validation.required"),
|
||||
passportNumber: z.string().min(1, "validation.required"),
|
||||
passportIssueDate: z.string().min(1, "validation.required"),
|
||||
passportIssuedBy: z.string().min(1, "validation.required"),
|
||||
passportBirthPlace: z.string().min(1, "validation.required"),
|
||||
passportPage1: z.custom<File | null>().nullable(),
|
||||
passportPage23: z.custom<File | null>().nullable(),
|
||||
passportPage89: z.custom<File | null>().nullable(),
|
||||
passportPage32: z.custom<File | null>().nullable(),
|
||||
termsAccepted: z.boolean(),
|
||||
phone: z.string().min(1, "validation.required"),
|
||||
phoneAdditional: optional(),
|
||||
passportSerie: z.string().min(1, "validation.required"),
|
||||
passportId: z.string().min(1, "validation.required"),
|
||||
passportOne: optional(),
|
||||
passportTwo: optional(),
|
||||
passportThree: optional(),
|
||||
passportFour: optional(),
|
||||
passportGivenAt: optional(),
|
||||
passportGivenBy: optional(),
|
||||
passportAddress: optional(),
|
||||
realAddress: optional(),
|
||||
jobLocation: optional(),
|
||||
userId: z.string().min(1, "validation.required"),
|
||||
notes: optional(),
|
||||
});
|
||||
|
||||
export type OrderNewCardFormData = z.infer<typeof orderNewCardFormSchema>;
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<OrderNewCardFormData>>> = {
|
||||
0: orderNewCardFormSchema.pick({
|
||||
uniqueId: true,
|
||||
status: true,
|
||||
issuanceReasonId: true,
|
||||
cardStateId: true,
|
||||
cardTypeId: true,
|
||||
provinceId: true,
|
||||
region: true,
|
||||
branchId: true,
|
||||
}),
|
||||
1: orderNewCardFormSchema.pick({
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
birthDate: true,
|
||||
phone: true,
|
||||
phoneExtra: true,
|
||||
customerName: true,
|
||||
customerSurname: true,
|
||||
citizenship: true,
|
||||
registeredAddress: true,
|
||||
currentAddress: true,
|
||||
workplace: true,
|
||||
phone: true,
|
||||
}),
|
||||
2: orderNewCardFormSchema.pick({
|
||||
passportSeriesId: true,
|
||||
passportNumber: true,
|
||||
passportIssueDate: true,
|
||||
passportIssuedBy: true,
|
||||
passportBirthPlace: true,
|
||||
passportSerie: true,
|
||||
passportId: true,
|
||||
}),
|
||||
3: z.object({
|
||||
passportPage1: fileRequired,
|
||||
passportPage23: fileRequired,
|
||||
passportPage89: fileRequired,
|
||||
passportPage32: fileRequired,
|
||||
termsAccepted: z.literal(true, { message: "validation.requiredTerms" }),
|
||||
3: orderNewCardFormSchema.pick({
|
||||
userId: true,
|
||||
}),
|
||||
};
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: OrderNewCardFormData,
|
||||
mode: "create" | "edit",
|
||||
): Partial<Record<keyof OrderNewCardFormData, string>> {
|
||||
if (stepIndex === 3 && mode === "edit") return {};
|
||||
export function validateStep(stepIndex: number, form: OrderNewCardFormData): Partial<Record<keyof OrderNewCardFormData, string>> {
|
||||
const schema = stepSchemas[stepIndex];
|
||||
const result = schema.safeParse(form);
|
||||
if (result.success) return {};
|
||||
|
||||
const errors: Partial<Record<keyof OrderNewCardFormData, string>> = {};
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof OrderNewCardFormData;
|
||||
@@ -129,64 +79,67 @@ export function validateStep(
|
||||
}
|
||||
|
||||
export const DEFAULT_FORM_VALUES: OrderNewCardFormData = {
|
||||
isPaid: false,
|
||||
uniqueId: "",
|
||||
status: "",
|
||||
note: "",
|
||||
issuanceReasonId: "",
|
||||
paid: false,
|
||||
cardStateId: "",
|
||||
cardTypeId: "",
|
||||
provinceId: "",
|
||||
region: "",
|
||||
branchId: "",
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
middleName: "",
|
||||
formerLastName: "",
|
||||
birthDate: "",
|
||||
customerName: "",
|
||||
customerSurname: "",
|
||||
customerPatronicName: "",
|
||||
oldSurname: "",
|
||||
bornAt: "",
|
||||
bornPlace: "",
|
||||
citizenship: "",
|
||||
phone: "",
|
||||
phoneExtra: "",
|
||||
citizenship: "Turkmenistan",
|
||||
registeredAddress: "",
|
||||
currentAddress: "",
|
||||
workplace: "",
|
||||
passportSeriesId: "",
|
||||
passportNumber: "",
|
||||
passportIssueDate: "",
|
||||
passportIssuedBy: "",
|
||||
passportBirthPlace: "",
|
||||
passportPage1: null,
|
||||
passportPage23: null,
|
||||
passportPage89: null,
|
||||
passportPage32: null,
|
||||
termsAccepted: false,
|
||||
phoneAdditional: "",
|
||||
passportSerie: "",
|
||||
passportId: "",
|
||||
passportOne: "",
|
||||
passportTwo: "",
|
||||
passportThree: "",
|
||||
passportFour: "",
|
||||
passportGivenAt: "",
|
||||
passportGivenBy: "",
|
||||
passportAddress: "",
|
||||
realAddress: "",
|
||||
jobLocation: "",
|
||||
userId: "",
|
||||
notes: "",
|
||||
};
|
||||
|
||||
export function buildPayload(data: OrderNewCardFormData) {
|
||||
export function buildPayload(data: OrderNewCardFormData): CreateCardOrderPayload {
|
||||
return {
|
||||
isPaid: data.isPaid,
|
||||
status: data.status as CardOrderStatus,
|
||||
note: data.note || null,
|
||||
issuanceReasonId: Number(data.issuanceReasonId),
|
||||
uniqueId: data.uniqueId.trim(),
|
||||
status: data.status.trim(),
|
||||
paid: data.paid,
|
||||
cardStateId: Number(data.cardStateId),
|
||||
cardTypeId: Number(data.cardTypeId),
|
||||
provinceId: Number(data.provinceId),
|
||||
region: data.region.trim(),
|
||||
branchId: Number(data.branchId),
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
middleName: data.middleName || null,
|
||||
formerLastName: data.formerLastName || null,
|
||||
birthDate: data.birthDate,
|
||||
phone: data.phone,
|
||||
phoneExtra: data.phoneExtra || null,
|
||||
citizenship: data.citizenship,
|
||||
registeredAddress: data.registeredAddress,
|
||||
currentAddress: data.currentAddress,
|
||||
workplace: data.workplace,
|
||||
passportSeriesId: Number(data.passportSeriesId),
|
||||
passportNumber: data.passportNumber,
|
||||
passportIssueDate: data.passportIssueDate,
|
||||
passportIssuedBy: data.passportIssuedBy,
|
||||
passportBirthPlace: data.passportBirthPlace,
|
||||
...(data.passportPage1 && { passportPage1: data.passportPage1 }),
|
||||
...(data.passportPage23 && { passportPage23: data.passportPage23 }),
|
||||
...(data.passportPage89 && { passportPage89: data.passportPage89 }),
|
||||
...(data.passportPage32 && { passportPage32: data.passportPage32 }),
|
||||
customerName: data.customerName.trim(),
|
||||
customerSurname: data.customerSurname.trim(),
|
||||
customerPatronicName: data.customerPatronicName.trim(),
|
||||
oldSurname: data.oldSurname.trim(),
|
||||
bornAt: data.bornAt.trim(),
|
||||
bornPlace: data.bornPlace.trim(),
|
||||
citizenship: data.citizenship.trim(),
|
||||
phone: data.phone.trim(),
|
||||
phoneAdditional: data.phoneAdditional.trim(),
|
||||
passportSerie: data.passportSerie.trim(),
|
||||
passportId: data.passportId.trim(),
|
||||
passportOne: data.passportOne.trim(),
|
||||
passportTwo: data.passportTwo.trim(),
|
||||
passportThree: data.passportThree.trim(),
|
||||
passportFour: data.passportFour.trim(),
|
||||
passportGivenAt: data.passportGivenAt.trim(),
|
||||
passportGivenBy: data.passportGivenBy.trim(),
|
||||
passportAddress: data.passportAddress.trim(),
|
||||
realAddress: data.realAddress.trim(),
|
||||
jobLocation: data.jobLocation.trim(),
|
||||
userId: Number(data.userId),
|
||||
notes: data.notes.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user