started connect with api
This commit is contained in:
1 parent
0ca218505d
commit
6da59f42d9
112 files changed
+7091
-6989
No files matched your search
@@ -2,213 +2,114 @@ import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type CardPinStatus = "pending" | "approved" | "rejected";
|
||||
|
||||
export interface CardPinItem {
|
||||
id: string;
|
||||
card_type: string;
|
||||
card_type_label: string;
|
||||
card_number: string;
|
||||
created_at: string;
|
||||
province: string;
|
||||
province_label: string;
|
||||
branch: string;
|
||||
branch_label: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
father_name: string;
|
||||
birth_date: string;
|
||||
export interface CardPinOrder {
|
||||
id: number;
|
||||
uniqueId: string;
|
||||
userId: number;
|
||||
cardTypeId: number;
|
||||
cardNumber: string;
|
||||
region: string;
|
||||
branchId: number;
|
||||
customerName: string;
|
||||
customerSurname: string;
|
||||
customerPatronicName: string | null;
|
||||
bornAt: string | null;
|
||||
phone: string;
|
||||
status: CardPinStatus;
|
||||
note: string | null;
|
||||
passport_series: string;
|
||||
passport_number: string;
|
||||
passport_file_1: string | null;
|
||||
passport_file_2: string | null;
|
||||
passport_file_3: string | null;
|
||||
passport_file_4: string | null;
|
||||
created_by: string;
|
||||
created_by_label: string;
|
||||
passportSerie: string;
|
||||
passportId: string;
|
||||
passportOne: string | null;
|
||||
passportTwo: string | null;
|
||||
passportThree: string | null;
|
||||
passportFour: string | null;
|
||||
status: string;
|
||||
notes: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface CardPinListResponse {
|
||||
count: number;
|
||||
cardPinOrders: CardPinOrder[];
|
||||
}
|
||||
|
||||
export interface CardPinListParams {
|
||||
page?: number;
|
||||
per_page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
status?: CardPinStatus | "";
|
||||
province?: string;
|
||||
// ─── Filter params ──────────────────────────────────────────────────────────
|
||||
status?: string;
|
||||
branch_id?: string;
|
||||
user_id?: string;
|
||||
card_type_id?: string;
|
||||
region?: string;
|
||||
}
|
||||
|
||||
export interface CardPinListResponse {
|
||||
data: CardPinItem[];
|
||||
meta: {
|
||||
current_page: number;
|
||||
last_page: number;
|
||||
per_page: number;
|
||||
total: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CardPinCreatePayload {
|
||||
status: CardPinStatus;
|
||||
note: string;
|
||||
card_type: string;
|
||||
card_number: string;
|
||||
province: string;
|
||||
branch: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
father_name: string;
|
||||
birth_date: string;
|
||||
export interface CreateCardPinPayload {
|
||||
bornAt: string;
|
||||
branchId: number;
|
||||
cardNumber: string;
|
||||
cardTypeId: number;
|
||||
customerName: string;
|
||||
customerPatronicName: string;
|
||||
customerSurname: string;
|
||||
notes: string;
|
||||
passportFour: string;
|
||||
passportId: string;
|
||||
passportOne: string;
|
||||
passportSerie: string;
|
||||
passportThree: string;
|
||||
passportTwo: string;
|
||||
phone: string;
|
||||
passport_series: string;
|
||||
passport_number: string;
|
||||
passport_file_1: File | null;
|
||||
passport_file_2: File | null;
|
||||
passport_file_3: File | null;
|
||||
passport_file_4: File | null;
|
||||
region: string;
|
||||
status: string;
|
||||
uniqueId: string;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export type CardPinUpdatePayload = CardPinCreatePayload;
|
||||
export type UpdateCardPinPayload = CreateCardPinPayload;
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_CARD_PINS: CardPinItem[] = [
|
||||
{
|
||||
id: "1",
|
||||
card_type: "altyn_asyr",
|
||||
card_type_label: "Altyn Asyr",
|
||||
card_number: "8600123456789012",
|
||||
created_at: "2024-05-07 10:00",
|
||||
province: "ashgabat",
|
||||
province_label: "Aşgabat",
|
||||
branch: "1",
|
||||
branch_label: "Merkezi şahamça",
|
||||
first_name: "Aman",
|
||||
last_name: "Amanow",
|
||||
father_name: "Amanowiç",
|
||||
birth_date: "1990-01-01",
|
||||
phone: "99365123456",
|
||||
status: "pending",
|
||||
note: "Test bellik",
|
||||
passport_series: "I-MR",
|
||||
passport_number: "123456",
|
||||
passport_file_1: null,
|
||||
passport_file_2: null,
|
||||
passport_file_3: null,
|
||||
passport_file_4: null,
|
||||
created_by: "1",
|
||||
created_by_label: "Admin",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
card_type: "visa",
|
||||
card_type_label: "Visa",
|
||||
card_number: "4400123456789012",
|
||||
created_at: "2024-05-07 11:30",
|
||||
province: "mary",
|
||||
province_label: "Mary",
|
||||
branch: "2",
|
||||
branch_label: "Mary şahamçasy",
|
||||
first_name: "Berdi",
|
||||
last_name: "Berdiyew",
|
||||
father_name: "Berdiyewiç",
|
||||
birth_date: "1995-05-05",
|
||||
phone: "99361112233",
|
||||
status: "approved",
|
||||
note: null,
|
||||
passport_series: "I-LB",
|
||||
passport_number: "654321",
|
||||
passport_file_1: null,
|
||||
passport_file_2: null,
|
||||
passport_file_3: null,
|
||||
passport_file_4: null,
|
||||
created_by: "1",
|
||||
created_by_label: "Admin",
|
||||
},
|
||||
];
|
||||
|
||||
export const cardPinApi = {
|
||||
list: async (params: CardPinListParams): Promise<CardPinListResponse> => {
|
||||
// Mock data return
|
||||
return {
|
||||
data: MOCK_CARD_PINS,
|
||||
meta: {
|
||||
current_page: params.page || 1,
|
||||
last_page: 1,
|
||||
per_page: params.per_page || 25,
|
||||
total: MOCK_CARD_PINS.length,
|
||||
/** GET /card-pin-orders */
|
||||
list: async (params: CardPinListParams = {}, signal?: AbortSignal): Promise<CardPinListResponse> => {
|
||||
const { page, limit, search, status, branch_id, user_id, card_type_id, region } = params;
|
||||
const { data } = await apiClient.get<CardPinListResponse>("/card-pin-orders", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
search: search || undefined,
|
||||
status: status || undefined,
|
||||
branch_id: branch_id || undefined,
|
||||
user_id: user_id || undefined,
|
||||
card_type_id: card_type_id || undefined,
|
||||
region: region || undefined,
|
||||
},
|
||||
};
|
||||
|
||||
const { data } = await apiClient.get("/card-pins", { params });
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
getById: async (id: string): Promise<CardPinItem> => {
|
||||
const mock = MOCK_CARD_PINS.find((p) => p.id === id);
|
||||
if (mock) return mock;
|
||||
|
||||
const { data } = await apiClient.get(`/card-pins/${id}`);
|
||||
/** GET /card-pin-orders/:id */
|
||||
getById: async (id: number): Promise<CardPinOrder> => {
|
||||
const { data } = await apiClient.get<CardPinOrder>(`/card-pin-orders/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
create: (payload: CardPinCreatePayload): Promise<CardPinItem> => {
|
||||
const form = buildFormData(payload);
|
||||
return apiClient
|
||||
.post("/card-pins", form, {
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
})
|
||||
.then((r) => r.data);
|
||||
/** POST /card-pin-orders */
|
||||
create: async (payload: CreateCardPinPayload): Promise<CardPinOrder> => {
|
||||
const { data } = await apiClient.post<CardPinOrder>("/card-pin-orders", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
update: (id: string, payload: CardPinUpdatePayload): Promise<CardPinItem> => {
|
||||
const form = buildFormData(payload);
|
||||
form.append("_method", "PUT");
|
||||
return apiClient
|
||||
.post(`/card-pins/${id}`, form, {
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
})
|
||||
.then((r) => r.data);
|
||||
/** PUT /card-pin-orders/:id */
|
||||
update: async (id: number, payload: UpdateCardPinPayload): Promise<CardPinOrder> => {
|
||||
const { data } = await apiClient.put<CardPinOrder>(`/card-pin-orders/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
delete: (id: string): Promise<void> => apiClient.delete(`/card-pins/${id}`).then((r) => r.data),
|
||||
/** DELETE /card-pin-orders/:id */
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await apiClient.delete(`/card-pin-orders/${id}`);
|
||||
},
|
||||
};
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function buildFormData(payload: CardPinCreatePayload): FormData {
|
||||
const form = new FormData();
|
||||
|
||||
const textFields: (keyof CardPinCreatePayload)[] = [
|
||||
"status",
|
||||
"note",
|
||||
"card_type",
|
||||
"card_number",
|
||||
"province",
|
||||
"branch",
|
||||
"first_name",
|
||||
"last_name",
|
||||
"father_name",
|
||||
"birth_date",
|
||||
"phone",
|
||||
"passport_series",
|
||||
"passport_number",
|
||||
];
|
||||
|
||||
for (const key of textFields) {
|
||||
const val = payload[key];
|
||||
if (val !== null && val !== undefined) {
|
||||
form.append(key, String(val));
|
||||
}
|
||||
}
|
||||
|
||||
const fileFields: (keyof CardPinCreatePayload)[] = ["passport_file_1", "passport_file_2", "passport_file_3", "passport_file_4"];
|
||||
|
||||
for (const key of fileFields) {
|
||||
const file = payload[key];
|
||||
if (file instanceof File) form.append(key, file);
|
||||
}
|
||||
|
||||
return form;
|
||||
}
|
||||
@@ -1,124 +1,103 @@
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type { TFunction } from 'i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { CreditCard, User, FileText } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { useState, useCallback, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { CreditCard, User, FileText } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
||||
import { BentoGrid, BentoCard } from '@/components/bento'
|
||||
import type { CardPinItem, CardPinCreatePayload } from '@/features/cardPins/api/cardPinApi'
|
||||
import { useCreateCardPin, useUpdateCardPin } from '@/features/cardPins/hooks/useCardPins'
|
||||
import { validateStep, DEFAULT_FORM_VALUES } from '@/features/cardPins/schemas/cardPin.schema'
|
||||
import type { CardPinFormData } from '@/features/cardPins/schemas/cardPin.schema'
|
||||
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 { CardPinOrder, CreateCardPinPayload } from "@/features/cardPins/api/cardPinApi";
|
||||
import { useCreateCardPin, useUpdateCardPin } from "@/features/cardPins/hooks/useCardPins";
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "@/features/cardPins/schemas/cardPin.schema";
|
||||
import type { CardPinFormData } from "@/features/cardPins/schemas/cardPin.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface CardPinFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardPinItem
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardPinOrder;
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const CARD_TYPE_OPTIONS = [
|
||||
{ value: 'altyn_asyr', label: 'Altyn Asyr' },
|
||||
{ value: 'visa', label: 'Visa' },
|
||||
{ value: 'mastercard', label: 'MasterCard' },
|
||||
]
|
||||
|
||||
const PASSPORT_SERIES_OPTIONS = [
|
||||
{ value: 'I', label: 'I' },
|
||||
{ value: 'II', label: 'II' },
|
||||
{ value: 'I-MR', label: 'I-MR' },
|
||||
{ value: 'II-MR', label: 'II-MR' },
|
||||
]
|
||||
|
||||
const PROVINCE_OPTIONS = [
|
||||
{ value: 'ashgabat', label: 'Aşgabat' },
|
||||
{ value: 'mary', label: 'Mary' },
|
||||
{ value: 'dasoguz', label: 'Daşoguz' },
|
||||
{ value: 'lebap', label: 'Lebap' },
|
||||
{ value: 'balkan', label: 'Balkan' },
|
||||
{ value: 'ahal', label: 'Ahal' },
|
||||
]
|
||||
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
|
||||
type FlatErrors = Partial<Record<keyof CardPinFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof CardPinFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof CardPinFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof CardPinFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
|
||||
interface StepDef {
|
||||
id: string
|
||||
titleKey: string
|
||||
titleFallback: string
|
||||
subtitleKey: string
|
||||
subtitleFallback: string
|
||||
icon: LucideIcon
|
||||
validate: (form: CardPinFormData, mode: 'create' | 'edit') => FlatErrors
|
||||
id: string;
|
||||
titleKey: string;
|
||||
titleFallback: string;
|
||||
subtitleKey: string;
|
||||
subtitleFallback: string;
|
||||
icon: LucideIcon;
|
||||
validate: (form: CardPinFormData) => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
{
|
||||
id: 'card',
|
||||
titleKey: 'cardPin.step.card',
|
||||
titleFallback: 'Kart',
|
||||
subtitleKey: 'cardPinForm.steps.card.subtitle',
|
||||
subtitleFallback: 'Görnüş & lokasiýa',
|
||||
id: "card",
|
||||
titleKey: "cardPin.step.card",
|
||||
titleFallback: "Kart",
|
||||
subtitleKey: "cardPinForm.steps.card.subtitle",
|
||||
subtitleFallback: "Görnüş & lokasiýa",
|
||||
icon: CreditCard,
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
validate: (form) => validateStep(0, form),
|
||||
},
|
||||
{
|
||||
id: 'personal',
|
||||
titleKey: 'cardPin.step.personal',
|
||||
titleFallback: 'Şahsy',
|
||||
subtitleKey: 'cardPinForm.steps.personal.subtitle',
|
||||
subtitleFallback: 'Maglumatlar',
|
||||
id: "personal",
|
||||
titleKey: "cardPin.step.personal",
|
||||
titleFallback: "Şahsy",
|
||||
subtitleKey: "cardPinForm.steps.personal.subtitle",
|
||||
subtitleFallback: "Maglumatlar",
|
||||
icon: User,
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
validate: (form) => validateStep(1, form),
|
||||
},
|
||||
{
|
||||
id: 'passport',
|
||||
titleKey: 'cardPin.step.passport',
|
||||
titleFallback: 'Pasport',
|
||||
subtitleKey: 'cardPinForm.steps.passport.subtitle',
|
||||
subtitleFallback: 'Resminamalar',
|
||||
id: "passport",
|
||||
titleKey: "cardPin.step.passport",
|
||||
titleFallback: "Pasport",
|
||||
subtitleKey: "cardPinForm.steps.passport.subtitle",
|
||||
subtitleFallback: "Resminamalar",
|
||||
icon: FileText,
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
validate: (form) => validateStep(2, form),
|
||||
},
|
||||
]
|
||||
];
|
||||
|
||||
// ─── Shared step content props ────────────────────────────────────────────────
|
||||
|
||||
interface StepContentProps {
|
||||
form: CardPinFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof CardPinFormData>(k: K, v: CardPinFormData[K]) => void
|
||||
t: TFunction
|
||||
form: CardPinFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof CardPinFormData>(k: K, v: CardPinFormData[K]) => void;
|
||||
t: TFunction;
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
|
||||
function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
const STATUS_OPTIONS = useMemo(() => [
|
||||
{ value: 'pending', label: t('cardPin.status.pending', 'Garaşylýar') },
|
||||
{ value: 'approved', label: t('cardPin.status.approved', 'Tassyklandy') },
|
||||
{ value: 'rejected', label: t('cardPin.status.rejected', 'Ret edildi') },
|
||||
], [t])
|
||||
const STATUS_OPTIONS = useMemo(
|
||||
() => [
|
||||
{ value: "pending", label: t("cardPin.status.pending", "Garaşylýar") },
|
||||
{ value: "approved", label: t("cardPin.status.approved", "Tassyklandy") },
|
||||
{ value: "rejected", label: t("cardPin.status.rejected", "Ýatyryldy") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -126,75 +105,86 @@ function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('loanOrderForm.labels.status') || 'Status'}
|
||||
label={t("cardPin.field.status", "Statusy")}
|
||||
required
|
||||
value={form.status}
|
||||
onChange={(v) => set('status', v)}
|
||||
onChange={(v) => set("status", v)}
|
||||
options={STATUS_OPTIONS}
|
||||
error={errors.status}
|
||||
placeholder={t('loanOrderForm.placeholders.select') || 'Saýlaň'}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Note') || 'Bellik'}
|
||||
value={form.note}
|
||||
onChange={(v) => set('note', v)}
|
||||
placeholder={t('loanOrderForm.placeholders.note') || 'Bellik...'}
|
||||
label={t("cardPin.field.uniqueId", "Sargyt belgisi")}
|
||||
required
|
||||
value={form.uniqueId}
|
||||
onChange={(v) => set("uniqueId", v)}
|
||||
placeholder={t("cardPin.field.uniqueId", "Sargyt belgisi")}
|
||||
error={errors.uniqueId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('loanOrderForm.titles.cardInfo') || 'Kart maglumatlary'}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Loan type') || 'Kart görnüşi'}
|
||||
required
|
||||
value={form.card_type}
|
||||
onChange={(v) => set('card_type', v)}
|
||||
options={CARD_TYPE_OPTIONS}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
error={errors.card_type}
|
||||
/>
|
||||
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Kart maglumatlary"}>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Card number') || 'Kart belgisi'}
|
||||
label={t("cardPin.field.cardNumber", "Kart belgisi")}
|
||||
required
|
||||
value={form.card_number}
|
||||
onChange={(v) => set('card_number', v)}
|
||||
placeholder={t('Card number') || 'Kart belgisi'}
|
||||
error={errors.card_number}
|
||||
value={form.cardNumber}
|
||||
onChange={(v) => set("cardNumber", v)}
|
||||
placeholder={t("cardPin.field.cardNumber", "Kart belgisi")}
|
||||
error={errors.cardNumber}
|
||||
/>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("cardPin.field.cardTypeId", "Kart görnüşi ID")}
|
||||
required
|
||||
value={form.cardTypeId}
|
||||
onChange={(v) => set("cardTypeId", v)}
|
||||
placeholder={t("cardPin.field.cardTypeId", "Kart görnüşi ID")}
|
||||
error={errors.cardTypeId}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('cardPinForm.titles.location') || 'Lokasiýa'}>
|
||||
<BentoCard title={t("cardPinForm.titles.location") || "Lokasiýa"}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Region') || 'Welaýat'}
|
||||
type="text"
|
||||
label={t("cardPin.field.region", "Sebit")}
|
||||
required
|
||||
value={form.province}
|
||||
onChange={(v) => { set('province', v); set('branch', '') }}
|
||||
options={PROVINCE_OPTIONS}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
error={errors.province}
|
||||
value={form.region}
|
||||
onChange={(v) => set("region", v)}
|
||||
placeholder={t("cardPin.field.region", "Sebit")}
|
||||
error={errors.region}
|
||||
/>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Branch') || 'Şahamça'}
|
||||
type="number"
|
||||
label={t("cardPin.field.branchId", "Şahamça ID")}
|
||||
required
|
||||
value={form.branch}
|
||||
onChange={(v) => set('branch', v)}
|
||||
options={[]}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
disabled={!form.province}
|
||||
error={errors.branch}
|
||||
value={form.branchId}
|
||||
onChange={(v) => set("branchId", v)}
|
||||
placeholder={t("cardPin.field.branchId", "Şahamça ID")}
|
||||
error={errors.branchId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t("cardPin.field.notes", "Bellikler")}
|
||||
value={form.notes}
|
||||
onChange={(v) => set("notes", v)}
|
||||
placeholder={t("cardPin.field.notes", "Bellikler")}
|
||||
error={errors.notes}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
@@ -203,313 +193,285 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text" label={t('Name') || 'Ady'} required
|
||||
value={form.first_name} onChange={(v) => set('first_name', v)}
|
||||
placeholder={t('Name') || 'Ady'} error={errors.first_name}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text" label={t('Surname') || 'Familiýasy'} required
|
||||
value={form.last_name} onChange={(v) => set('last_name', v)}
|
||||
placeholder={t('Surname') || 'Familiýasy'} error={errors.last_name}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text" label={t('Patronic name') || 'Atasynyň ady'}
|
||||
value={form.father_name} onChange={(v) => set('father_name', v)}
|
||||
placeholder={t('Patronic name') || 'Atasynyň ady'}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date" label={t('Date of birth') || 'Doglan güni'} required
|
||||
value={form.birth_date} onChange={(v) => set('birth_date', v)}
|
||||
error={errors.birth_date}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone" label={t('Phone') || 'Telefon'} required
|
||||
value={form.phone} onChange={(v) => set('phone', v)}
|
||||
error={errors.phone}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function StepPassport({ form, errors, set, t, mode, initialData }: StepContentProps & {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardPinItem
|
||||
}) {
|
||||
const existingFiles =
|
||||
mode === 'edit' && initialData
|
||||
? [
|
||||
{ url: initialData.passport_file_1, label: t('Passport (page 1)') || 'Pasport (sahypa 1)' },
|
||||
{ url: initialData.passport_file_2, label: t('Passport (page 2-3)') || 'Pasport (2-3-nji sahypa)' },
|
||||
{ url: initialData.passport_file_3, label: t('Passport (page 8-9)') || 'Pasport (8-9 sahypa)' },
|
||||
{ url: initialData.passport_file_4, 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">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Passport serie') || 'Pasport seriýasy'}
|
||||
type="text"
|
||||
label={t("cardPin.field.customerName", "Ady")}
|
||||
required
|
||||
value={form.passport_series}
|
||||
onChange={(v) => set('passport_series', v)}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
error={errors.passport_series}
|
||||
value={form.customerName}
|
||||
onChange={(v) => set("customerName", v)}
|
||||
placeholder={t("cardPin.field.customerName", "Ady")}
|
||||
error={errors.customerName}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Passport id') || 'Pasport belgisi'}
|
||||
label={t("cardPin.field.customerSurname", "Familiýasy")}
|
||||
required
|
||||
value={form.passport_number}
|
||||
onChange={(v) => set('passport_number', v)}
|
||||
placeholder={t('Passport id') || 'Pasport belgisi'}
|
||||
error={errors.passport_number}
|
||||
value={form.customerSurname}
|
||||
onChange={(v) => set("customerSurname", v)}
|
||||
placeholder={t("cardPin.field.customerSurname", "Familiýasy")}
|
||||
error={errors.customerSurname}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.customerPatronicName", "Atasynyň ady")}
|
||||
value={form.customerPatronicName}
|
||||
onChange={(v) => set("customerPatronicName", v)}
|
||||
placeholder={t("cardPin.field.customerPatronicName", "Atasynyň ady")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{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}>
|
||||
<BentoGrid cols={3}>
|
||||
<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.passport_file_1}
|
||||
onFileChange={(f) => set('passport_file_1', f)}
|
||||
error={errors.passport_file_1}
|
||||
type="date"
|
||||
label={t("cardPin.field.bornAt", "Doglan güni")}
|
||||
value={form.bornAt}
|
||||
onChange={(v) => set("bornAt", v)}
|
||||
error={errors.bornAt}
|
||||
/>
|
||||
</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.passport_file_2}
|
||||
onFileChange={(f) => set('passport_file_2', f)}
|
||||
error={errors.passport_file_2}
|
||||
type="text"
|
||||
label={t("cardPin.field.phone", "Telefon")}
|
||||
required
|
||||
value={form.phone}
|
||||
onChange={(v) => set("phone", v)}
|
||||
placeholder={t("cardPin.field.phone", "Telefon")}
|
||||
error={errors.phone}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={t('Passport (page 8-9)') || 'Pasport (8-9 sahypa)'}
|
||||
required={mode === 'create'}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_file_3}
|
||||
onFileChange={(f) => set('passport_file_3', f)}
|
||||
error={errors.passport_file_3}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={t('Passport (page 32)') || 'Pasport (32-nji sahypa)'}
|
||||
required={mode === 'create'}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_file_4}
|
||||
onFileChange={(f) => set('passport_file_4', f)}
|
||||
error={errors.passport_file_4}
|
||||
type="number"
|
||||
label={t("cardPin.field.userId", "Ulanyjy ID")}
|
||||
required
|
||||
value={form.userId}
|
||||
onChange={(v) => set("userId", v)}
|
||||
placeholder={t("cardPin.field.userId", "Ulanyjy ID")}
|
||||
error={errors.userId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportSerie", "Pasport seriýasy")}
|
||||
required
|
||||
value={form.passportSerie}
|
||||
onChange={(v) => set("passportSerie", v)}
|
||||
placeholder={t("cardPin.field.passportSerie", "Pasport seriýasy")}
|
||||
error={errors.passportSerie}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||
required
|
||||
value={form.passportId}
|
||||
onChange={(v) => set("passportId", v)}
|
||||
placeholder={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||
error={errors.passportId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={4}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportOne", "Pasport 1")}
|
||||
value={form.passportOne}
|
||||
onChange={(v) => set("passportOne", v)}
|
||||
placeholder={t("cardPin.field.passportOne", "Pasport 1")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportTwo", "Pasport 2")}
|
||||
value={form.passportTwo}
|
||||
onChange={(v) => set("passportTwo", v)}
|
||||
placeholder={t("cardPin.field.passportTwo", "Pasport 2")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportThree", "Pasport 3")}
|
||||
value={form.passportThree}
|
||||
onChange={(v) => set("passportThree", v)}
|
||||
placeholder={t("cardPin.field.passportThree", "Pasport 3")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportFour", "Pasport 4")}
|
||||
value={form.passportFour}
|
||||
onChange={(v) => set("passportFour", v)}
|
||||
placeholder={t("cardPin.field.passportFour", "Pasport 4")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const createMutation = useCreateCardPin()
|
||||
const updateMutation = useUpdateCardPin(initialData?.id ?? '')
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const createMutation = useCreateCardPin();
|
||||
const updateMutation = useUpdateCardPin(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, setError,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<CardPinFormData>({
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
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())
|
||||
const form = watch();
|
||||
const [currentStep, setCurrentStep] = useState(0);
|
||||
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());
|
||||
|
||||
// ── Computed step errors ───────────────────────────────────────────────────
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
const out = new Set<number>()
|
||||
const out = new Set<number>();
|
||||
visited.forEach((i) => {
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i)
|
||||
})
|
||||
return out
|
||||
}, [form, mode, visited, i18n.language])
|
||||
if (Object.keys(STEPS[i].validate(form)).length > 0) out.add(i);
|
||||
});
|
||||
return out;
|
||||
}, [form, mode, visited, i18n.language]);
|
||||
|
||||
// ── set helper ─────────────────────────────────────────────────────────────
|
||||
|
||||
const set = useCallback(<K extends keyof CardPinFormData>(key: K, value: CardPinFormData[K]) => {
|
||||
(setValue as (name: K, val: CardPinFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
const set = useCallback(
|
||||
<K extends keyof CardPinFormData>(key: K, value: CardPinFormData[K]) => {
|
||||
(setValue as (name: K, val: CardPinFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const allSubmittedErrors = useMemo(() => {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const stepIdx of submittedSteps) {
|
||||
Object.assign(result, STEPS[stepIdx].validate(form, mode))
|
||||
Object.assign(result, STEPS[stepIdx].validate(form));
|
||||
}
|
||||
return result
|
||||
}, [form, mode, submittedSteps, i18n.language])
|
||||
return result;
|
||||
}, [form, mode, submittedSteps, i18n.language]);
|
||||
const errors = useMemo(() => {
|
||||
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>)
|
||||
return { ...fromRHF, ...allSubmittedErrors }
|
||||
}, [rhfErrors, allSubmittedErrors])
|
||||
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>);
|
||||
return { ...fromRHF, ...allSubmittedErrors };
|
||||
}, [rhfErrors, allSubmittedErrors]);
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t])
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t]);
|
||||
|
||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||
|
||||
const markVisited = (i: number) =>
|
||||
setVisited((prev) => new Set([...prev, i]))
|
||||
const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i]));
|
||||
|
||||
const markSubmitted = (i: number) =>
|
||||
setSubmittedSteps((prev) => new Set([...prev, i]))
|
||||
const markSubmitted = (i: number) => setSubmittedSteps((prev) => new Set([...prev, i]));
|
||||
|
||||
const handleNext = () => {
|
||||
markVisited(currentStep)
|
||||
markSubmitted(currentStep)
|
||||
const errs = STEPS[currentStep].validate(form, mode)
|
||||
markVisited(currentStep);
|
||||
markSubmitted(currentStep);
|
||||
const errs = STEPS[currentStep].validate(form);
|
||||
if (Object.keys(errs).length > 0) {
|
||||
Object.entries(errs).forEach(([key, msg]) => {
|
||||
setError(key as keyof CardPinFormData, { type: 'manual', message: msg })
|
||||
})
|
||||
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||
return
|
||||
setError(key as keyof CardPinFormData, { type: "manual", message: msg });
|
||||
});
|
||||
toast.error(t("common.errors.fillRequiredCorrectly", "Dogry maglumat girizmegiňizi haýyş edýäris."));
|
||||
return;
|
||||
}
|
||||
setCurrentStep(currentStep + 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
setCurrentStep(currentStep + 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
markVisited(currentStep)
|
||||
setCurrentStep(currentStep - 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(currentStep - 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep)
|
||||
setCurrentStep(i)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(i);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = () => {
|
||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
||||
setSubmittedSteps(new Set(STEPS.map((_, i) => i)))
|
||||
setVisited(new Set(STEPS.map((_, i) => i)));
|
||||
setSubmittedSteps(new Set(STEPS.map((_, i) => i)));
|
||||
|
||||
const values = getValues()
|
||||
const allErrors: FlatErrors = {}
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(values, mode))
|
||||
const values = getValues();
|
||||
const allErrors: FlatErrors = {};
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(values));
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
Object.entries(allErrors).forEach(([key, msg]) => {
|
||||
setError(key as keyof CardPinFormData, { type: 'manual', message: msg })
|
||||
})
|
||||
toast.error(t('common.errors.requiredFieldsMissing', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
||||
setError(key as keyof CardPinFormData, { type: "manual", message: msg });
|
||||
});
|
||||
toast.error(t("common.errors.requiredFieldsMissing", "Käbir hökmany meýdanlar doldurylan däldir."));
|
||||
for (let i = 0; i < STEPS.length; i++) {
|
||||
if (Object.keys(STEPS[i].validate(values, mode)).length > 0) {
|
||||
setCurrentStep(i)
|
||||
break
|
||||
if (Object.keys(STEPS[i].validate(values)).length > 0) {
|
||||
setCurrentStep(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: CardPinCreatePayload = {
|
||||
status: values.status as CardPinCreatePayload['status'],
|
||||
note: values.note ?? '',
|
||||
card_type: values.card_type,
|
||||
card_number: values.card_number,
|
||||
province: values.province,
|
||||
branch: values.branch,
|
||||
first_name: values.first_name,
|
||||
last_name: values.last_name,
|
||||
father_name: values.father_name ?? '',
|
||||
birth_date: values.birth_date,
|
||||
phone: values.phone,
|
||||
passport_series: values.passport_series,
|
||||
passport_number: values.passport_number,
|
||||
passport_file_1: values.passport_file_1,
|
||||
passport_file_2: values.passport_file_2,
|
||||
passport_file_3: values.passport_file_3,
|
||||
passport_file_4: values.passport_file_4,
|
||||
}
|
||||
const payload: CreateCardPinPayload = buildPayload(values);
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, { onSuccess: (data) => navigate(`/card-pins/${data.id}`) })
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, { onSuccess: (data) => navigate(`/card-pins/${data.id}`) });
|
||||
} else {
|
||||
updateMutation.mutate(payload, { onSuccess: () => navigate('/card-pins') })
|
||||
updateMutation.mutate(payload, { onSuccess: () => navigate("/card-pins") });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── StepBar items ──────────────────────────────────────────────────────────
|
||||
|
||||
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
|
||||
const isActive = i === currentStep
|
||||
const hasErrors = stepsWithErrors.has(i)
|
||||
const isDone = visited.has(i) && !hasErrors
|
||||
const isActive = i === currentStep;
|
||||
const hasErrors = stepsWithErrors.has(i);
|
||||
const isDone = visited.has(i) && !hasErrors;
|
||||
return {
|
||||
id: s.id,
|
||||
title: t(s.titleKey) || s.titleFallback,
|
||||
id: s.id,
|
||||
title: t(s.titleKey) || s.titleFallback,
|
||||
subtitle: t(s.subtitleKey) || s.subtitleFallback,
|
||||
icon: s.icon,
|
||||
status: isActive ? 'active' : hasErrors ? 'error' : isDone ? 'done' : 'idle',
|
||||
}
|
||||
})
|
||||
icon: s.icon,
|
||||
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||
};
|
||||
});
|
||||
|
||||
const isLastStep = currentStep === STEPS.length - 1
|
||||
const isLastStep = currentStep === STEPS.length - 1;
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -518,13 +480,9 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
{/* Page header */}
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('cardPin.createTitle', 'Kart pin bukja dörediň')
|
||||
: t('cardPin.editTitle', 'Kart pin bukja redaktirläň')}
|
||||
{mode === "create" ? t("cardPin.createTitle", "Kart pin bukja dörediň") : t("cardPin.editTitle", "Kart pin bukja redaktirläň")}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{t('common.form.subtitle', 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">{t("common.form.subtitle", "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.")}</p>
|
||||
</div>
|
||||
|
||||
{/* Step bar */}
|
||||
@@ -533,46 +491,48 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
</div>
|
||||
|
||||
{/* Step content */}
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
||||
{currentStep === 2 && (
|
||||
<StepPassport {...stepProps} mode={mode} initialData={initialData} />
|
||||
)}
|
||||
{currentStep === 2 && <StepPassport {...stepProps} />}
|
||||
|
||||
{/* Actions */}
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onCancel={currentStep === 0 ? () => navigate('/card-pins') : undefined}
|
||||
onCancel={currentStep === 0 ? () => navigate("/card-pins") : undefined}
|
||||
onPrev={currentStep > 0 ? handleBack : undefined}
|
||||
prevLabel={t('common.prev', 'Yza')}
|
||||
prevLabel={t("common.prev", "Yza")}
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
nextLabel={t('common.next', 'Indiki')}
|
||||
nextLabel={t("common.next", "Indiki")}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? handleSubmit : undefined}
|
||||
submitLabel={
|
||||
mode === 'create'
|
||||
? t('cardPin.createBtn', 'Kart pin bukja dörediň')
|
||||
: t('cardPin.editBtn', 'Kart pin bukja redaktirläň')
|
||||
mode === "create" ? t("cardPin.createBtn", "Kart pin bukja dörediň") : t("cardPin.editBtn", "Kart pin bukja redaktirläň")
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function mapInitial(data: CardPinItem): Partial<CardPinFormData> {
|
||||
function mapInitial(data: CardPinOrder): Partial<CardPinFormData> {
|
||||
return {
|
||||
status: data.status ?? 'pending',
|
||||
note: data.note ?? '',
|
||||
card_type: data.card_type ?? '',
|
||||
card_number: data.card_number ?? '',
|
||||
province: data.province ?? '',
|
||||
branch: data.branch ?? '',
|
||||
first_name: data.first_name ?? '',
|
||||
last_name: data.last_name ?? '',
|
||||
father_name: data.father_name ?? '',
|
||||
birth_date: data.birth_date ?? '',
|
||||
phone: data.phone ?? '',
|
||||
passport_series: data.passport_series ?? '',
|
||||
passport_number: data.passport_number ?? '',
|
||||
}
|
||||
uniqueId: data.uniqueId ?? "",
|
||||
status: data.status ?? "",
|
||||
cardNumber: data.cardNumber ?? "",
|
||||
cardTypeId: String(data.cardTypeId ?? ""),
|
||||
region: data.region ?? "",
|
||||
branchId: String(data.branchId ?? ""),
|
||||
customerName: data.customerName ?? "",
|
||||
customerSurname: data.customerSurname ?? "",
|
||||
customerPatronicName: data.customerPatronicName ?? "",
|
||||
bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "",
|
||||
phone: data.phone ?? "",
|
||||
passportSerie: data.passportSerie ?? "",
|
||||
passportId: data.passportId ?? "",
|
||||
passportOne: data.passportOne ?? "",
|
||||
passportTwo: data.passportTwo ?? "",
|
||||
passportThree: data.passportThree ?? "",
|
||||
passportFour: data.passportFour ?? "",
|
||||
userId: String(data.userId ?? ""),
|
||||
notes: data.notes ?? "",
|
||||
};
|
||||
}
|
||||
@@ -1,77 +1,81 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { cardPinApi, type CardPinListParams, type CardPinCreatePayload, type CardPinUpdatePayload } from '../api/cardPinApi'
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import { cardPinApi, type CardPinListParams, type CreateCardPinPayload, type UpdateCardPinPayload } from "../api/cardPinApi";
|
||||
|
||||
export const CARD_PIN_KEYS = {
|
||||
all: ['card-pins'] as const,
|
||||
lists: () => [...CARD_PIN_KEYS.all, 'list'] as const,
|
||||
list: (p: CardPinListParams) => [...CARD_PIN_KEYS.lists(), p] as const,
|
||||
detail: (id: string) => [...CARD_PIN_KEYS.all, 'detail', id] as const,
|
||||
}
|
||||
all: ["card-pin-orders"] as const,
|
||||
lists: () => [...CARD_PIN_KEYS.all, "list"] as const,
|
||||
list: (p: CardPinListParams) => [...CARD_PIN_KEYS.lists(), p] as const,
|
||||
detail: (id: number) => [...CARD_PIN_KEYS.all, "detail", id] as const,
|
||||
};
|
||||
|
||||
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardPins(params: CardPinListParams) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: CardPinListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: CARD_PIN_KEYS.list(params),
|
||||
queryFn: () => cardPinApi.list(params),
|
||||
queryKey: CARD_PIN_KEYS.list(queryParams),
|
||||
queryFn: ({ signal }) => cardPinApi.list(queryParams, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Detail ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardPin(id: string) {
|
||||
export function useCardPin(id: number) {
|
||||
return useQuery({
|
||||
queryKey: CARD_PIN_KEYS.detail(id),
|
||||
queryFn: () => cardPinApi.getById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
queryFn: () => cardPinApi.getById(id),
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCardPin() {
|
||||
const qc = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const qc = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CardPinCreatePayload) => cardPinApi.create(payload),
|
||||
mutationFn: (payload: CreateCardPinPayload) => cardPinApi.create(payload),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
|
||||
toast.success(t('cardPin.createSuccess', 'Kart pin bukja döredildi'))
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() });
|
||||
toast.success(t("cardPin.createSuccess", "Kart pin bukja döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCardPin(id: string) {
|
||||
const qc = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
export function useUpdateCardPin(id: number) {
|
||||
const qc = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CardPinUpdatePayload) => cardPinApi.update(id, payload),
|
||||
mutationFn: (payload: UpdateCardPinPayload) => cardPinApi.update(id, payload),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.detail(id) })
|
||||
toast.success(t('cardPin.updateSuccess', 'Kart pin bukja üýtgedildi'))
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() });
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.detail(id) });
|
||||
toast.success(t("cardPin.updateSuccess", "Kart pin bukja üýtgedildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCardPin() {
|
||||
const qc = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const qc = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => cardPinApi.delete(id),
|
||||
mutationFn: (id: number) => cardPinApi.delete(id),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
|
||||
toast.success(t('cardPin.deleteSuccess', 'Kart pin bukja pozuldy'))
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() });
|
||||
toast.success(t("cardPin.deleteSuccess", "Kart pin bukja pozuldy"));
|
||||
},
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,89 +1,74 @@
|
||||
import { z } from "zod";
|
||||
import i18next from "i18next";
|
||||
import type { CreateCardPinPayload } from "../api/cardPinApi";
|
||||
|
||||
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 cardPinFormSchema = z.object({
|
||||
uniqueId: z.string().min(1, "validation.required"),
|
||||
status: z.string().min(1, "validation.required"),
|
||||
note: z.string().optional(),
|
||||
card_type: z.string().min(1, "validation.required"),
|
||||
card_number: z.string().min(1, "validation.required"),
|
||||
province: z.string().min(1, "validation.required"),
|
||||
branch: z.string().min(1, "validation.required"),
|
||||
first_name: z.string().min(1, "validation.required"),
|
||||
last_name: z.string().min(1, "validation.required"),
|
||||
father_name: z.string().optional(),
|
||||
birth_date: 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" },
|
||||
),
|
||||
passport_series: z.string().min(1, "validation.required"),
|
||||
passport_number: z.string().min(1, "validation.required"),
|
||||
passport_file_1: z.custom<File | null>().nullable(),
|
||||
passport_file_2: z.custom<File | null>().nullable(),
|
||||
passport_file_3: z.custom<File | null>().nullable(),
|
||||
passport_file_4: z.custom<File | null>().nullable(),
|
||||
customerName: z.string().min(1, "validation.required"),
|
||||
customerSurname: z.string().min(1, "validation.required"),
|
||||
customerPatronicName: optional(),
|
||||
bornAt: optional(),
|
||||
region: z.string().min(1, "validation.required"),
|
||||
branchId: z.string().min(1, "validation.required"),
|
||||
cardTypeId: z.string().min(1, "validation.required"),
|
||||
cardNumber: z.string().min(1, "validation.required"),
|
||||
phone: z.string().min(1, "validation.required"),
|
||||
passportSerie: z.string().min(1, "validation.required"),
|
||||
passportId: z.string().min(1, "validation.required"),
|
||||
passportOne: optional(),
|
||||
passportTwo: optional(),
|
||||
passportThree: optional(),
|
||||
passportFour: optional(),
|
||||
userId: z.string().min(1, "validation.required"),
|
||||
notes: optional(),
|
||||
});
|
||||
|
||||
export type CardPinFormData = z.infer<typeof cardPinFormSchema>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardPinFormData = {
|
||||
status: "pending",
|
||||
note: "",
|
||||
card_type: "",
|
||||
card_number: "",
|
||||
province: "",
|
||||
branch: "",
|
||||
first_name: "",
|
||||
last_name: "",
|
||||
father_name: "",
|
||||
birth_date: "",
|
||||
uniqueId: "",
|
||||
status: "",
|
||||
customerName: "",
|
||||
customerSurname: "",
|
||||
customerPatronicName: "",
|
||||
bornAt: "",
|
||||
region: "",
|
||||
branchId: "",
|
||||
cardTypeId: "",
|
||||
cardNumber: "",
|
||||
phone: "",
|
||||
passport_series: "",
|
||||
passport_number: "",
|
||||
passport_file_1: null,
|
||||
passport_file_2: null,
|
||||
passport_file_3: null,
|
||||
passport_file_4: null,
|
||||
passportSerie: "",
|
||||
passportId: "",
|
||||
passportOne: "",
|
||||
passportTwo: "",
|
||||
passportThree: "",
|
||||
passportFour: "",
|
||||
userId: "",
|
||||
notes: "",
|
||||
};
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<CardPinFormData>>> = {
|
||||
0: cardPinFormSchema.pick({
|
||||
uniqueId: true,
|
||||
status: true,
|
||||
card_type: true,
|
||||
card_number: true,
|
||||
province: true,
|
||||
branch: true,
|
||||
cardNumber: true,
|
||||
cardTypeId: true,
|
||||
region: true,
|
||||
branchId: true,
|
||||
}),
|
||||
1: cardPinFormSchema.pick({
|
||||
first_name: true,
|
||||
last_name: true,
|
||||
birth_date: true,
|
||||
customerName: true,
|
||||
customerSurname: true,
|
||||
bornAt: true,
|
||||
phone: true,
|
||||
userId: true,
|
||||
}),
|
||||
2: z.object({
|
||||
passport_series: z.string().min(1, "validation.required"),
|
||||
passport_number: z.string().min(1, "validation.required"),
|
||||
passport_file_1: fileRequired,
|
||||
passport_file_2: fileRequired,
|
||||
passport_file_3: fileRequired,
|
||||
passport_file_4: fileRequired,
|
||||
2: cardPinFormSchema.pick({
|
||||
passportSerie: true,
|
||||
passportId: true,
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -91,23 +76,7 @@ function translateMsg(msg: string): string {
|
||||
return msg.startsWith("validation.") ? i18next.t(msg, msg) : msg;
|
||||
}
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: CardPinFormData,
|
||||
mode: "create" | "edit",
|
||||
): Partial<Record<keyof CardPinFormData, string>> {
|
||||
if (stepIndex === 2 && mode === "edit") {
|
||||
const schema = cardPinFormSchema.pick({ passport_series: true, passport_number: true });
|
||||
const result = schema.safeParse(form);
|
||||
if (result.success) return {};
|
||||
const errors: Partial<Record<keyof CardPinFormData, string>> = {};
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof CardPinFormData;
|
||||
if (!errors[key]) errors[key] = translateMsg(issue.message);
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
export function validateStep(stepIndex: number, form: CardPinFormData): Partial<Record<keyof CardPinFormData, string>> {
|
||||
const schema = stepSchemas[stepIndex];
|
||||
const result = schema.safeParse(form);
|
||||
if (result.success) return {};
|
||||
@@ -119,3 +88,27 @@ export function validateStep(
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
export function buildPayload(data: CardPinFormData): CreateCardPinPayload {
|
||||
return {
|
||||
uniqueId: data.uniqueId.trim(),
|
||||
status: data.status.trim(),
|
||||
customerName: data.customerName.trim(),
|
||||
customerSurname: data.customerSurname.trim(),
|
||||
customerPatronicName: data.customerPatronicName.trim(),
|
||||
bornAt: data.bornAt.trim(),
|
||||
region: data.region.trim(),
|
||||
branchId: Number(data.branchId),
|
||||
cardTypeId: Number(data.cardTypeId),
|
||||
cardNumber: data.cardNumber.trim(),
|
||||
phone: data.phone.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(),
|
||||
userId: Number(data.userId),
|
||||
notes: data.notes.trim(),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user