connected api with card balance and and requisites
This commit is contained in:
@@ -1,104 +1,96 @@
|
||||
import apiClient from '@/lib/api/client'
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type CardBalanceStatus = "pending" | "approved" | "rejected";
|
||||
|
||||
export interface CardBalanceUser {
|
||||
id: number;
|
||||
name: string;
|
||||
username: string;
|
||||
phone: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
/** Raw backend entity (GET responses mirror this shape). */
|
||||
export interface CardBalance {
|
||||
id: number
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
card_number: string
|
||||
card_expiry_month: string
|
||||
card_expiry_year: string
|
||||
id: number;
|
||||
passportNumber: string;
|
||||
cardLast4: string;
|
||||
expiryMonth: number;
|
||||
expiryYear: number;
|
||||
expiryAt: string;
|
||||
balanceAmount: number;
|
||||
balanceCurrency: string;
|
||||
status: string;
|
||||
checkedAt: string;
|
||||
createdBy: CardBalanceUser;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** LIST RESPONSE: GET /card-balances */
|
||||
export interface CardBalanceListResponse {
|
||||
data: CardBalance[]
|
||||
total: number
|
||||
page: number
|
||||
per_page: number
|
||||
count: number;
|
||||
cardBalances: CardBalance[];
|
||||
}
|
||||
|
||||
export interface CreateCardBalancePayload {
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
card_number: string
|
||||
card_expiry_month: string
|
||||
card_expiry_year: string
|
||||
}
|
||||
|
||||
export type UpdateCardBalancePayload = CreateCardBalancePayload
|
||||
|
||||
/** LIST PARAMS */
|
||||
export interface CardBalanceListParams {
|
||||
page?: number
|
||||
per_page?: number
|
||||
search?: string
|
||||
page?: number;
|
||||
limit?: number;
|
||||
status?: string;
|
||||
passport_number?: string;
|
||||
created_by?: number | string;
|
||||
}
|
||||
|
||||
// ─── API ─────────────────────────────────────────────────────────────────────
|
||||
/** CREATE / UPDATE PAYLOAD (camelCase, JSON) */
|
||||
export interface CardBalancePayload {
|
||||
balanceAmount: number;
|
||||
balanceCurrency: string;
|
||||
cardNumber: string;
|
||||
checkedAt: string;
|
||||
createdBy: number;
|
||||
expiryMonth: number;
|
||||
expiryYear: number;
|
||||
passportNumber: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
const MOCK_CARD_BALANCES: CardBalance[] = [
|
||||
{
|
||||
id: 1,
|
||||
passport_series: 'AA',
|
||||
passport_number: '1112223',
|
||||
card_number: '8600123412341234',
|
||||
card_expiry_month: '10',
|
||||
card_expiry_year: '2028',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
passport_series: 'I-MR',
|
||||
passport_number: '9988776',
|
||||
card_number: '9860123456789012',
|
||||
card_expiry_month: '05',
|
||||
card_expiry_year: '2027',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
passport_series: 'II-LB',
|
||||
passport_number: '4455667',
|
||||
card_number: '4400556677889900',
|
||||
card_expiry_month: '12',
|
||||
card_expiry_year: '2026',
|
||||
},
|
||||
]
|
||||
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||
|
||||
export const cardBalancesApi = {
|
||||
getAll: async (params?: CardBalanceListParams): Promise<CardBalanceListResponse> => {
|
||||
// Mock data kullanmak için:
|
||||
return { data: MOCK_CARD_BALANCES, total: MOCK_CARD_BALANCES.length, page: params?.page || 1, per_page: params?.per_page || 25 }
|
||||
|
||||
const { data } = await apiClient.get('/card-balances', { params })
|
||||
return data
|
||||
getList: async (params: CardBalanceListParams = {}, signal?: AbortSignal): Promise<CardBalanceListResponse> => {
|
||||
const { page, limit, status, passport_number, created_by } = params;
|
||||
const { data } = await apiClient.get<CardBalanceListResponse>("/card-balances", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
status: status || undefined,
|
||||
passport_number: passport_number || undefined,
|
||||
created_by: created_by || undefined,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
getById: async (id: number): Promise<CardBalance> => {
|
||||
// Mock data kullanmak için:
|
||||
const mock = MOCK_CARD_BALANCES.find(b => b.id === id)
|
||||
if (mock) return mock
|
||||
|
||||
const { data } = await apiClient.get(`/card-balances/${id}`)
|
||||
return data
|
||||
const { data } = await apiClient.get<CardBalance>(`/card-balances/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
create: async (payload: CreateCardBalancePayload): Promise<CardBalance> => {
|
||||
const { data } = await apiClient.post('/card-balances', payload)
|
||||
return data
|
||||
create: async (payload: CardBalancePayload): Promise<CardBalance> => {
|
||||
const { data } = await apiClient.post<CardBalance>("/card-balances", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
update: async (id: number, payload: UpdateCardBalancePayload): Promise<CardBalance> => {
|
||||
const { data } = await apiClient.put(`/card-balances/${id}`, payload)
|
||||
return data
|
||||
update: async (id: number, payload: CardBalancePayload): Promise<CardBalance> => {
|
||||
const { data } = await apiClient.put<CardBalance>(`/card-balances/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await apiClient.delete(`/card-balances/${id}`)
|
||||
await apiClient.delete(`/card-balances/${id}`);
|
||||
},
|
||||
|
||||
download: async (id: number): Promise<Blob> => {
|
||||
const { data } = await apiClient.get(`/card-balances/${id}/download`, {
|
||||
responseType: 'blob',
|
||||
})
|
||||
return data
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useState, useCallback, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormInput, type SelectOption } from "@/components/formInput";
|
||||
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { type CardBalance } from "@/features/cardBalance/api/cardBalanceApi";
|
||||
import { useCreateCardBalance, useUpdateCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
||||
import { cardBalanceFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "@/features/cardBalance/schemas/cardBalance.schema";
|
||||
import { cardBalanceFormSchema, DEFAULT_FORM_VALUES, mapInitial, buildPayload } from "@/features/cardBalance/schemas/cardBalance.schema";
|
||||
import type { CardBalanceFormData } from "@/features/cardBalance/schemas/cardBalance.schema";
|
||||
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||
|
||||
interface CardBalanceFormProps {
|
||||
mode: "create" | "edit";
|
||||
@@ -27,28 +29,25 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const PASSPORT_SERIES_OPTIONS = [
|
||||
{ value: "I-MR", label: "I-MR" },
|
||||
{ value: "II-MR", label: "II-MR" },
|
||||
{ value: "I-LB", label: "I-LB" },
|
||||
{ value: "II-LB", label: "II-LB" },
|
||||
{ value: "III-LB", label: "III-LB" },
|
||||
{ value: "I-BN", label: "I-BN" },
|
||||
{ value: "II-BN", label: "II-BN" },
|
||||
{ value: "I-AH", label: "I-AH" },
|
||||
{ value: "I-AS", label: "I-AS" },
|
||||
{ value: "I-DZ", label: "I-DZ" },
|
||||
{ value: "II-DZ", label: "II-DZ" },
|
||||
{ value: "A", label: "A" },
|
||||
{ value: "B", label: "B" },
|
||||
const STATUS_OPTIONS: SelectOption[] = [
|
||||
{ value: "pending", label: "Garaşylýar" },
|
||||
{ value: "approved", label: "Tassyklanan" },
|
||||
{ value: "rejected", label: "Ret edilen" },
|
||||
];
|
||||
|
||||
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
|
||||
const CURRENCY_OPTIONS: SelectOption[] = [
|
||||
{ value: "TMT", label: "TMT" },
|
||||
{ value: "USD", label: "USD" },
|
||||
{ value: "RUB", label: "RUB" },
|
||||
{ value: "EUR", label: "EUR" },
|
||||
];
|
||||
|
||||
const MONTH_OPTIONS: SelectOption[] = Array.from({ length: 12 }, (_, i) => {
|
||||
const val = String(i + 1).padStart(2, "0");
|
||||
return { value: val, label: val };
|
||||
});
|
||||
|
||||
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
|
||||
const YEAR_OPTIONS: SelectOption[] = Array.from({ length: 20 }, (_, i) => {
|
||||
const year = String(new Date().getFullYear() + i);
|
||||
return { value: year, label: year };
|
||||
});
|
||||
@@ -63,6 +62,22 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
|
||||
const updateMutation = useUpdateCardBalance(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const userQuery = useInfiniteUsers(userSearch);
|
||||
|
||||
const userOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (userQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.users ?? [])
|
||||
.map((u) => ({ value: String(u.id), label: u.name || u.username || String(u.id) }));
|
||||
if (initialData?.createdBy?.id && !opts.some((o) => o.value === String(initialData.createdBy.id))) {
|
||||
opts.unshift({
|
||||
value: String(initialData.createdBy.id),
|
||||
label: initialData.createdBy.name || String(initialData.createdBy.id),
|
||||
});
|
||||
}
|
||||
return opts;
|
||||
}, [userQuery, initialData]);
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
@@ -71,20 +86,22 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<CardBalanceFormData>({
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...initialData } : DEFAULT_FORM_VALUES,
|
||||
defaultValues: initialData ? mapInitial(initialData) : DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const setField = useCallback(
|
||||
(field: keyof CardBalanceFormData) => (value: string) => {
|
||||
(setValue as (name: keyof CardBalanceFormData, val: string) => void)(field, value);
|
||||
clearErrors(field);
|
||||
const set = useCallback(
|
||||
<K extends keyof CardBalanceFormData>(key: K, value: CardBalanceFormData[K]) => {
|
||||
(setValue as (name: K, val: CardBalanceFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const setString = (key: keyof CardBalanceFormData) => (value: string) => set(key, value as CardBalanceFormData[typeof key]);
|
||||
|
||||
const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
@@ -120,60 +137,101 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
|
||||
</h1>
|
||||
<div className="rounded-lg border border-border bg-card p-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{/* Row 1 */}
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("Passport series", "Pasport seriýasy")}
|
||||
value={form.passport_series}
|
||||
onChange={setField("passport_series")}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.passport_series)}
|
||||
type="select"
|
||||
label={t("Status", "Status")}
|
||||
value={form.status}
|
||||
onChange={setString("status")}
|
||||
options={STATUS_OPTIONS}
|
||||
placeholder={t("Select", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.status)}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Passport number", "Pasport belgisi")}
|
||||
value={form.passport_number}
|
||||
onChange={setField("passport_number")}
|
||||
value={form.passportNumber}
|
||||
onChange={setString("passportNumber")}
|
||||
placeholder={t("Passport number", "Pasport belgisi")}
|
||||
error={errMsg(errors.passport_number)}
|
||||
error={errMsg(errors.passportNumber)}
|
||||
required
|
||||
/>
|
||||
|
||||
{/* Row 2 — card number full width + 2 selects */}
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Card number", "Kart belgisi")}
|
||||
value={form.card_number}
|
||||
onChange={setField("card_number")}
|
||||
placeholder={t("Card number", "Kart belgisi")}
|
||||
error={errMsg(errors.card_number)}
|
||||
value={form.cardNumber}
|
||||
onChange={setString("cardNumber")}
|
||||
placeholder="9800 0000 0000 0000"
|
||||
error={errMsg(errors.cardNumber)}
|
||||
required
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Card expiry month", "Kart Möhleti (aý)")}
|
||||
value={form.card_expiry_month}
|
||||
onChange={setField("card_expiry_month")}
|
||||
value={form.expiryMonth}
|
||||
onChange={setString("expiryMonth")}
|
||||
options={MONTH_OPTIONS}
|
||||
placeholder={t("Select", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.card_expiry_month)}
|
||||
error={errMsg(errors.expiryMonth)}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Card expiry year", "Kart Möhleti (ýyl)")}
|
||||
value={form.card_expiry_year}
|
||||
onChange={setField("card_expiry_year")}
|
||||
value={form.expiryYear}
|
||||
onChange={setString("expiryYear")}
|
||||
options={YEAR_OPTIONS}
|
||||
placeholder={t("Select", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.card_expiry_year)}
|
||||
error={errMsg(errors.expiryYear)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("Balance amount", "Galyndy möçberi")}
|
||||
value={form.balanceAmount}
|
||||
onChange={setString("balanceAmount")}
|
||||
placeholder="0.00"
|
||||
error={errMsg(errors.balanceAmount)}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("Balance currency", "Galyndy walýutasy")}
|
||||
value={form.balanceCurrency}
|
||||
onChange={setString("balanceCurrency")}
|
||||
options={CURRENCY_OPTIONS}
|
||||
placeholder={t("Select", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.balanceCurrency)}
|
||||
required
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("Checked at", "Barlan senesi")}
|
||||
value={form.checkedAt}
|
||||
onChange={setString("checkedAt")}
|
||||
error={errMsg(errors.checkedAt)}
|
||||
required
|
||||
/>
|
||||
<InfiniteSelect
|
||||
label={t("Created by", "Döreden")}
|
||||
value={form.createdBy}
|
||||
onChange={(v) => set("createdBy", v)}
|
||||
options={userOptions}
|
||||
placeholder={t("Select user", "Ulanyjyny saýlaň")}
|
||||
loading={userQuery.isLoading}
|
||||
isLoadingMore={userQuery.isFetchingNextPage}
|
||||
hasNextPage={!!userQuery.hasNextPage}
|
||||
onLoadMore={() => userQuery.fetchNextPage()}
|
||||
searchValue={userSearch}
|
||||
onSearchChange={setUserSearch}
|
||||
error={errMsg(errors.createdBy)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormActions
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import type { CardBalanceStatus } from "../api/cardBalanceApi";
|
||||
|
||||
const STATUS_CONFIG: Record<
|
||||
CardBalanceStatus,
|
||||
{ labelKey: string; fallback: string; variant: StatusBadgeVariant; icon: React.ElementType }
|
||||
> = {
|
||||
pending: { labelKey: "cardBalance.status.pending", fallback: "Garaşylýar", variant: "warning", icon: AlertCircle },
|
||||
approved: { labelKey: "cardBalance.status.approved", fallback: "Tassyklanan", variant: "success", icon: CheckCircle2 },
|
||||
rejected: { labelKey: "cardBalance.status.rejected", fallback: "Ret edilen", variant: "error", icon: XCircle },
|
||||
};
|
||||
|
||||
export function CardBalanceStatusBadge({ status }: { status: string }) {
|
||||
const { t } = useTranslation();
|
||||
const cfg = STATUS_CONFIG[status as CardBalanceStatus];
|
||||
if (!cfg) return <span className="text-xs text-muted-foreground">{status}</span>;
|
||||
return <StatusBadge label={t(cfg.labelKey, cfg.fallback)} variant={cfg.variant} icon={cfg.icon} />;
|
||||
}
|
||||
@@ -1,84 +1,80 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
cardBalancesApi,
|
||||
type CardBalanceListParams,
|
||||
type CreateCardBalancePayload,
|
||||
type UpdateCardBalancePayload,
|
||||
} from '../api/cardBalanceApi'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { cardBalancesApi, type CardBalanceListParams, type CardBalancePayload } from "../api/cardBalanceApi";
|
||||
|
||||
const QUERY_KEY = 'card-balances'
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardBalances(params?: CardBalanceListParams) {
|
||||
export const cardBalanceKeys = {
|
||||
all: ["cardBalances"] as const,
|
||||
lists: () => [...cardBalanceKeys.all, "list"] as const,
|
||||
list: (params: CardBalanceListParams) => [...cardBalanceKeys.lists(), params] as const,
|
||||
details: () => [...cardBalanceKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...cardBalanceKeys.details(), id] as const,
|
||||
};
|
||||
|
||||
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardBalances(params: CardBalanceListParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: [QUERY_KEY, params],
|
||||
queryFn: () => cardBalancesApi.getAll(params),
|
||||
})
|
||||
queryKey: cardBalanceKeys.list(params),
|
||||
queryFn: ({ signal }) => cardBalancesApi.getList(params, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Single ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardBalance(id: number) {
|
||||
return useQuery({
|
||||
queryKey: [QUERY_KEY, id],
|
||||
queryKey: cardBalanceKeys.detail(id),
|
||||
queryFn: () => cardBalancesApi.getById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCardBalance() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateCardBalancePayload) => cardBalancesApi.create(payload),
|
||||
mutationFn: (payload: CardBalancePayload) => cardBalancesApi.create(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
||||
toast.success(t('Card balance created successfully', 'Kart galyndysy üstünlikli döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: cardBalanceKeys.lists() });
|
||||
toast.success(t("cardBalance.createSuccess", "Kart galyndysy üstünlikli döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCardBalance(id: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateCardBalancePayload) => cardBalancesApi.update(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
||||
toast.success(t('Card balance updated successfully', 'Kart galyndysy üstünlikli üýtgedildi'))
|
||||
mutationFn: (payload: CardBalancePayload) => cardBalancesApi.update(id, payload),
|
||||
onSuccess: (updated) => {
|
||||
queryClient.invalidateQueries({ queryKey: cardBalanceKeys.lists() });
|
||||
queryClient.setQueryData(cardBalanceKeys.detail(id), updated);
|
||||
toast.success(t("cardBalance.updateSuccess", "Kart galyndysy üstünlikli üýtgedildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCardBalance() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => cardBalancesApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
||||
toast.success(t('Card balance deleted successfully', 'Kart galyndysy üstünlikli öçürildi'))
|
||||
queryClient.invalidateQueries({ queryKey: cardBalanceKeys.lists() });
|
||||
toast.success(t("cardBalance.deleteSuccess", "Kart galyndysy üstünlikli öçürildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadCardBalance() {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (id: number) => {
|
||||
const blob = await cardBalancesApi.download(id)
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `card-balance-${id}.pdf`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi'))
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,30 +1,56 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateCardBalancePayload } from '../api/cardBalanceApi'
|
||||
import { z } from "zod";
|
||||
import type { CardBalance, CardBalancePayload } from "../api/cardBalanceApi";
|
||||
|
||||
export const cardBalanceFormSchema = z.object({
|
||||
passport_series: z.string().min(1, 'validation.required'),
|
||||
passport_number: z.string().min(1, 'validation.required'),
|
||||
card_number: z.string().min(1, 'validation.required'),
|
||||
card_expiry_month: z.string().min(1, 'validation.required'),
|
||||
card_expiry_year: z.string().min(1, 'validation.required'),
|
||||
})
|
||||
status: z.string().min(1, "validation.required"),
|
||||
passportNumber: z.string().min(1, "validation.required"),
|
||||
cardNumber: z.string().min(1, "validation.required"),
|
||||
expiryMonth: z.string().min(1, "validation.required"),
|
||||
expiryYear: z.string().min(1, "validation.required"),
|
||||
balanceAmount: z.string().min(1, "validation.required"),
|
||||
balanceCurrency: z.string().min(1, "validation.required"),
|
||||
checkedAt: z.string().min(1, "validation.required"),
|
||||
createdBy: z.string().min(1, "validation.required"),
|
||||
});
|
||||
|
||||
export type CardBalanceFormData = z.infer<typeof cardBalanceFormSchema>
|
||||
export type CardBalanceFormData = z.infer<typeof cardBalanceFormSchema>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardBalanceFormData = {
|
||||
passport_series: '',
|
||||
passport_number: '',
|
||||
card_number: '',
|
||||
card_expiry_month: '',
|
||||
card_expiry_year: '',
|
||||
status: "",
|
||||
passportNumber: "",
|
||||
cardNumber: "",
|
||||
expiryMonth: "",
|
||||
expiryYear: "",
|
||||
balanceAmount: "",
|
||||
balanceCurrency: "",
|
||||
checkedAt: "",
|
||||
createdBy: "",
|
||||
};
|
||||
|
||||
export function mapInitial(data: CardBalance): CardBalanceFormData {
|
||||
return {
|
||||
status: data.status ?? "",
|
||||
passportNumber: data.passportNumber ?? "",
|
||||
cardNumber: "",
|
||||
expiryMonth: data.expiryMonth != null ? String(data.expiryMonth) : "",
|
||||
expiryYear: data.expiryYear != null ? String(data.expiryYear) : "",
|
||||
balanceAmount: data.balanceAmount != null ? String(data.balanceAmount) : "",
|
||||
balanceCurrency: data.balanceCurrency ?? "",
|
||||
checkedAt: data.checkedAt ? data.checkedAt.slice(0, 10) : "",
|
||||
createdBy: data.createdBy?.id != null ? String(data.createdBy.id) : "",
|
||||
};
|
||||
}
|
||||
|
||||
export function buildPayload(data: CardBalanceFormData): CreateCardBalancePayload {
|
||||
export function buildPayload(data: CardBalanceFormData): CardBalancePayload {
|
||||
return {
|
||||
passport_series: data.passport_series,
|
||||
passport_number: data.passport_number,
|
||||
card_number: data.card_number,
|
||||
card_expiry_month: data.card_expiry_month,
|
||||
card_expiry_year: data.card_expiry_year,
|
||||
}
|
||||
status: data.status,
|
||||
passportNumber: data.passportNumber,
|
||||
cardNumber: data.cardNumber,
|
||||
expiryMonth: Number(data.expiryMonth),
|
||||
expiryYear: Number(data.expiryYear),
|
||||
balanceAmount: Number(data.balanceAmount),
|
||||
balanceCurrency: data.balanceCurrency,
|
||||
checkedAt: new Date(data.checkedAt).toISOString(),
|
||||
createdBy: Number(data.createdBy),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,259 +1,146 @@
|
||||
import apiClient from '@/lib/api/client'
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type CardRequisiteStatus = 'pending' | 'approved' | 'rejected'
|
||||
export interface LocalizedText {
|
||||
tm: string;
|
||||
ru: string;
|
||||
en: string;
|
||||
}
|
||||
|
||||
export function resolveLocalizedName(name: LocalizedText | string | null | undefined, lang = "en"): string {
|
||||
if (!name) return "";
|
||||
if (typeof name === "string") return name;
|
||||
return name[lang as keyof LocalizedText] ?? name.tm ?? name.en ?? name.ru ?? "";
|
||||
}
|
||||
|
||||
export type CardRequisiteStatus = "pending" | "approved" | "rejected";
|
||||
|
||||
export interface CardRequisiteUser {
|
||||
id: number;
|
||||
name: string;
|
||||
username: string;
|
||||
phone: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface CardRequisiteCardType {
|
||||
id: number;
|
||||
name: LocalizedText;
|
||||
}
|
||||
|
||||
export interface CardRequisiteBranch {
|
||||
id: number;
|
||||
name: LocalizedText;
|
||||
}
|
||||
|
||||
/** Raw backend entity (GET responses mirror this shape). */
|
||||
export interface CardRequisite {
|
||||
id: string
|
||||
status: CardRequisiteStatus
|
||||
note: string
|
||||
created_at: string
|
||||
|
||||
// Card
|
||||
card_type: string
|
||||
card_number: string
|
||||
card_expiry_month: string
|
||||
card_expiry_year: string
|
||||
|
||||
// Location
|
||||
province_id: string
|
||||
branch_id: string
|
||||
province_name?: string
|
||||
branch_name?: string
|
||||
|
||||
// Personal
|
||||
first_name: string
|
||||
last_name: string
|
||||
middle_name?: string
|
||||
birth_date: string
|
||||
phone: string
|
||||
|
||||
// Passport
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
passport_page1_url?: string
|
||||
passport_page2_3_url?: string
|
||||
passport_page8_9_url?: string
|
||||
passport_page32_url?: string
|
||||
id: number;
|
||||
uniqueId: string;
|
||||
user: CardRequisiteUser;
|
||||
cardType: CardRequisiteCardType;
|
||||
cardNumber: string;
|
||||
cardMonth: string;
|
||||
cardYear: string;
|
||||
region: string;
|
||||
branch: CardRequisiteBranch;
|
||||
customerName: string;
|
||||
customerSurname: string;
|
||||
customerPatronicName: string;
|
||||
bornAt: string;
|
||||
phone: string;
|
||||
passportSerie: string;
|
||||
passportId: string;
|
||||
passportOne: string;
|
||||
passportTwo: string;
|
||||
passportThree: string;
|
||||
passportFour: string;
|
||||
status: string;
|
||||
notes: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** LIST RESPONSE: GET /card-rekwizit-orders */
|
||||
export interface CardRequisiteListResponse {
|
||||
data: CardRequisite[]
|
||||
total: number
|
||||
page: number
|
||||
per_page: number
|
||||
count: number;
|
||||
cardRekwizitOrders: CardRequisite[];
|
||||
}
|
||||
|
||||
export interface CreateCardRequisitePayload {
|
||||
status: CardRequisiteStatus
|
||||
note?: string
|
||||
card_type: string
|
||||
card_number: string
|
||||
card_expiry_month: string
|
||||
card_expiry_year: string
|
||||
province_id: string
|
||||
branch_id: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
middle_name?: string
|
||||
birth_date: string
|
||||
phone: string
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
passport_page1?: File
|
||||
passport_page2_3?: File
|
||||
passport_page8_9?: File
|
||||
passport_page32?: File
|
||||
}
|
||||
|
||||
export type UpdateCardRequisitePayload = CreateCardRequisitePayload
|
||||
|
||||
/** LIST PARAMS */
|
||||
export interface CardRequisiteListParams {
|
||||
page?: number
|
||||
per_page?: number
|
||||
search?: string
|
||||
page?: number;
|
||||
limit?: number;
|
||||
status?: string;
|
||||
branch_id?: number | string;
|
||||
user_id?: number | string;
|
||||
card_type_id?: number | string;
|
||||
region?: string;
|
||||
search?: string;
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function buildFormData(payload: CreateCardRequisitePayload): FormData {
|
||||
const fd = new FormData()
|
||||
|
||||
const textFields: (keyof Omit<
|
||||
CreateCardRequisitePayload,
|
||||
'passport_page1' | 'passport_page2_3' | 'passport_page8_9' | 'passport_page32'
|
||||
>)[] = [
|
||||
'status', 'note', 'card_type', 'card_number', 'card_expiry_month',
|
||||
'card_expiry_year', 'province_id', 'branch_id', 'first_name', 'last_name',
|
||||
'middle_name', 'birth_date', 'phone', 'passport_series', 'passport_number',
|
||||
]
|
||||
|
||||
textFields.forEach((key) => {
|
||||
const val = payload[key]
|
||||
if (val !== undefined && val !== null) fd.append(key, val)
|
||||
})
|
||||
|
||||
if (payload.passport_page1) fd.append('passport_page1', payload.passport_page1)
|
||||
if (payload.passport_page2_3) fd.append('passport_page2_3', payload.passport_page2_3)
|
||||
if (payload.passport_page8_9) fd.append('passport_page8_9', payload.passport_page8_9)
|
||||
if (payload.passport_page32) fd.append('passport_page32', payload.passport_page32)
|
||||
|
||||
return fd
|
||||
/** CREATE / UPDATE PAYLOAD (camelCase, JSON) */
|
||||
export interface CardRequisitePayload {
|
||||
bornAt: string;
|
||||
branchId: number;
|
||||
cardMonth: string;
|
||||
cardNumber: string;
|
||||
cardTypeId: number;
|
||||
cardYear: string;
|
||||
customerName: string;
|
||||
customerPatronicName: string;
|
||||
customerSurname: string;
|
||||
notes: string;
|
||||
passportFour: string;
|
||||
passportId: string;
|
||||
passportOne: string;
|
||||
passportSerie: string;
|
||||
passportThree: string;
|
||||
passportTwo: string;
|
||||
phone: string;
|
||||
region: string;
|
||||
status: string;
|
||||
uniqueId: string;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
// ─── Mock data ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_CARD_REQUISITES: CardRequisite[] = [
|
||||
{
|
||||
id: '1',
|
||||
status: 'pending',
|
||||
note: '',
|
||||
card_type: 'UZCARD',
|
||||
card_number: '8600123456789012',
|
||||
card_expiry_month: '12',
|
||||
card_expiry_year: '28',
|
||||
province_id: '1',
|
||||
branch_id: '1',
|
||||
province_name: 'Toshkent',
|
||||
branch_name: 'Filial 1',
|
||||
first_name: 'Ali',
|
||||
last_name: 'Valiyev',
|
||||
middle_name: 'Akbarovich',
|
||||
birth_date: '1990-05-15',
|
||||
phone: '+998901234567',
|
||||
passport_series: 'AA',
|
||||
passport_number: '1234567',
|
||||
created_at: '2025-01-15T10:30:00Z',
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
status: 'approved',
|
||||
note: 'Approved',
|
||||
card_type: 'HUMO',
|
||||
card_number: '9860123456789012',
|
||||
card_expiry_month: '05',
|
||||
card_expiry_year: '27',
|
||||
province_id: '2',
|
||||
branch_id: '3',
|
||||
province_name: 'Samarqand',
|
||||
branch_name: 'Filial 3',
|
||||
first_name: 'Bobur',
|
||||
last_name: 'Karimov',
|
||||
middle_name: 'Rustamovich',
|
||||
birth_date: '1985-08-22',
|
||||
phone: '+998907654321',
|
||||
passport_series: 'AB',
|
||||
passport_number: '7654321',
|
||||
created_at: '2025-02-20T14:00:00Z',
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
status: 'rejected',
|
||||
note: 'Hujjatlar not\'g\'ri',
|
||||
card_type: 'VISA',
|
||||
card_number: '4400123456789012',
|
||||
card_expiry_month: '08',
|
||||
card_expiry_year: '26',
|
||||
province_id: '3',
|
||||
branch_id: '5',
|
||||
province_name: 'Buxoro',
|
||||
branch_name: 'Filial 5',
|
||||
first_name: 'Dilorom',
|
||||
last_name: 'Rahimova',
|
||||
middle_name: 'Shavkatovna',
|
||||
birth_date: '1995-11-02',
|
||||
phone: '+998903334455',
|
||||
passport_series: 'AC',
|
||||
passport_number: '1122334',
|
||||
created_at: '2025-03-10T09:15:00Z',
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
status: 'pending',
|
||||
note: '',
|
||||
card_type: 'UZCARD',
|
||||
card_number: '5300123456789012',
|
||||
card_expiry_month: '01',
|
||||
card_expiry_year: '30',
|
||||
province_id: '4',
|
||||
branch_id: '7',
|
||||
province_name: 'Farg\'ona',
|
||||
branch_name: 'Filial 7',
|
||||
first_name: 'Elyor',
|
||||
last_name: 'Toshmatov',
|
||||
middle_name: 'Olimovich',
|
||||
birth_date: '2000-03-18',
|
||||
phone: '+998905556677',
|
||||
passport_series: 'KA',
|
||||
passport_number: '9988776',
|
||||
created_at: '2025-04-05T16:45:00Z',
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
status: 'approved',
|
||||
note: 'Tasdiqlangan',
|
||||
card_type: 'HUMO',
|
||||
card_number: '6200123456789012',
|
||||
card_expiry_month: '03',
|
||||
card_expiry_year: '29',
|
||||
province_id: '5',
|
||||
branch_id: '9',
|
||||
province_name: 'Namangan',
|
||||
branch_name: 'Filial 9',
|
||||
first_name: 'Gulnora',
|
||||
last_name: 'Abdullayeva',
|
||||
middle_name: 'Anvarovna',
|
||||
birth_date: '1992-07-30',
|
||||
phone: '+998908889900',
|
||||
passport_series: 'KB',
|
||||
passport_number: '5566778',
|
||||
created_at: '2025-05-12T11:30:00Z',
|
||||
},
|
||||
]
|
||||
|
||||
// ─── API functions ────────────────────────────────────────────────────────────
|
||||
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||
|
||||
export const cardRequisitesApi = {
|
||||
getAll: async (params?: CardRequisiteListParams): Promise<CardRequisiteListResponse> => {
|
||||
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz:
|
||||
return { data: MOCK_CARD_REQUISITES, total: MOCK_CARD_REQUISITES.length, page: params?.page || 1, per_page: params?.per_page || 10 }
|
||||
|
||||
const { data } = await apiClient.get('/card-requisites', { params })
|
||||
return data
|
||||
getList: async (params: CardRequisiteListParams = {}, signal?: AbortSignal): Promise<CardRequisiteListResponse> => {
|
||||
const { page, limit, status, branch_id, user_id, card_type_id, region } = params;
|
||||
const { data } = await apiClient.get<CardRequisiteListResponse>("/card-rekwizit-orders", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
status: status || undefined,
|
||||
branch_id: branch_id || undefined,
|
||||
user_id: user_id || undefined,
|
||||
card_type_id: card_type_id || undefined,
|
||||
region: region || undefined,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
getById: async (id: string): Promise<CardRequisite> => {
|
||||
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz:
|
||||
const mock = MOCK_CARD_REQUISITES.find(r => r.id === id)
|
||||
if (mock) return mock
|
||||
|
||||
const { data } = await apiClient.get(`/card-requisites/${id}`)
|
||||
return data
|
||||
getById: async (id: number): Promise<CardRequisite> => {
|
||||
const { data } = await apiClient.get<CardRequisite>(`/card-rekwizit-orders/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
create: async (payload: CreateCardRequisitePayload): Promise<CardRequisite> => {
|
||||
const { data } = await apiClient.post('/card-requisites', buildFormData(payload), {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})
|
||||
return data
|
||||
create: async (payload: CardRequisitePayload): Promise<CardRequisite> => {
|
||||
const { data } = await apiClient.post<CardRequisite>("/card-rekwizit-orders", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
update: async (id: string, payload: UpdateCardRequisitePayload): Promise<CardRequisite> => {
|
||||
const { data } = await apiClient.post(`/card-requisites/${id}`, buildFormData(payload), {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})
|
||||
return data
|
||||
update: async (id: number, payload: CardRequisitePayload): Promise<CardRequisite> => {
|
||||
const { data } = await apiClient.put<CardRequisite>(`/card-rekwizit-orders/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
delete: async (id: string): Promise<void> => {
|
||||
await apiClient.delete(`/card-requisites/${id}`)
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await apiClient.delete(`/card-rekwizit-orders/${id}`);
|
||||
},
|
||||
|
||||
download: async (id: string): Promise<Blob> => {
|
||||
const { data } = await apiClient.get(`/card-requisites/${id}/download`, {
|
||||
responseType: 'blob',
|
||||
})
|
||||
return data
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
@@ -7,7 +7,9 @@ import { toast } from "sonner";
|
||||
import { CreditCard, User, FileText } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormInput, type SelectOption } from "@/components/formInput";
|
||||
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||
import { DocumentUpload } from "@/components/documentUpload";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
@@ -15,6 +17,10 @@ import type { CardRequisite } from "../api/cardRequisitesApi";
|
||||
import { useCreateCardRequisite, useUpdateCardRequisite } from "../hooks/useCardRequisites";
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardRequisite.schema";
|
||||
import type { CardRequisiteFormData } from "../schemas/cardRequisite.schema";
|
||||
import { useInfiniteCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
||||
import { useInfiniteBranches } from "@/features/branches/hooks/useBranches";
|
||||
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||
import { resolveLocalizedName } from "@/features/loanOrders/api/loanOrdersApi";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -36,17 +42,20 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
const STATUS_OPTIONS: SelectOption[] = [
|
||||
{ value: "pending", label: "Garaşylýar" },
|
||||
{ value: "approved", label: "Tassyklanan" },
|
||||
{ value: "rejected", label: "Ret edilen" },
|
||||
];
|
||||
|
||||
const CARD_TYPE_OPTIONS = [
|
||||
{ value: "altyn_asyr", label: "Altyn Asyr" },
|
||||
{ value: "visa", label: "Visa" },
|
||||
{ value: "mastercard", label: "MasterCard" },
|
||||
];
|
||||
const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const;
|
||||
|
||||
function getRegionOptions(t: TFunction): SelectOption[] {
|
||||
return REGION_CODES.map((code) => ({
|
||||
value: code,
|
||||
label: t(`cardRequisites.regions.${code}`, code),
|
||||
}));
|
||||
}
|
||||
|
||||
const PASSPORT_SERIES_OPTIONS = [
|
||||
{ value: "I-MR", label: "I-MR" },
|
||||
@@ -58,50 +67,12 @@ const PASSPORT_SERIES_OPTIONS = [
|
||||
{ value: "B", label: "B" },
|
||||
];
|
||||
|
||||
const PROVINCE_OPTIONS = [
|
||||
{ value: "1", label: "Aşgabat" },
|
||||
{ value: "2", label: "Ahal" },
|
||||
{ value: "3", label: "Balkan" },
|
||||
{ value: "4", label: "Daşoguz" },
|
||||
{ value: "5", label: "Lebap" },
|
||||
{ value: "6", label: "Mary" },
|
||||
];
|
||||
|
||||
const BRANCH_OPTIONS: Record<string, { value: string; label: string }[]> = {
|
||||
"1": [
|
||||
{ value: "11", label: "Köpetdag" },
|
||||
{ value: "12", label: "Çandybil" },
|
||||
{ value: "13", label: "Büzmeyin" },
|
||||
],
|
||||
"2": [
|
||||
{ value: "21", label: "Änew" },
|
||||
{ value: "22", label: "Tejen" },
|
||||
],
|
||||
"3": [
|
||||
{ value: "31", label: "Balkanabat" },
|
||||
{ value: "32", label: "Türkmenbaşy" },
|
||||
],
|
||||
"4": [
|
||||
{ value: "41", label: "Daşoguz ş." },
|
||||
{ value: "42", label: "Köneürgenç" },
|
||||
],
|
||||
"5": [
|
||||
{ value: "51", label: "Türkmenabat" },
|
||||
{ value: "52", label: "Hazar" },
|
||||
],
|
||||
"6": [
|
||||
{ value: "61", label: "Mary ş." },
|
||||
{ value: "62", label: "Ýolöten" },
|
||||
{ value: "63", label: "Şatlyk" },
|
||||
],
|
||||
};
|
||||
|
||||
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
|
||||
const MONTH_OPTIONS: SelectOption[] = Array.from({ length: 12 }, (_, i) => {
|
||||
const val = String(i + 1).padStart(2, "0");
|
||||
return { value: val, label: val };
|
||||
});
|
||||
|
||||
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
|
||||
const YEAR_OPTIONS: SelectOption[] = Array.from({ length: 20 }, (_, i) => {
|
||||
const year = String(new Date().getFullYear() + i);
|
||||
return { value: year, label: year };
|
||||
});
|
||||
@@ -109,24 +80,26 @@ const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
|
||||
function mapInitial(data: CardRequisite): CardRequisiteFormData {
|
||||
return {
|
||||
status: data.status ?? "pending",
|
||||
note: data.note ?? "",
|
||||
card_type: data.card_type ?? "",
|
||||
card_number: data.card_number ?? "",
|
||||
card_expiry_month: data.card_expiry_month ?? "",
|
||||
card_expiry_year: data.card_expiry_year ?? "",
|
||||
province_id: data.province_id ?? "",
|
||||
branch_id: data.branch_id ?? "",
|
||||
first_name: data.first_name ?? "",
|
||||
last_name: data.last_name ?? "",
|
||||
middle_name: data.middle_name ?? "",
|
||||
birth_date: data.birth_date ?? "",
|
||||
notes: data.notes ?? "",
|
||||
region: data.region ?? "",
|
||||
cardTypeId: data.cardType?.id != null ? String(data.cardType.id) : "",
|
||||
branchId: data.branch?.id != null ? String(data.branch.id) : "",
|
||||
userId: data.user?.id != null ? String(data.user.id) : "",
|
||||
uniqueId: data.uniqueId ?? "",
|
||||
cardNumber: data.cardNumber ?? "",
|
||||
cardMonth: data.cardMonth ?? "",
|
||||
cardYear: data.cardYear ?? "",
|
||||
customerName: data.customerName ?? "",
|
||||
customerSurname: data.customerSurname ?? "",
|
||||
customerPatronicName: data.customerPatronicName ?? "",
|
||||
bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "",
|
||||
phone: data.phone ?? "",
|
||||
passport_series: data.passport_series ?? "",
|
||||
passport_number: data.passport_number ?? "",
|
||||
passport_page1: null,
|
||||
passport_page2_3: null,
|
||||
passport_page8_9: null,
|
||||
passport_page32: null,
|
||||
passportSerie: data.passportSerie ?? "",
|
||||
passportId: data.passportId ?? "",
|
||||
passportOne: data.passportOne ?? "",
|
||||
passportTwo: data.passportTwo ?? "",
|
||||
passportThree: data.passportThree ?? "",
|
||||
passportFour: data.passportFour ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -148,9 +121,9 @@ const STEPS: StepDef[] = [
|
||||
titleKey: "Card",
|
||||
titleFallback: "Kart",
|
||||
subtitleKey: "cardRequisiteForm.steps.card.subtitle",
|
||||
subtitleFallback: "Görnüş & lokasiýa",
|
||||
subtitleFallback: "Görnüş & maglumatlar",
|
||||
icon: CreditCard,
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
validate: (form) => validateStep(0, form),
|
||||
},
|
||||
{
|
||||
id: "personal",
|
||||
@@ -159,7 +132,7 @@ const STEPS: StepDef[] = [
|
||||
subtitleKey: "cardRequisiteForm.steps.personal.subtitle",
|
||||
subtitleFallback: "At & telefon",
|
||||
icon: User,
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
validate: (form) => validateStep(1, form),
|
||||
},
|
||||
{
|
||||
id: "passport",
|
||||
@@ -168,7 +141,7 @@ const STEPS: StepDef[] = [
|
||||
subtitleKey: "cardRequisiteForm.steps.passport.subtitle",
|
||||
subtitleFallback: "Resminamalar",
|
||||
icon: FileText,
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
validate: (form) => validateStep(2, form),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -179,12 +152,58 @@ interface StepContentProps {
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof CardRequisiteFormData>(k: K, v: CardRequisiteFormData[K]) => void;
|
||||
t: TFunction;
|
||||
initialData?: CardRequisite;
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
|
||||
function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
const branchOptions = BRANCH_OPTIONS[form.province_id] ?? [];
|
||||
function StepCard({ form, errors, set, t, initialData }: StepContentProps) {
|
||||
const [cardTypeSearch, setCardTypeSearch] = useState("");
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const [clientSearch, setClientSearch] = useState("");
|
||||
|
||||
const cardTypeQuery = useInfiniteCardTypes(cardTypeSearch);
|
||||
const branchQuery = useInfiniteBranches(branchSearch);
|
||||
const clientQuery = useInfiniteClients(clientSearch);
|
||||
|
||||
const regionOptions = useMemo(() => getRegionOptions(t), [t]);
|
||||
|
||||
const cardTypeOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (cardTypeQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.paymentCards ?? [])
|
||||
.map((ct) => ({ value: String(ct.id), label: resolveLocalizedName(ct.title) || String(ct.id) }));
|
||||
if (initialData?.cardType?.id && !opts.some((o) => o.value === String(initialData.cardType.id))) {
|
||||
opts.unshift({
|
||||
value: String(initialData.cardType.id),
|
||||
label: resolveLocalizedName(initialData.cardType.name) || String(initialData.cardType.id),
|
||||
});
|
||||
}
|
||||
return opts;
|
||||
}, [cardTypeQuery, initialData]);
|
||||
|
||||
const branchOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const langBranches = (branchQuery.data?.pages ?? []).flatMap((p) => p?.branches ?? []);
|
||||
const opts: InfiniteSelectOption[] = langBranches
|
||||
.filter((b) => (form.region ? b.region === form.region : true))
|
||||
.map((b) => ({ value: String(b.id), label: resolveLocalizedName(b.name) || String(b.id) }));
|
||||
if (initialData?.branch?.id && !opts.some((o) => o.value === String(initialData.branch.id))) {
|
||||
opts.unshift({
|
||||
value: String(initialData.branch.id),
|
||||
label: resolveLocalizedName(initialData.branch.name) || String(initialData.branch.id),
|
||||
});
|
||||
}
|
||||
return opts;
|
||||
}, [branchQuery, initialData, form.region]);
|
||||
|
||||
const clientOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (clientQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.users ?? [])
|
||||
.map((u) => ({ value: String(u.id), label: u.name || u.username || String(u.id) }));
|
||||
if (initialData?.user?.id && !opts.some((o) => o.value === String(initialData.user.id))) {
|
||||
opts.unshift({ value: String(initialData.user.id), label: initialData.user.name || String(initialData.user.id) });
|
||||
}
|
||||
return opts;
|
||||
}, [clientQuery, initialData]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -192,103 +211,148 @@ function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("loanOrderForm.labels.status") || "Status"}
|
||||
label={t("cardRequisiteForm.labels.status") || "Statusy"}
|
||||
required
|
||||
value={form.status}
|
||||
onChange={(v) => set("status", v)}
|
||||
options={STATUS_OPTIONS}
|
||||
error={errors.status}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.status}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardRequisiteForm.labels.uniqueId") || "Sargyt belgisi (Unikal ID)"}
|
||||
value={form.uniqueId}
|
||||
onChange={(v) => set("uniqueId", v)}
|
||||
placeholder={t("cardRequisiteForm.placeholders.uniqueId") || "Unikal ID..."}
|
||||
error={errors.uniqueId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<InfiniteSelect
|
||||
label={t("cardRequisiteForm.labels.cardType") || "Kart görnüşi"}
|
||||
value={form.cardTypeId}
|
||||
onChange={(v) => set("cardTypeId", v)}
|
||||
options={cardTypeOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
loading={cardTypeQuery.isLoading}
|
||||
isLoadingMore={cardTypeQuery.isFetchingNextPage}
|
||||
hasNextPage={!!cardTypeQuery.hasNextPage}
|
||||
onLoadMore={() => cardTypeQuery.fetchNextPage()}
|
||||
searchValue={cardTypeSearch}
|
||||
onSearchChange={setCardTypeSearch}
|
||||
error={errors.cardTypeId}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardRequisiteForm.labels.cardNumber") || "Kart belgisi"}
|
||||
value={form.cardNumber}
|
||||
onChange={(v) => set("cardNumber", v)}
|
||||
placeholder="9800 0000 0000 0000"
|
||||
error={errors.cardNumber}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("loanOrderForm.labels.cardExpMonth") || "Aý"}
|
||||
required
|
||||
value={form.cardMonth}
|
||||
onChange={(v) => set("cardMonth", v)}
|
||||
options={MONTH_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.cardMonth}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("loanOrderForm.labels.cardExpYear") || "Ýyl"}
|
||||
required
|
||||
value={form.cardYear}
|
||||
onChange={(v) => set("cardYear", v)}
|
||||
options={YEAR_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.cardYear}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("Region") || "Welaýat"}
|
||||
required
|
||||
value={form.region}
|
||||
onChange={(v) => {
|
||||
set("region", v);
|
||||
set("branchId", "");
|
||||
}}
|
||||
options={regionOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.region}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<InfiniteSelect
|
||||
label={t("Branch") || "Şahamça"}
|
||||
value={form.branchId}
|
||||
onChange={(v) => set("branchId", v)}
|
||||
options={branchOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
loading={branchQuery.isLoading}
|
||||
isLoadingMore={branchQuery.isFetchingNextPage}
|
||||
hasNextPage={!!branchQuery.hasNextPage}
|
||||
onLoadMore={() => branchQuery.fetchNextPage()}
|
||||
searchValue={branchSearch}
|
||||
onSearchChange={setBranchSearch}
|
||||
disabled={!form.region}
|
||||
error={errors.branchId}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<InfiniteSelect
|
||||
label={t("cardRequisiteForm.labels.user") || "Ulanyjy"}
|
||||
value={form.userId}
|
||||
onChange={(v) => set("userId", v)}
|
||||
options={clientOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
loading={clientQuery.isLoading}
|
||||
isLoadingMore={clientQuery.isFetchingNextPage}
|
||||
hasNextPage={!!clientQuery.hasNextPage}
|
||||
onLoadMore={() => clientQuery.fetchNextPage()}
|
||||
searchValue={clientSearch}
|
||||
onSearchChange={setClientSearch}
|
||||
error={errors.userId}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Note") || "Bellik"}
|
||||
value={form.note}
|
||||
onChange={(v) => set("note", v)}
|
||||
value={form.notes}
|
||||
onChange={(v) => set("notes", v)}
|
||||
placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Kart maglumatlary"}>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("cardRequisiteForm.labels.cardType") || "Görnüşi"}
|
||||
required
|
||||
value={form.card_type}
|
||||
onChange={(v) => set("card_type", v)}
|
||||
options={CARD_TYPE_OPTIONS}
|
||||
placeholder="—"
|
||||
error={errors.card_type}
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Card number") || "Kart belgisi"}
|
||||
required
|
||||
value={form.card_number}
|
||||
onChange={(v) => set("card_number", v)}
|
||||
placeholder={t("Card number") || "Kart belgisi"}
|
||||
error={errors.card_number}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("loanOrderForm.titles.cardExpiry") || "Kart möhleti"}>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Expiration month") || "Möhleti (aý)"}
|
||||
required
|
||||
value={form.card_expiry_month}
|
||||
onChange={(v) => set("card_expiry_month", v)}
|
||||
options={MONTH_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.card_expiry_month}
|
||||
/>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Expiration year") || "Möhleti (ýyl)"}
|
||||
required
|
||||
value={form.card_expiry_year}
|
||||
onChange={(v) => set("card_expiry_year", v)}
|
||||
options={YEAR_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.card_expiry_year}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Region") || "Welaýat"}
|
||||
required
|
||||
value={form.province_id}
|
||||
onChange={(v) => {
|
||||
set("province_id", v);
|
||||
set("branch_id", "");
|
||||
}}
|
||||
options={PROVINCE_OPTIONS}
|
||||
placeholder={t("Region") || "Aşgabat"}
|
||||
error={errors.province_id}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("Branch") || "Şahamça"}
|
||||
required
|
||||
value={form.branch_id}
|
||||
onChange={(v) => set("branch_id", v)}
|
||||
options={branchOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
disabled={!form.province_id}
|
||||
error={errors.branch_id}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -302,10 +366,10 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
type="text"
|
||||
label={t("Name") || "Ady"}
|
||||
required
|
||||
value={form.first_name}
|
||||
onChange={(v) => set("first_name", v)}
|
||||
value={form.customerName}
|
||||
onChange={(v) => set("customerName", v)}
|
||||
placeholder={t("Name") || "Ady"}
|
||||
error={errors.first_name}
|
||||
error={errors.customerName}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
@@ -313,18 +377,18 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
type="text"
|
||||
label={t("Surname") || "Familiýasy"}
|
||||
required
|
||||
value={form.last_name}
|
||||
onChange={(v) => set("last_name", v)}
|
||||
value={form.customerSurname}
|
||||
onChange={(v) => set("customerSurname", v)}
|
||||
placeholder={t("Surname") || "Familiýasy"}
|
||||
error={errors.last_name}
|
||||
error={errors.customerSurname}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Patronic name") || "Atasynyň ady"}
|
||||
value={form.middle_name}
|
||||
onChange={(v) => set("middle_name", v)}
|
||||
value={form.customerPatronicName}
|
||||
onChange={(v) => set("customerPatronicName", v)}
|
||||
placeholder={t("Patronic name") || "Atasynyň ady"}
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -336,9 +400,9 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
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}
|
||||
value={form.bornAt}
|
||||
onChange={(v) => set("bornAt", v)}
|
||||
error={errors.bornAt}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
@@ -357,27 +421,7 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
);
|
||||
}
|
||||
|
||||
function StepPassport({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
mode,
|
||||
initialData,
|
||||
}: StepContentProps & {
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardRequisite;
|
||||
}) {
|
||||
const existingFiles =
|
||||
mode === "edit" && initialData
|
||||
? [
|
||||
{ url: initialData.passport_page1_url, label: t("Passport (page 1)") || "Pasport (sahypa 1)" },
|
||||
{ url: initialData.passport_page2_3_url, label: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)" },
|
||||
{ url: initialData.passport_page8_9_url, label: t("Passport (page 8-9)") || "Pasport (8-9 sahypa)" },
|
||||
{ url: initialData.passport_page32_url, label: t("Passport (page 32)") || "Pasport (32-nji sahypa)" },
|
||||
].filter((f): f is { url: string; label: string } => !!f.url)
|
||||
: [];
|
||||
|
||||
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={2}>
|
||||
@@ -386,11 +430,11 @@ function StepPassport({
|
||||
type="searchable-select"
|
||||
label={t("Passport serie") || "Pasport seriýasy"}
|
||||
required
|
||||
value={form.passport_series}
|
||||
onChange={(v) => set("passport_series", v)}
|
||||
value={form.passportSerie}
|
||||
onChange={(v) => set("passportSerie", v)}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.passport_series}
|
||||
error={errors.passportSerie}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
@@ -398,77 +442,49 @@ function StepPassport({
|
||||
type="text"
|
||||
label={t("Passport id") || "Pasport belgisi"}
|
||||
required
|
||||
value={form.passport_number}
|
||||
onChange={(v) => set("passport_number", v)}
|
||||
value={form.passportId}
|
||||
onChange={(v) => set("passportId", v)}
|
||||
placeholder={t("Passport id") || "Pasport belgisi"}
|
||||
error={errors.passport_number}
|
||||
error={errors.passportId}
|
||||
/>
|
||||
</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}>
|
||||
<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_page1}
|
||||
onFileChange={(f) => set("passport_page1", f)}
|
||||
error={errors.passport_page1}
|
||||
<DocumentUpload
|
||||
label={t("Passport (page 1)") || "Pasport (sahypa 1)"}
|
||||
value={form.passportOne}
|
||||
onChange={(v) => set("passportOne", v)}
|
||||
error={errors.passportOne}
|
||||
accept="image/*"
|
||||
/>
|
||||
</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_page2_3}
|
||||
onFileChange={(f) => set("passport_page2_3", f)}
|
||||
error={errors.passport_page2_3}
|
||||
<DocumentUpload
|
||||
label={t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)"}
|
||||
value={form.passportTwo}
|
||||
onChange={(v) => set("passportTwo", v)}
|
||||
error={errors.passportTwo}
|
||||
accept="image/*"
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
<DocumentUpload
|
||||
label={t("Passport (page 8-9)") || "Pasport (8-9 sahypa)"}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_page8_9}
|
||||
onFileChange={(f) => set("passport_page8_9", f)}
|
||||
error={errors.passport_page8_9}
|
||||
value={form.passportThree}
|
||||
onChange={(v) => set("passportThree", v)}
|
||||
error={errors.passportThree}
|
||||
accept="image/*"
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
<DocumentUpload
|
||||
label={t("Passport (page 32)") || "Pasport (32-nji sahypa)"}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_page32}
|
||||
onFileChange={(f) => set("passport_page32", f)}
|
||||
error={errors.passport_page32}
|
||||
value={form.passportFour}
|
||||
onChange={(v) => set("passportFour", v)}
|
||||
error={errors.passportFour}
|
||||
accept="image/*"
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -483,7 +499,7 @@ export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps)
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateCardRequisite();
|
||||
const updateMutation = useUpdateCardRequisite(initialData?.id ?? "");
|
||||
const updateMutation = useUpdateCardRequisite(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
@@ -534,7 +550,7 @@ export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps)
|
||||
return { ...fromRHF, ...allSubmittedErrors };
|
||||
}, [rhfErrors, allSubmittedErrors]);
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t]);
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t, initialData }), [form, errors, set, t, initialData]);
|
||||
|
||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -647,7 +663,7 @@ export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps)
|
||||
{/* Step content */}
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
||||
{currentStep === 2 && <StepPassport {...stepProps} mode={mode} initialData={initialData} />}
|
||||
{currentStep === 2 && <StepPassport {...stepProps} />}
|
||||
|
||||
{/* Actions */}
|
||||
<FormActions
|
||||
|
||||
@@ -1,96 +1,80 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
cardRequisitesApi,
|
||||
type CardRequisiteListParams,
|
||||
type CreateCardRequisitePayload,
|
||||
type UpdateCardRequisitePayload,
|
||||
} from '../api/cardRequisitesApi'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { cardRequisitesApi, type CardRequisiteListParams, type CardRequisitePayload } from "../api/cardRequisitesApi";
|
||||
|
||||
const QUERY_KEY = 'card-requisites'
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const cardRequisiteKeys = {
|
||||
all: ["cardRequisites"] as const,
|
||||
lists: () => [...cardRequisiteKeys.all, "list"] as const,
|
||||
list: (params: CardRequisiteListParams) => [...cardRequisiteKeys.lists(), params] as const,
|
||||
details: () => [...cardRequisiteKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...cardRequisiteKeys.details(), id] as const,
|
||||
};
|
||||
|
||||
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardRequisites(params?: CardRequisiteListParams) {
|
||||
export function useCardRequisites(params: CardRequisiteListParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: [QUERY_KEY, params],
|
||||
queryFn: () => cardRequisitesApi.getAll(params),
|
||||
})
|
||||
queryKey: cardRequisiteKeys.list(params),
|
||||
queryFn: ({ signal }) => cardRequisitesApi.getList(params, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Single ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardRequisite(id: string) {
|
||||
export function useCardRequisite(id: number) {
|
||||
return useQuery({
|
||||
queryKey: [QUERY_KEY, id],
|
||||
queryKey: cardRequisiteKeys.detail(id),
|
||||
queryFn: () => cardRequisitesApi.getById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCardRequisite() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateCardRequisitePayload) => cardRequisitesApi.create(payload),
|
||||
mutationFn: (payload: CardRequisitePayload) => cardRequisitesApi.create(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
||||
toast.success(t('Card requisite created successfully', 'Kart rekwiziti üstünlikli döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: cardRequisiteKeys.lists() });
|
||||
toast.success(t("cardRequisites.createSuccess", "Kart rekwiziti üstünlikli döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCardRequisite(id: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
export function useUpdateCardRequisite(id: number) {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateCardRequisitePayload) => cardRequisitesApi.update(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
||||
toast.success(t('Card requisite updated successfully', 'Kart rekwiziti üstünlikli üýtgedildi'))
|
||||
mutationFn: (payload: CardRequisitePayload) => cardRequisitesApi.update(id, payload),
|
||||
onSuccess: (updated) => {
|
||||
queryClient.invalidateQueries({ queryKey: cardRequisiteKeys.lists() });
|
||||
queryClient.setQueryData(cardRequisiteKeys.detail(id), updated);
|
||||
toast.success(t("cardRequisites.updateSuccess", "Kart rekwiziti üstünlikli üýtgedildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCardRequisite() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => cardRequisitesApi.delete(id),
|
||||
mutationFn: (id: number) => cardRequisitesApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
||||
toast.success(t('Card requisite deleted successfully', 'Kart rekwiziti üstünlikli öçürildi'))
|
||||
queryClient.invalidateQueries({ queryKey: cardRequisiteKeys.lists() });
|
||||
toast.success(t("cardRequisites.deleteSuccess", "Kart rekwiziti üstünlikli öçürildi"));
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── Download ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDownloadCardRequisite() {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const blob = await cardRequisitesApi.download(id)
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `card-requisite-${id}.pdf`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi'))
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
import { z } from "zod";
|
||||
import i18next from "i18next";
|
||||
import type { CardRequisiteStatus, CreateCardRequisitePayload } from "../api/cardRequisitesApi";
|
||||
import type { CardRequisitePayload } from "../api/cardRequisitesApi";
|
||||
|
||||
const fileRequired = z.custom<File>((val) => val instanceof File, "validation.requiredFile");
|
||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
||||
|
||||
export const cardRequisiteFormSchema = z.object({
|
||||
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"),
|
||||
card_expiry_month: z.string().min(1, "validation.required"),
|
||||
card_expiry_year: z.string().min(1, "validation.required"),
|
||||
province_id: z.string().min(1, "validation.required"),
|
||||
branch_id: z.string().min(1, "validation.required"),
|
||||
first_name: z.string().min(1, "validation.required"),
|
||||
last_name: z.string().min(1, "validation.required"),
|
||||
middle_name: z.string().optional(),
|
||||
birth_date: z.string().min(1, "validation.required"),
|
||||
notes: z.string().optional(),
|
||||
region: z.string().min(1, "validation.required"),
|
||||
cardTypeId: z.string().min(1, "validation.required"),
|
||||
branchId: z.string().min(1, "validation.required"),
|
||||
userId: z.string().min(1, "validation.required"),
|
||||
uniqueId: z.string().optional(),
|
||||
cardNumber: z.string().optional(),
|
||||
cardMonth: z.string().optional(),
|
||||
cardYear: z.string().optional(),
|
||||
customerName: z.string().min(1, "validation.required"),
|
||||
customerSurname: z.string().min(1, "validation.required"),
|
||||
customerPatronicName: z.string().optional(),
|
||||
bornAt: z.string().min(1, "validation.required"),
|
||||
phone: z
|
||||
.string()
|
||||
.min(1, "validation.required")
|
||||
@@ -36,12 +37,12 @@ export const cardRequisiteFormSchema = z.object({
|
||||
},
|
||||
{ message: "validation.invalidPhonePrefix" },
|
||||
),
|
||||
passport_series: z.string().min(1, "validation.required"),
|
||||
passport_number: z.string().min(1, "validation.required"),
|
||||
passport_page1: z.custom<File | null>().nullable(),
|
||||
passport_page2_3: z.custom<File | null>().nullable(),
|
||||
passport_page8_9: z.custom<File | null>().nullable(),
|
||||
passport_page32: z.custom<File | null>().nullable(),
|
||||
passportSerie: z.string().min(1, "validation.required"),
|
||||
passportId: z.string().min(1, "validation.required"),
|
||||
passportOne: z.string().optional(),
|
||||
passportTwo: z.string().optional(),
|
||||
passportThree: z.string().optional(),
|
||||
passportFour: z.string().optional(),
|
||||
});
|
||||
|
||||
export type CardRequisiteFormData = z.infer<typeof cardRequisiteFormSchema>;
|
||||
@@ -49,26 +50,30 @@ export type CardRequisiteFormData = z.infer<typeof cardRequisiteFormSchema>;
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<CardRequisiteFormData>>> = {
|
||||
0: cardRequisiteFormSchema.pick({
|
||||
status: true,
|
||||
card_type: true,
|
||||
card_number: true,
|
||||
card_expiry_month: true,
|
||||
card_expiry_year: true,
|
||||
province_id: true,
|
||||
branch_id: true,
|
||||
region: true,
|
||||
cardTypeId: true,
|
||||
branchId: true,
|
||||
userId: true,
|
||||
uniqueId: true,
|
||||
cardNumber: true,
|
||||
cardMonth: true,
|
||||
cardYear: true,
|
||||
notes: true,
|
||||
}),
|
||||
1: cardRequisiteFormSchema.pick({
|
||||
first_name: true,
|
||||
last_name: true,
|
||||
birth_date: true,
|
||||
customerName: true,
|
||||
customerSurname: true,
|
||||
customerPatronicName: true,
|
||||
bornAt: true,
|
||||
phone: true,
|
||||
}),
|
||||
2: z.object({
|
||||
passport_series: z.string().min(1, "validation.required"),
|
||||
passport_number: z.string().min(1, "validation.required"),
|
||||
passport_page1: fileRequired,
|
||||
passport_page2_3: fileRequired,
|
||||
passport_page8_9: fileRequired,
|
||||
passport_page32: fileRequired,
|
||||
2: cardRequisiteFormSchema.pick({
|
||||
passportSerie: true,
|
||||
passportId: true,
|
||||
passportOne: true,
|
||||
passportTwo: true,
|
||||
passportThree: true,
|
||||
passportFour: true,
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -76,26 +81,7 @@ function translateMsg(msg: string): string {
|
||||
return msg.startsWith("validation.") ? i18next.t(msg, msg) : msg;
|
||||
}
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: CardRequisiteFormData,
|
||||
mode: "create" | "edit",
|
||||
): Partial<Record<keyof CardRequisiteFormData, string>> {
|
||||
if (stepIndex === 2 && mode === "edit") {
|
||||
const schema = z.object({
|
||||
passport_series: z.string().min(1, "validation.required"),
|
||||
passport_number: z.string().min(1, "validation.required"),
|
||||
});
|
||||
const result = schema.safeParse(form);
|
||||
if (result.success) return {};
|
||||
const errors: Partial<Record<keyof CardRequisiteFormData, string>> = {};
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof CardRequisiteFormData;
|
||||
if (!errors[key]) errors[key] = translateMsg(issue.message);
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
export function validateStep(stepIndex: number, form: CardRequisiteFormData): Partial<Record<keyof CardRequisiteFormData, string>> {
|
||||
const schema = stepSchemas[stepIndex];
|
||||
if (!schema) return {};
|
||||
const result = schema.safeParse(form);
|
||||
@@ -110,46 +96,50 @@ export function validateStep(
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardRequisiteFormData = {
|
||||
status: "pending",
|
||||
note: "",
|
||||
card_type: "",
|
||||
card_number: "",
|
||||
card_expiry_month: "",
|
||||
card_expiry_year: "",
|
||||
province_id: "",
|
||||
branch_id: "",
|
||||
first_name: "",
|
||||
last_name: "",
|
||||
middle_name: "",
|
||||
birth_date: "",
|
||||
notes: "",
|
||||
region: "",
|
||||
cardTypeId: "",
|
||||
branchId: "",
|
||||
userId: "",
|
||||
uniqueId: "",
|
||||
cardNumber: "",
|
||||
cardMonth: "",
|
||||
cardYear: "",
|
||||
customerName: "",
|
||||
customerSurname: "",
|
||||
customerPatronicName: "",
|
||||
bornAt: "",
|
||||
phone: "",
|
||||
passport_series: "",
|
||||
passport_number: "",
|
||||
passport_page1: null,
|
||||
passport_page2_3: null,
|
||||
passport_page8_9: null,
|
||||
passport_page32: null,
|
||||
passportSerie: "",
|
||||
passportId: "",
|
||||
passportOne: "",
|
||||
passportTwo: "",
|
||||
passportThree: "",
|
||||
passportFour: "",
|
||||
};
|
||||
|
||||
export function buildPayload(data: CardRequisiteFormData): CreateCardRequisitePayload {
|
||||
export function buildPayload(data: CardRequisiteFormData): CardRequisitePayload {
|
||||
return {
|
||||
status: data.status as CardRequisiteStatus,
|
||||
note: data.note || undefined,
|
||||
card_type: data.card_type,
|
||||
card_number: data.card_number,
|
||||
card_expiry_month: data.card_expiry_month,
|
||||
card_expiry_year: data.card_expiry_year,
|
||||
province_id: data.province_id,
|
||||
branch_id: data.branch_id,
|
||||
first_name: data.first_name,
|
||||
last_name: data.last_name,
|
||||
middle_name: data.middle_name || undefined,
|
||||
birth_date: data.birth_date,
|
||||
status: data.status,
|
||||
notes: data.notes || "",
|
||||
region: data.region,
|
||||
cardTypeId: Number(data.cardTypeId),
|
||||
branchId: Number(data.branchId),
|
||||
userId: Number(data.userId),
|
||||
customerName: data.customerName,
|
||||
customerSurname: data.customerSurname,
|
||||
customerPatronicName: data.customerPatronicName || "",
|
||||
bornAt: data.bornAt,
|
||||
phone: data.phone,
|
||||
passport_series: data.passport_series,
|
||||
passport_number: data.passport_number,
|
||||
...(data.passport_page1 && { passport_page1: data.passport_page1 }),
|
||||
...(data.passport_page2_3 && { passport_page2_3: data.passport_page2_3 }),
|
||||
...(data.passport_page8_9 && { passport_page8_9: data.passport_page8_9 }),
|
||||
...(data.passport_page32 && { passport_page32: data.passport_page32 }),
|
||||
passportSerie: data.passportSerie,
|
||||
passportId: data.passportId,
|
||||
passportOne: data.passportOne || "",
|
||||
passportTwo: data.passportTwo || "",
|
||||
passportThree: data.passportThree || "",
|
||||
passportFour: data.passportFour || "",
|
||||
uniqueId: data.uniqueId || "",
|
||||
cardNumber: data.cardNumber || "",
|
||||
cardMonth: data.cardMonth || "",
|
||||
cardYear: data.cardYear || "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,498 +1,84 @@
|
||||
import apiClient from "@/lib/api/client";
|
||||
import type { StatusValue } from "@/constants";
|
||||
import {
|
||||
mapBackendToUI,
|
||||
getLoanOrderById,
|
||||
createLoanOrder,
|
||||
updateLoanOrder,
|
||||
patchLoanOrder,
|
||||
deleteLoanOrder,
|
||||
type LoanOrder,
|
||||
type LoanOrderStatus,
|
||||
type LoanOrderUser,
|
||||
type LoanOrderPayload,
|
||||
type LoanOrdersParams,
|
||||
type LoanOrdersResponse,
|
||||
type BackendLoanOrder,
|
||||
type LoanOrdersListResponse,
|
||||
} from "@/features/loanOrders/api/loanOrdersApi";
|
||||
|
||||
// ─── Types ─────────────────────────────────────────────────────────────────────
|
||||
// ─── Type Aliases (Seamless backwards compatibility & domain clarity) ────────
|
||||
|
||||
export type LoanOrderMobileStatus = StatusValue;
|
||||
export type { LoanOrderStatus, LoanOrder, LoanOrderUser, LoanOrderPayload, LoanOrdersParams, LoanOrdersResponse };
|
||||
|
||||
export interface LoanOrderMobile {
|
||||
id: string;
|
||||
loanType: string;
|
||||
createdAt: string;
|
||||
region: string;
|
||||
branch: string;
|
||||
branchId?: number | string;
|
||||
loanTypeId?: number | string;
|
||||
workCityId?: number | string;
|
||||
createdById?: number | string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
phone: string;
|
||||
status: LoanOrderMobileStatus;
|
||||
createdBy?: string;
|
||||
|
||||
// ── Detail fields ─────────────────────────────────────────────────────────
|
||||
patronicName?: string | null;
|
||||
education?: string | null;
|
||||
marriageStatus?: string | null;
|
||||
dateOfBirth?: string | null;
|
||||
residence?: string | null;
|
||||
currentResidence?: string | null;
|
||||
|
||||
// Passport
|
||||
passportSerie?: string | null;
|
||||
passportNumber?: string | null;
|
||||
passportDateOfIssue?: string | null;
|
||||
passportGivenBy?: string | null;
|
||||
bornPlace?: string | null;
|
||||
passportPage1Url?: string | null;
|
||||
passportPage23Url?: string | null;
|
||||
passportPage89Url?: string | null;
|
||||
passportPage32Url?: string | null;
|
||||
|
||||
// Contact
|
||||
email?: string | null;
|
||||
phoneAdditional?: string | null;
|
||||
homePhone?: string | null;
|
||||
|
||||
// Employment
|
||||
workCompany?: string | null;
|
||||
workHrPhone?: string | null;
|
||||
workRegion?: string | null;
|
||||
workProvince?: string | null;
|
||||
position?: string | null;
|
||||
salary?: number | null;
|
||||
workStartedAt?: string | null;
|
||||
|
||||
// New fields
|
||||
note?: string | null;
|
||||
loanAmount?: number | null;
|
||||
loanHistory?: string | null;
|
||||
|
||||
// Card (Zähmet haky)
|
||||
cardNumber?: string | null;
|
||||
cardName?: string | null;
|
||||
cardExpMonth?: string | null;
|
||||
cardExpYear?: string | null;
|
||||
|
||||
// Guarantor (Zamun)
|
||||
guarantor1Name?: string | null;
|
||||
guarantor1Surname?: string | null;
|
||||
guarantor1Patronic?: string | null;
|
||||
guarantor1PassportSerie?: string | null;
|
||||
guarantor1PassportNumber?: string | null;
|
||||
guarantor1CardNumber?: string | null;
|
||||
guarantor1CardName?: string | null;
|
||||
guarantor1CardExpMonth?: string | null;
|
||||
guarantor1CardExpYear?: string | null;
|
||||
guarantor1Salary?: number | null;
|
||||
}
|
||||
|
||||
export interface LoanOrderMobilePayload {
|
||||
status: string;
|
||||
loanType: string;
|
||||
region: string;
|
||||
branch: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
patronicName?: string;
|
||||
education: string;
|
||||
marriageStatus: string;
|
||||
dateOfBirth: string;
|
||||
residence: string;
|
||||
currentResidence?: string;
|
||||
passportSerie: string;
|
||||
passportNumber: string;
|
||||
passportDateOfIssue: string;
|
||||
passportGivenBy: string;
|
||||
bornPlace?: string;
|
||||
email?: string;
|
||||
phone: string;
|
||||
phoneAdditional?: string;
|
||||
homePhone?: string;
|
||||
workCompany: string;
|
||||
workHrPhone?: string;
|
||||
workRegion?: string;
|
||||
workProvince?: string;
|
||||
position: string;
|
||||
salary: number;
|
||||
workStartedAt: string;
|
||||
|
||||
note?: string;
|
||||
loanAmount?: number;
|
||||
loanHistory?: string;
|
||||
|
||||
cardNumber?: string;
|
||||
cardName?: string;
|
||||
cardExpMonth?: string;
|
||||
cardExpYear?: string;
|
||||
|
||||
guarantor1Name?: string;
|
||||
guarantor1Surname?: string;
|
||||
guarantor1Patronic?: string;
|
||||
guarantor1PassportSerie?: string;
|
||||
guarantor1PassportNumber?: string;
|
||||
guarantor1CardNumber?: string;
|
||||
guarantor1CardName?: string;
|
||||
guarantor1CardExpMonth?: string;
|
||||
guarantor1CardExpYear?: string;
|
||||
guarantor1Salary?: number;
|
||||
}
|
||||
|
||||
export interface LoanOrderMobileListParams {
|
||||
search?: string;
|
||||
region?: string;
|
||||
status?: LoanOrderMobileStatus;
|
||||
branch?: string;
|
||||
archived?: string;
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
export type LoanOrderMobileStatus = LoanOrderStatus;
|
||||
export type LoanOrderMobile = LoanOrder;
|
||||
export type LoanOrderMobileUser = LoanOrderUser;
|
||||
export type LoanOrderMobilePayload = LoanOrderPayload;
|
||||
export type LoanOrderMobileListParams = LoanOrdersParams;
|
||||
export type LoanOrderMobilesResponse = LoanOrdersResponse;
|
||||
export type PaginatedResponse<T> = {
|
||||
data: T[];
|
||||
total: number;
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
};
|
||||
export type BackendLoanOrderMobile = BackendLoanOrder;
|
||||
|
||||
// ─── Shared CRUD API Functions (Re-exported from loanOrdersApi) ───────────────
|
||||
|
||||
export const getLoanOrderMobileById = getLoanOrderById;
|
||||
export const updateLoanOrderMobile = updateLoanOrder;
|
||||
export const patchLoanOrderMobile = patchLoanOrder;
|
||||
export const deleteLoanOrderMobile = deleteLoanOrder;
|
||||
|
||||
export async function createLoanOrderMobile(payload: LoanOrderPayload): Promise<LoanOrder> {
|
||||
return createLoanOrder({ ...payload, source: payload.source ?? "mobile" });
|
||||
}
|
||||
|
||||
// ─── Mock Data ─────────────────────────────────────────────────────────────────
|
||||
// ─── Mobile-specific List API ──────────────────────────────────────────────────
|
||||
|
||||
const MOCK_DATA: LoanOrderMobile[] = [
|
||||
{
|
||||
id: "LOM-0001",
|
||||
loanType: "Sarp ediş karzy",
|
||||
createdAt: "2025-01-15 09:42",
|
||||
region: "Aşgabat",
|
||||
branch: "Merkezi şahamça",
|
||||
branchId: 1,
|
||||
loanTypeId: 1,
|
||||
workCityId: 1,
|
||||
createdById: "U-1001",
|
||||
firstName: "Oraz",
|
||||
lastName: "Annaýew",
|
||||
phone: "+99361123456",
|
||||
status: "pending",
|
||||
note: "Müşderi dokumentleri tassyklamady",
|
||||
loanAmount: 15000,
|
||||
loanHistory: "positive",
|
||||
patronicName: "Myradowiç",
|
||||
education: "high",
|
||||
marriageStatus: "MARRIED",
|
||||
dateOfBirth: "1992-04-18",
|
||||
residence: "Aşgabat, Bitarap Türkmenistan şaýoly, 15",
|
||||
currentResidence: "Aşgabat, Garaşsyzlyk köçesi, 5",
|
||||
passportSerie: "I-AŞ",
|
||||
passportNumber: "123456",
|
||||
passportDateOfIssue: "2015-03-10",
|
||||
passportGivenBy: "Aşgabat şäheriniň Içeri işler müdirligi",
|
||||
bornPlace: "Aşgabat şäheri",
|
||||
email: "oraz.annayew@email.com",
|
||||
phoneAdditional: "+99365443322",
|
||||
workCompany: "Türkmennebit",
|
||||
workHrPhone: "+99312456789",
|
||||
workRegion: "Aşgabat",
|
||||
workProvince: "Büzmeýin etraby",
|
||||
position: "Inžener",
|
||||
salary: 2500,
|
||||
workStartedAt: "2018-06-01",
|
||||
cardNumber: "4111111111111111",
|
||||
cardName: "ORAZ ANNAÝEW",
|
||||
cardExpMonth: "12",
|
||||
cardExpYear: "2027",
|
||||
guarantor1Name: "Berdi",
|
||||
guarantor1Surname: "Berdiýew",
|
||||
guarantor1Patronic: "Annagulyýewiç",
|
||||
guarantor1PassportSerie: "II-MR",
|
||||
guarantor1PassportNumber: "654321",
|
||||
guarantor1CardNumber: "4222222222222222",
|
||||
guarantor1CardName: "BERDI BERDIÝEW",
|
||||
guarantor1CardExpMonth: "06",
|
||||
guarantor1CardExpYear: "2026",
|
||||
guarantor1Salary: 3000,
|
||||
},
|
||||
{
|
||||
id: "LOM-0002",
|
||||
loanType: "Awtoulag karzy",
|
||||
createdAt: "2025-01-18 11:05",
|
||||
region: "Ahal",
|
||||
branch: "Änew şahamçasy",
|
||||
branchId: 2,
|
||||
loanTypeId: 2,
|
||||
workCityId: 2,
|
||||
createdById: "U-1002",
|
||||
firstName: "Merjen",
|
||||
lastName: "Hudaýewa",
|
||||
phone: "+99362234567",
|
||||
status: "approved",
|
||||
loanAmount: 30000,
|
||||
loanHistory: "new",
|
||||
patronicName: "Myratowna",
|
||||
education: "masters",
|
||||
marriageStatus: "SINGLE",
|
||||
dateOfBirth: "1995-11-20",
|
||||
residence: "Änew şäher, Garaşsyzlyk köçesi, 10",
|
||||
passportSerie: "I-MR",
|
||||
passportNumber: "789012",
|
||||
passportDateOfIssue: "2018-07-22",
|
||||
passportGivenBy: "Ahal welaýatynyň Içeri işler müdirligi",
|
||||
bornPlace: "Änew şäheri",
|
||||
email: "merjen.hudayewa@email.com",
|
||||
workCompany: "Änew etrap hasap bölümi",
|
||||
position: "Hasapçy",
|
||||
salary: 1800,
|
||||
workStartedAt: "2019-03-15",
|
||||
cardNumber: "4333333333333333",
|
||||
cardName: "MERJEN HUDAÝEWA",
|
||||
cardExpMonth: "09",
|
||||
cardExpYear: "2028",
|
||||
guarantor1Name: "Merdan",
|
||||
guarantor1Surname: "Merdanow",
|
||||
guarantor1PassportSerie: "I-AH",
|
||||
guarantor1PassportNumber: "345678",
|
||||
guarantor1CardNumber: "4444444444444444",
|
||||
guarantor1CardName: "MERDAN MERDANOW",
|
||||
guarantor1CardExpMonth: "03",
|
||||
guarantor1CardExpYear: "2025",
|
||||
guarantor1Salary: 2200,
|
||||
},
|
||||
{
|
||||
id: "LOM-0003",
|
||||
loanType: "Ipoteka karzy",
|
||||
createdAt: "2025-01-20 14:30",
|
||||
region: "Balkan",
|
||||
branch: "Balkanabat şahamçasy",
|
||||
branchId: 3,
|
||||
loanTypeId: 3,
|
||||
workCityId: 7,
|
||||
createdById: "U-1003",
|
||||
firstName: "Serdar",
|
||||
lastName: "Durdyýew",
|
||||
phone: "+99363345678",
|
||||
status: "pending",
|
||||
loanAmount: 50000,
|
||||
loanHistory: "positive",
|
||||
patronicName: "Annagylyjowiç",
|
||||
education: "high",
|
||||
marriageStatus: "MARRIED",
|
||||
dateOfBirth: "1988-07-12",
|
||||
residence: "Balkanabat, Magtymguly köçesi, 25",
|
||||
passportSerie: "II-AH",
|
||||
passportNumber: "456123",
|
||||
passportDateOfIssue: "2016-05-18",
|
||||
passportGivenBy: "Balkan welaýatynyň Içeri işler müdirligi",
|
||||
email: "serdar.durdyyew@email.com",
|
||||
workCompany: "Balkan nebit",
|
||||
position: "Operator",
|
||||
salary: 3200,
|
||||
workStartedAt: "2015-09-01",
|
||||
cardNumber: "4555555555555555",
|
||||
cardName: "SERDAR DURDYÝEW",
|
||||
cardExpMonth: "04",
|
||||
cardExpYear: "2029",
|
||||
guarantor1Name: "Döwran",
|
||||
guarantor1Surname: "Döwranow",
|
||||
guarantor1PassportSerie: "I-LB",
|
||||
guarantor1PassportNumber: "789456",
|
||||
guarantor1CardNumber: "4666666666666666",
|
||||
guarantor1CardName: "DÖWRAN DÖWRANOW",
|
||||
guarantor1CardExpMonth: "11",
|
||||
guarantor1CardExpYear: "2027",
|
||||
guarantor1Salary: 3500,
|
||||
},
|
||||
{
|
||||
id: "LOM-0004",
|
||||
loanType: "Telekeçilik karzy",
|
||||
createdAt: "2025-01-22 08:15",
|
||||
region: "Lebap",
|
||||
branch: "Türkmenabat şahamçasy",
|
||||
firstName: "Aýna",
|
||||
lastName: "Meredowa",
|
||||
phone: "+99365456789",
|
||||
status: "rejected",
|
||||
loanAmount: 25000,
|
||||
patronicName: "Begenjowna",
|
||||
education: "high",
|
||||
marriageStatus: "DIVORCED",
|
||||
dateOfBirth: "1991-02-28",
|
||||
residence: "Türkmenabat, Lebap köçesi, 8",
|
||||
passportSerie: "II-LB",
|
||||
passportNumber: "321654",
|
||||
passportDateOfIssue: "2017-11-05",
|
||||
passportGivenBy: "Lebap welaýatynyň Içeri işler müdirligi",
|
||||
workCompany: "Hususy telekeçi",
|
||||
position: "Telekeçi",
|
||||
salary: 4000,
|
||||
workStartedAt: "2020-01-10",
|
||||
cardNumber: "4777777777777777",
|
||||
cardName: "AÝNA MEREDOWA",
|
||||
cardExpMonth: "07",
|
||||
cardExpYear: "2026",
|
||||
},
|
||||
{
|
||||
id: "LOM-0005",
|
||||
loanType: "Sarp ediş karzy",
|
||||
createdAt: "2025-01-25 16:00",
|
||||
region: "Mary",
|
||||
branch: "Mary-1 şahamçasy",
|
||||
firstName: "Begmyrat",
|
||||
lastName: "Oraz",
|
||||
phone: "+99366567890",
|
||||
status: "pending",
|
||||
loanAmount: 8000,
|
||||
loanHistory: "new",
|
||||
patronicName: "Annageldiwiç",
|
||||
education: "middle",
|
||||
marriageStatus: "SINGLE",
|
||||
dateOfBirth: "2000-08-15",
|
||||
residence: "Mary şäher, Saýat köçesi, 3",
|
||||
passportSerie: "I-BN",
|
||||
passportNumber: "567890",
|
||||
passportDateOfIssue: "2020-01-20",
|
||||
passportGivenBy: "Mary welaýatynyň Içeri işler müdirligi",
|
||||
workCompany: "Mary gurluşyk",
|
||||
position: "Işçi",
|
||||
salary: 1200,
|
||||
workStartedAt: "2022-06-01",
|
||||
},
|
||||
{
|
||||
id: "LOM-0006",
|
||||
loanType: "Bilim karzy",
|
||||
createdAt: "2025-01-28 10:20",
|
||||
region: "Daşoguz",
|
||||
branch: "Daşoguz şahamçasy",
|
||||
firstName: "Gülälek",
|
||||
lastName: "Saparowa",
|
||||
phone: "+99361678901",
|
||||
status: "approved",
|
||||
loanAmount: 12000,
|
||||
patronicName: "Mämmedowna",
|
||||
education: "phd",
|
||||
marriageStatus: "MARRIED",
|
||||
dateOfBirth: "1985-12-03",
|
||||
residence: "Daşoguz, Gurbansoltan eje köçesi, 12",
|
||||
passportSerie: "II-BN",
|
||||
passportNumber: "901234",
|
||||
passportDateOfIssue: "2014-08-30",
|
||||
passportGivenBy: "Daşoguz welaýatynyň Içeri işler müdirligi",
|
||||
email: "gulalek.saparowa@email.com",
|
||||
workCompany: "Daşoguz uniwersiteti",
|
||||
position: "Mugallym",
|
||||
salary: 2000,
|
||||
workStartedAt: "2016-09-01",
|
||||
cardNumber: "4888888888888888",
|
||||
cardName: "GÜLÄLEK SAPAROWA",
|
||||
cardExpMonth: "02",
|
||||
cardExpYear: "2028",
|
||||
guarantor1Name: "Maksat",
|
||||
guarantor1Surname: "Saparow",
|
||||
guarantor1PassportSerie: "I-DZ",
|
||||
guarantor1PassportNumber: "112233",
|
||||
guarantor1CardNumber: "4999999999999999",
|
||||
guarantor1CardName: "MAKSAT SAPAROW",
|
||||
guarantor1CardExpMonth: "10",
|
||||
guarantor1CardExpYear: "2027",
|
||||
guarantor1Salary: 2500,
|
||||
},
|
||||
{
|
||||
id: "LOM-0007",
|
||||
loanType: "Awtoulag karzy",
|
||||
createdAt: "2025-02-01 13:45",
|
||||
region: "Aşgabat",
|
||||
branch: "Garaşsyzlyk şahamçasy",
|
||||
firstName: "Myrat",
|
||||
lastName: "Ataýew",
|
||||
phone: "+99362789012",
|
||||
status: "pending",
|
||||
loanAmount: 35000,
|
||||
patronicName: "Batyrowiç",
|
||||
education: "high",
|
||||
marriageStatus: "MARRIED",
|
||||
dateOfBirth: "1989-09-22",
|
||||
residence: "Aşgabat, Çandybil köçesi, 45",
|
||||
passportSerie: "II-DZ",
|
||||
passportNumber: "334455",
|
||||
passportDateOfIssue: "2015-12-12",
|
||||
passportGivenBy: "Aşgabat şäheriniň Içeri işler müdirligi",
|
||||
workCompany: "Türkmenhowaýollar",
|
||||
position: "Sürüji",
|
||||
salary: 2800,
|
||||
workStartedAt: "2017-04-01",
|
||||
cardNumber: "4111111111112222",
|
||||
cardName: "MYRAT ATAÝEW",
|
||||
cardExpMonth: "08",
|
||||
cardExpYear: "2027",
|
||||
},
|
||||
];
|
||||
export async function fetchLoanOrderMobiles(params: LoanOrdersParams = {}, signal?: AbortSignal): Promise<LoanOrdersResponse> {
|
||||
const { page, perPage, limit, search, region, status, branch, branch_id, createdById, userId, user_id, archived } = params;
|
||||
const branchId = branch || branch_id;
|
||||
const uid = createdById || userId || user_id;
|
||||
|
||||
let mockStore = [...MOCK_DATA];
|
||||
let nextId = 8;
|
||||
|
||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
function applyMockFilters(params: LoanOrderMobileListParams): PaginatedResponse<LoanOrderMobile> {
|
||||
const page = params.page ?? 1;
|
||||
const perPage = params.perPage ?? 25;
|
||||
|
||||
let result = [...mockStore];
|
||||
|
||||
if (params.search) {
|
||||
const q = params.search.toLowerCase();
|
||||
result = result.filter(
|
||||
(r) =>
|
||||
r.firstName.toLowerCase().includes(q) ||
|
||||
r.lastName.toLowerCase().includes(q) ||
|
||||
r.phone.includes(q) ||
|
||||
r.id.toLowerCase().includes(q),
|
||||
);
|
||||
}
|
||||
if (params.region) result = result.filter((r) => r.region === params.region);
|
||||
if (params.status) result = result.filter((r) => r.status === params.status);
|
||||
if (params.branch) result = result.filter((r) => r.branch === params.branch);
|
||||
|
||||
const total = result.length;
|
||||
const start = (page - 1) * perPage;
|
||||
|
||||
return { data: result.slice(start, start + perPage), total };
|
||||
}
|
||||
|
||||
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchLoanOrderMobiles(params: LoanOrderMobileListParams): Promise<PaginatedResponse<LoanOrderMobile>> {
|
||||
if (true) {
|
||||
await delay(500);
|
||||
return applyMockFilters(params);
|
||||
}
|
||||
const { data } = await apiClient.get<PaginatedResponse<LoanOrderMobile>>("/loan-order-mobiles", { params });
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteLoanOrderMobile(id: string): Promise<void> {
|
||||
await delay(300);
|
||||
mockStore = mockStore.filter((r) => r.id !== id);
|
||||
}
|
||||
|
||||
export async function getLoanOrderMobileById(id: string): Promise<LoanOrderMobile> {
|
||||
await delay(300);
|
||||
const order = mockStore.find((r) => r.id === id);
|
||||
if (!order) throw new Error("Not found");
|
||||
return { ...order };
|
||||
}
|
||||
|
||||
export async function createLoanOrderMobile(payload: LoanOrderMobilePayload): Promise<LoanOrderMobile> {
|
||||
await delay(500);
|
||||
const newOrder: LoanOrderMobile = {
|
||||
...payload,
|
||||
id: `LOM-${String(nextId++).padStart(4, "0")}`,
|
||||
createdAt: new Date().toISOString().slice(0, 16).replace("T", " "),
|
||||
status: payload.status as LoanOrderMobileStatus,
|
||||
const { data } = await apiClient.get<LoanOrdersListResponse>("/loan-orders/mobile", {
|
||||
params: {
|
||||
page: page ?? 1,
|
||||
limit: perPage ?? limit ?? 25,
|
||||
search: search || undefined,
|
||||
region: region || undefined,
|
||||
status: status || undefined,
|
||||
branch_id: branchId || undefined,
|
||||
user_id: uid || undefined,
|
||||
archived: archived || undefined,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
const orders = (data.loanOrders ?? []).map(mapBackendToUI);
|
||||
return {
|
||||
data: orders,
|
||||
total: data.count ?? orders.length,
|
||||
page: page ?? 1,
|
||||
perPage: perPage ?? limit ?? 25,
|
||||
};
|
||||
mockStore = [newOrder, ...mockStore];
|
||||
return newOrder;
|
||||
}
|
||||
|
||||
export async function updateLoanOrderMobile(id: string, payload: Partial<LoanOrderMobilePayload>): Promise<LoanOrderMobile> {
|
||||
await delay(500);
|
||||
const idx = mockStore.findIndex((r) => r.id === id);
|
||||
if (idx === -1) throw new Error("Not found");
|
||||
const updated = { ...mockStore[idx], ...payload } as LoanOrderMobile;
|
||||
mockStore = mockStore.map((r) => (r.id === id ? updated : r));
|
||||
return updated;
|
||||
}
|
||||
|
||||
// ─── Branch options by region ─────────────────────────────────────────────────
|
||||
// ─── Branch options by region (Fallback) ──────────────────────────────────────
|
||||
|
||||
export const BRANCHES_BY_REGION_MOBILE: Record<string, { value: string; label: string }[]> = {
|
||||
Aşgabat: [
|
||||
{ value: "Merkezi şahamça", label: "Merkezi şahamça" },
|
||||
{ value: "Merkezi şahamça", label: "Merkezi şahamçaaaaaaaaaaaaaaaaaa" },
|
||||
{ value: "Garaşsyzlyk şahamçasy", label: "Garaşsyzlyk şahamçasy" },
|
||||
{ value: "Bitarap şahamça", label: "Bitarap şahamça" },
|
||||
{ value: "Aşgabat-1 şahamçasy", label: "Aşgabat-1 şahamçasy" },
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
fetchLoanOrderMobiles,
|
||||
@@ -8,40 +8,42 @@ import {
|
||||
getLoanOrderMobileById,
|
||||
createLoanOrderMobile,
|
||||
updateLoanOrderMobile,
|
||||
patchLoanOrderMobile,
|
||||
type LoanOrderMobileListParams,
|
||||
type LoanOrderMobilePayload,
|
||||
} from '../api/loanOrderMobilesApi'
|
||||
} from "../api/loanOrderMobilesApi";
|
||||
|
||||
// ─── Query keys ────────────────────────────────────────────────────────────────
|
||||
|
||||
export const loanOrderMobileKeys = {
|
||||
all: ['loanOrderMobiles'] as const,
|
||||
lists: () => [...loanOrderMobileKeys.all, 'list'] as const,
|
||||
all: ["loanOrderMobiles"] as const,
|
||||
lists: () => [...loanOrderMobileKeys.all, "list"] as const,
|
||||
list: (params: LoanOrderMobileListParams) => [...loanOrderMobileKeys.lists(), params] as const,
|
||||
details: () => [...loanOrderMobileKeys.all, 'detail'] as const,
|
||||
details: () => [...loanOrderMobileKeys.all, "detail"] as const,
|
||||
detail: (id: string) => [...loanOrderMobileKeys.details(), id] as const,
|
||||
}
|
||||
};
|
||||
|
||||
// ─── Hooks ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useLoanOrderMobiles(params: LoanOrderMobileListParams) {
|
||||
return useQuery({
|
||||
queryKey: loanOrderMobileKeys.list(params),
|
||||
queryFn: () => fetchLoanOrderMobiles(params),
|
||||
})
|
||||
queryFn: ({ signal }) => fetchLoanOrderMobiles(params, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteLoanOrderMobile() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => deleteLoanOrderMobile(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() })
|
||||
toast.success(t('loanOrderMobiles.deleteSuccess', 'Sargyt üstünlikli pozuldy'))
|
||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() });
|
||||
toast.success(t("loanOrderMobiles.deleteSuccess", "Sargyt üstünlikli pozuldy"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useLoanOrderMobileById(id: string) {
|
||||
@@ -49,33 +51,47 @@ export function useLoanOrderMobileById(id: string) {
|
||||
queryKey: loanOrderMobileKeys.detail(id),
|
||||
queryFn: () => getLoanOrderMobileById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateLoanOrderMobile() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: LoanOrderMobilePayload) => createLoanOrderMobile(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() })
|
||||
toast.success(t('loanOrderMobiles.createSuccess', 'Sargyt üstünlikli döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() });
|
||||
toast.success(t("loanOrderMobiles.createSuccess", "Sargyt üstünlikli döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateLoanOrderMobile() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, payload }: { id: string; payload: Partial<LoanOrderMobilePayload> }) =>
|
||||
updateLoanOrderMobile(id, payload),
|
||||
mutationFn: ({ id, payload }: { id: string; payload: Partial<LoanOrderMobilePayload> }) => updateLoanOrderMobile(id, payload),
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.detail(variables.id) })
|
||||
toast.success(t('loanOrderMobiles.updateSuccess', 'Sargyt üstünlikli üýtgedildi'))
|
||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() });
|
||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.detail(variables.id) });
|
||||
toast.success(t("loanOrderMobiles.updateSuccess", "Sargyt üstünlikli üýtgedildi"));
|
||||
},
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function usePatchLoanOrderMobile() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, payload }: { id: string; payload: Partial<LoanOrderMobilePayload> | Record<string, unknown> }) =>
|
||||
patchLoanOrderMobile(id, payload),
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() });
|
||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.detail(variables.id) });
|
||||
toast.success(t("loanOrderMobiles.updateSuccess", "Sargyt üstünlikli üýtgedildi"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,293 +1,3 @@
|
||||
import { z } from "zod";
|
||||
import i18next from "i18next";
|
||||
|
||||
const fileRequired = z.custom<File>((val) => val instanceof File, "validation.requiredFile");
|
||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
||||
|
||||
export const loanOrderMobileFormSchema = z.object({
|
||||
status: z.string().min(1, "validation.required"),
|
||||
loanType: z.string().min(1, "validation.required"),
|
||||
region: z.string().min(1, "validation.required"),
|
||||
branch: z.string().min(1, "validation.required"),
|
||||
firstName: z.string().min(1, "validation.required"),
|
||||
lastName: z.string().min(1, "validation.required"),
|
||||
patronicName: z.string().optional(),
|
||||
education: z.string().min(1, "validation.required"),
|
||||
marriageStatus: z.string().min(1, "validation.required"),
|
||||
dateOfBirth: z.string().min(1, "validation.required"),
|
||||
residence: z.string().min(1, "validation.required"),
|
||||
currentResidence: z.string().optional(),
|
||||
passportSerie: z.string().min(1, "validation.required"),
|
||||
passportNumber: z.string().min(1, "validation.required"),
|
||||
passportDateOfIssue: z.string().min(1, "validation.required"),
|
||||
passportGivenBy: z.string().min(1, "validation.required"),
|
||||
bornPlace: z.string().optional(),
|
||||
email: z.string().optional(),
|
||||
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" },
|
||||
),
|
||||
phoneAdditional: 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(),
|
||||
homePhone: z
|
||||
.string()
|
||||
.refine(
|
||||
(val) => {
|
||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
||||
return val.replace(/\D/g, "").length === 8;
|
||||
},
|
||||
{ message: "validation.invalidPhone" },
|
||||
)
|
||||
.refine(
|
||||
(val) => {
|
||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
||||
return VALID_PHONE_PREFIXES.includes(val.replace(/\D/g, "").slice(0, 2));
|
||||
},
|
||||
{ message: "validation.invalidPhonePrefix" },
|
||||
)
|
||||
.optional(),
|
||||
workCompany: z.string().min(1, "validation.required"),
|
||||
workHrPhone: z
|
||||
.string()
|
||||
.refine(
|
||||
(val) => {
|
||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
||||
return val.replace(/\D/g, "").length === 8;
|
||||
},
|
||||
{ message: "validation.invalidPhone" },
|
||||
)
|
||||
.refine(
|
||||
(val) => {
|
||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
||||
return VALID_PHONE_PREFIXES.includes(val.replace(/\D/g, "").slice(0, 2));
|
||||
},
|
||||
{ message: "validation.invalidPhonePrefix" },
|
||||
)
|
||||
.optional(),
|
||||
workRegion: z.string().optional(),
|
||||
workProvince: z.string().optional(),
|
||||
position: z.string().min(1, "validation.required"),
|
||||
salary: z.string().min(1, "validation.required"),
|
||||
workStartedAt: 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(),
|
||||
note: z.string().optional(),
|
||||
loanAmount: z.string().min(1, "validation.required"),
|
||||
loanHistory: z.string().optional(),
|
||||
cardNumber: z.string().min(1, "validation.required"),
|
||||
cardName: z.string().min(1, "validation.required"),
|
||||
cardExpMonth: z.string().min(1, "validation.required"),
|
||||
cardExpYear: z.string().min(1, "validation.required"),
|
||||
guarantor1Name: z.string().min(1, "validation.required"),
|
||||
guarantor1Surname: z.string().min(1, "validation.required"),
|
||||
guarantor1Patronic: z.string().optional(),
|
||||
guarantor1PassportSerie: z.string().min(1, "validation.required"),
|
||||
guarantor1PassportNumber: z.string().min(1, "validation.required"),
|
||||
guarantor1CardNumber: z.string().min(1, "validation.required"),
|
||||
guarantor1CardName: z.string().min(1, "validation.required"),
|
||||
guarantor1CardExpMonth: z.string().min(1, "validation.required"),
|
||||
guarantor1CardExpYear: z.string().min(1, "validation.required"),
|
||||
guarantor1Salary: z.string().min(1, "validation.required"),
|
||||
});
|
||||
|
||||
export type LoanOrderMobileFormData = z.infer<typeof loanOrderMobileFormSchema>;
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<LoanOrderMobileFormData>>> = {
|
||||
0: loanOrderMobileFormSchema.pick({ loanType: true, loanAmount: true, region: true, branch: true }),
|
||||
1: loanOrderMobileFormSchema.pick({
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
education: true,
|
||||
marriageStatus: true,
|
||||
dateOfBirth: true,
|
||||
residence: true,
|
||||
passportSerie: true,
|
||||
passportNumber: true,
|
||||
passportDateOfIssue: true,
|
||||
passportGivenBy: true,
|
||||
}),
|
||||
2: loanOrderMobileFormSchema.pick({
|
||||
phone: true,
|
||||
phoneAdditional: true,
|
||||
homePhone: true,
|
||||
workCompany: true,
|
||||
position: true,
|
||||
salary: true,
|
||||
workStartedAt: true,
|
||||
workHrPhone: true,
|
||||
}),
|
||||
3: loanOrderMobileFormSchema.pick({
|
||||
cardNumber: true,
|
||||
cardName: true,
|
||||
cardExpMonth: true,
|
||||
cardExpYear: true,
|
||||
guarantor1Name: true,
|
||||
guarantor1Surname: true,
|
||||
guarantor1PassportSerie: true,
|
||||
guarantor1PassportNumber: true,
|
||||
guarantor1CardNumber: true,
|
||||
guarantor1CardName: true,
|
||||
guarantor1CardExpMonth: true,
|
||||
guarantor1CardExpYear: true,
|
||||
guarantor1Salary: true,
|
||||
}),
|
||||
4: z.object({
|
||||
passportPage1: fileRequired,
|
||||
passportPage23: fileRequired,
|
||||
}),
|
||||
};
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: LoanOrderMobileFormData,
|
||||
mode: "create" | "edit",
|
||||
): Partial<Record<keyof LoanOrderMobileFormData, string>> {
|
||||
if (stepIndex === 4 && mode === "edit") return {};
|
||||
const schema = stepSchemas[stepIndex];
|
||||
const result = schema.safeParse(form);
|
||||
if (result.success) return {};
|
||||
const errors: Partial<Record<keyof LoanOrderMobileFormData, string>> = {};
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof LoanOrderMobileFormData;
|
||||
if (!errors[key]) {
|
||||
const msg = issue.message;
|
||||
errors[key] = msg.startsWith("validation.") ? i18next.t(msg, msg) : msg;
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
export const DEFAULT_FORM_VALUES: LoanOrderMobileFormData = {
|
||||
status: "pending",
|
||||
loanType: "",
|
||||
region: "Aşgabat",
|
||||
branch: "",
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
patronicName: "",
|
||||
education: "",
|
||||
marriageStatus: "",
|
||||
dateOfBirth: "",
|
||||
residence: "",
|
||||
currentResidence: "",
|
||||
passportSerie: "",
|
||||
passportNumber: "",
|
||||
passportDateOfIssue: "",
|
||||
passportGivenBy: "",
|
||||
bornPlace: "",
|
||||
email: "",
|
||||
phone: "",
|
||||
phoneAdditional: "",
|
||||
homePhone: "",
|
||||
workCompany: "",
|
||||
workHrPhone: "",
|
||||
workRegion: "Aşgabat",
|
||||
workProvince: "",
|
||||
position: "",
|
||||
salary: "",
|
||||
workStartedAt: "",
|
||||
passportPage1: null,
|
||||
passportPage23: null,
|
||||
passportPage89: null,
|
||||
passportPage32: null,
|
||||
note: "",
|
||||
loanAmount: "",
|
||||
loanHistory: "",
|
||||
cardNumber: "",
|
||||
cardName: "",
|
||||
cardExpMonth: "",
|
||||
cardExpYear: "",
|
||||
guarantor1Name: "",
|
||||
guarantor1Surname: "",
|
||||
guarantor1Patronic: "",
|
||||
guarantor1PassportSerie: "",
|
||||
guarantor1PassportNumber: "",
|
||||
guarantor1CardNumber: "",
|
||||
guarantor1CardName: "",
|
||||
guarantor1CardExpMonth: "",
|
||||
guarantor1CardExpYear: "",
|
||||
guarantor1Salary: "",
|
||||
};
|
||||
|
||||
export function buildPayload(data: LoanOrderMobileFormData) {
|
||||
return {
|
||||
status: data.status,
|
||||
loanType: data.loanType,
|
||||
region: data.region,
|
||||
branch: data.branch,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
patronicName: data.patronicName || undefined,
|
||||
education: data.education,
|
||||
marriageStatus: data.marriageStatus,
|
||||
dateOfBirth: data.dateOfBirth,
|
||||
residence: data.residence,
|
||||
currentResidence: data.currentResidence || undefined,
|
||||
passportSerie: data.passportSerie,
|
||||
passportNumber: data.passportNumber,
|
||||
passportDateOfIssue: data.passportDateOfIssue,
|
||||
passportGivenBy: data.passportGivenBy,
|
||||
bornPlace: data.bornPlace || undefined,
|
||||
email: data.email || undefined,
|
||||
phone: data.phone,
|
||||
phoneAdditional: data.phoneAdditional || undefined,
|
||||
homePhone: data.homePhone || undefined,
|
||||
workCompany: data.workCompany,
|
||||
workHrPhone: data.workHrPhone || undefined,
|
||||
workRegion: data.workRegion || undefined,
|
||||
workProvince: data.workProvince || undefined,
|
||||
position: data.position,
|
||||
salary: Number(data.salary),
|
||||
workStartedAt: data.workStartedAt,
|
||||
note: data.note || undefined,
|
||||
loanAmount: Number(data.loanAmount) || undefined,
|
||||
loanHistory: data.loanHistory || undefined,
|
||||
cardNumber: data.cardNumber || undefined,
|
||||
cardName: data.cardName || undefined,
|
||||
cardExpMonth: data.cardExpMonth || undefined,
|
||||
cardExpYear: data.cardExpYear || undefined,
|
||||
guarantor1Name: data.guarantor1Name || undefined,
|
||||
guarantor1Surname: data.guarantor1Surname || undefined,
|
||||
guarantor1Patronic: data.guarantor1Patronic || undefined,
|
||||
guarantor1PassportSerie: data.guarantor1PassportSerie || undefined,
|
||||
guarantor1PassportNumber: data.guarantor1PassportNumber || undefined,
|
||||
guarantor1CardNumber: data.guarantor1CardNumber || undefined,
|
||||
guarantor1CardName: data.guarantor1CardName || undefined,
|
||||
guarantor1CardExpMonth: data.guarantor1CardExpMonth || undefined,
|
||||
guarantor1CardExpYear: data.guarantor1CardExpYear || undefined,
|
||||
guarantor1Salary: Number(data.guarantor1Salary) || undefined,
|
||||
};
|
||||
}
|
||||
export * from "@/features/loanOrders/schemas/loanOrder.schema";
|
||||
export type { LoanOrderFormData as LoanOrderMobileFormData } from "@/features/loanOrders/schemas/loanOrder.schema";
|
||||
export { loanOrderFormSchema as loanOrderMobileFormSchema } from "@/features/loanOrders/schemas/loanOrder.schema";
|
||||
|
||||
@@ -8,52 +8,81 @@ import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
|
||||
export type LoanOrderStatus = StatusValue;
|
||||
|
||||
export interface LoanOrderUser {
|
||||
id?: number;
|
||||
name?: string;
|
||||
username?: string;
|
||||
phone?: string;
|
||||
email?: string;
|
||||
}
|
||||
|
||||
export interface LoanOrder {
|
||||
id: string;
|
||||
uniqueId?: string | null;
|
||||
source?: string | null;
|
||||
user?: LoanOrderUser | null;
|
||||
loanType: string;
|
||||
createdAt: string;
|
||||
updatedAt?: string | null;
|
||||
region: string;
|
||||
branch: string;
|
||||
branchId?: number | string;
|
||||
loanTypeId?: number | string;
|
||||
workCityId?: number | string;
|
||||
workProvinceId?: number | string;
|
||||
createdById?: number | string;
|
||||
createdBy?: string | null;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
patronicName?: string | null;
|
||||
fullName?: string | null;
|
||||
phone: string;
|
||||
homePhone?: string | null;
|
||||
phoneAdditional?: string | null;
|
||||
status: LoanOrderStatus;
|
||||
note?: string | null;
|
||||
notes?: string | null;
|
||||
|
||||
loanAmount?: number | null;
|
||||
loanHistory?: string | null;
|
||||
patronicName?: string | null;
|
||||
loanOrderRequiredDoc?: { id: number; name: string } | null;
|
||||
satisfiable?: string | null;
|
||||
|
||||
education?: string | null;
|
||||
marriageStatus?: string | null;
|
||||
maritalStatus?: string | null;
|
||||
dateOfBirth?: string | null;
|
||||
birthDate?: string | null;
|
||||
residence?: string | null;
|
||||
registeredAddress?: string | null;
|
||||
currentResidence?: string | null;
|
||||
currentAddress?: string | null;
|
||||
|
||||
passportSerie?: string | null;
|
||||
passportNumber?: string | null;
|
||||
passportDateOfIssue?: string | null;
|
||||
passportGivenBy?: string | null;
|
||||
passportIssuedBy?: string | null;
|
||||
bornPlace?: string | null;
|
||||
passportBirthPlace?: string | null;
|
||||
passportPage1Url?: string | null;
|
||||
passportPage23Url?: string | null;
|
||||
passportPage89Url?: string | null;
|
||||
passportPage32Url?: string | null;
|
||||
|
||||
email?: string | null;
|
||||
phoneAdditional?: string | null;
|
||||
homePhone?: string | null;
|
||||
|
||||
workCompany?: string | null;
|
||||
employer?: string | null;
|
||||
workHrPhone?: string | null;
|
||||
deptPhone?: string | null;
|
||||
workRegion?: string | null;
|
||||
workProvince?: string | null;
|
||||
workCity?: string | null;
|
||||
position?: string | null;
|
||||
salary?: number | null;
|
||||
workStartedAt?: string | null;
|
||||
employedSince?: string | null;
|
||||
|
||||
cardNumber?: string | null;
|
||||
cardName?: string | null;
|
||||
@@ -70,6 +99,7 @@ export interface LoanOrder {
|
||||
guarantor1CardExpMonth?: string | null;
|
||||
guarantor1CardExpYear?: string | null;
|
||||
guarantor1Salary?: number | null;
|
||||
guarantor1Note?: string | null;
|
||||
|
||||
guarantor2Name?: string | null;
|
||||
guarantor2Surname?: string | null;
|
||||
@@ -82,20 +112,13 @@ export interface LoanOrder {
|
||||
guarantor2CardExpYear?: string | null;
|
||||
guarantor2Note?: string | null;
|
||||
|
||||
loanCardNumber?: string | null;
|
||||
loanCardName?: string | null;
|
||||
loanCardMonth?: string | null;
|
||||
loanCardYear?: string | null;
|
||||
|
||||
amount?: number | null;
|
||||
createdBy?: string | null;
|
||||
fullName?: string | null;
|
||||
maritalStatus?: string | null;
|
||||
birthDate?: string | null;
|
||||
registeredAddress?: string | null;
|
||||
currentAddress?: string | null;
|
||||
phoneAlt?: string | null;
|
||||
employer?: string | null;
|
||||
deptPhone?: string | null;
|
||||
workCity?: string | null;
|
||||
employedSince?: string | null;
|
||||
passportIssuedBy?: string | null;
|
||||
passportBirthPlace?: string | null;
|
||||
}
|
||||
|
||||
export interface LoanOrdersParams {
|
||||
@@ -103,9 +126,14 @@ export interface LoanOrdersParams {
|
||||
region?: string;
|
||||
status?: LoanOrderStatus | "";
|
||||
branch?: string;
|
||||
branch_id?: string | number;
|
||||
createdById?: string | number;
|
||||
userId?: string | number;
|
||||
user_id?: string | number;
|
||||
archived?: string;
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface LoanOrdersResponse {
|
||||
@@ -120,7 +148,7 @@ export interface LoanOrderPayload {
|
||||
loanType: string;
|
||||
region: string;
|
||||
branch: string;
|
||||
userId: string;
|
||||
userId?: string | number;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
patronicName?: string;
|
||||
@@ -181,13 +209,14 @@ export interface LoanOrderPayload {
|
||||
passportTwo?: string;
|
||||
passportThree?: string;
|
||||
passportFour?: string;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
// ─── Backend types ─────────────────────────────────────────────────────────────
|
||||
|
||||
type NestedLocalized = { id: number; name: LocalizedText | string };
|
||||
export type NestedLocalized = { id: number; name: LocalizedText | string };
|
||||
|
||||
interface BackendLoanOrder {
|
||||
export interface BackendLoanOrder {
|
||||
id?: number | string;
|
||||
uniqueId?: string | null;
|
||||
region?: string | null;
|
||||
@@ -196,6 +225,7 @@ interface BackendLoanOrder {
|
||||
branchName?: LocalizedText | string | null;
|
||||
loanType?: NestedLocalized | number | string | null;
|
||||
loanTypeName?: LocalizedText | string | null;
|
||||
user?: LoanOrderUser | null;
|
||||
userId?: number | null;
|
||||
userName?: string | null;
|
||||
customerName?: string | null;
|
||||
@@ -236,6 +266,7 @@ interface BackendLoanOrder {
|
||||
workCompanyAccountantNumber?: string | null;
|
||||
workRegion?: string | null;
|
||||
workProvinceId?: number | null;
|
||||
workProvince?: NestedLocalized | number | string | null;
|
||||
workProvinceName?: LocalizedText | string | null;
|
||||
workSalary?: string | number | null;
|
||||
workPosition?: string | null;
|
||||
@@ -243,6 +274,7 @@ interface BackendLoanOrder {
|
||||
satisfiable?: string | null;
|
||||
source?: string | null;
|
||||
loanOrderRequiredDocId?: number | null;
|
||||
loanOrderRequiredDoc?: { id: number; name: string } | null;
|
||||
guarantorName?: string | null;
|
||||
guarantorSurname?: string | null;
|
||||
guarantorPatronicName?: string | null;
|
||||
@@ -265,14 +297,14 @@ interface BackendLoanOrder {
|
||||
guarantor2Note?: string | null;
|
||||
}
|
||||
|
||||
interface LoanOrdersListResponse {
|
||||
export interface LoanOrdersListResponse {
|
||||
count: number;
|
||||
loanOrders: BackendLoanOrder[];
|
||||
}
|
||||
|
||||
// ─── Mapping helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
function resolveLocalizedName(name: LocalizedText | string | null | undefined): string {
|
||||
export function resolveLocalizedName(name: LocalizedText | string | null | undefined): string {
|
||||
if (!name) return "";
|
||||
if (typeof name === "string") return name;
|
||||
const lang = i18next.language || "en";
|
||||
@@ -281,7 +313,7 @@ function resolveLocalizedName(name: LocalizedText | string | null | undefined):
|
||||
}
|
||||
|
||||
/** Extract a display name from a nested `{id, name}` object, a `LocalizedText`, or a plain string/number. */
|
||||
function resolveNestedName(value: NestedLocalized | LocalizedText | string | number | null | undefined): string {
|
||||
export function resolveNestedName(value: NestedLocalized | LocalizedText | string | number | null | undefined): string {
|
||||
if (value === null || value === undefined || value === "") return "";
|
||||
if (typeof value === "string") return value;
|
||||
if (typeof value === "number") return "";
|
||||
@@ -290,7 +322,7 @@ function resolveNestedName(value: NestedLocalized | LocalizedText | string | num
|
||||
}
|
||||
|
||||
/** Extract a numeric ID from a nested `{id}` object, a number, or a string. */
|
||||
function resolveNestedId(value: NestedLocalized | number | string | null | undefined): number | null {
|
||||
export function resolveNestedId(value: NestedLocalized | number | string | null | undefined): number | null {
|
||||
if (value === null || value === undefined || value === "") return null;
|
||||
if (typeof value === "number") return value;
|
||||
if (typeof value === "string") {
|
||||
@@ -301,58 +333,78 @@ function resolveNestedId(value: NestedLocalized | number | string | null | undef
|
||||
return null;
|
||||
}
|
||||
|
||||
function toNum(value: string | number | null | undefined): number | null {
|
||||
export function toNum(value: string | number | null | undefined): number | null {
|
||||
if (value === null || value === undefined || value === "") return null;
|
||||
const n = Number(value);
|
||||
return Number.isNaN(n) ? null : n;
|
||||
}
|
||||
|
||||
function mapBackendToUI(order: BackendLoanOrder): LoanOrder {
|
||||
export function mapBackendToUI(order: BackendLoanOrder): LoanOrder {
|
||||
const rawStatus = order.status ?? "";
|
||||
const status: LoanOrderStatus = isStatusValue(rawStatus) ? rawStatus : "pending";
|
||||
|
||||
return {
|
||||
id: String(order.id ?? order.uniqueId ?? ""),
|
||||
uniqueId: order.uniqueId ?? "",
|
||||
source: order.source ?? "web",
|
||||
user: order.user ?? (order.userId ? { id: order.userId, name: order.userName ?? "" } : undefined),
|
||||
loanType: resolveNestedName(order.loanType) || resolveLocalizedName(order.loanTypeName),
|
||||
createdAt: order.createdAt ?? "",
|
||||
updatedAt: order.updatedAt ?? "",
|
||||
region: order.region ?? "",
|
||||
branch: resolveNestedName(order.branch) || resolveLocalizedName(order.branchName),
|
||||
branchId: resolveNestedId(order.branch) ?? order.branchId ?? undefined,
|
||||
loanTypeId: resolveNestedId(order.loanType) ?? undefined,
|
||||
workCityId: order.workProvinceId ?? undefined,
|
||||
createdById: order.userId ?? undefined,
|
||||
workCityId: resolveNestedId(order.workProvince) ?? order.workProvinceId ?? undefined,
|
||||
workProvinceId: resolveNestedId(order.workProvince) ?? order.workProvinceId ?? undefined,
|
||||
createdById: order.user?.id ?? order.userId ?? undefined,
|
||||
createdBy: order.user?.name ?? order.userName ?? "",
|
||||
firstName: order.customerName ?? "",
|
||||
lastName: order.customerSurname ?? "",
|
||||
patronicName: order.customerPatronicName ?? "",
|
||||
fullName: [order.customerName, order.customerSurname].filter(Boolean).join(" "),
|
||||
phone: formatFromApiPhone(order.phone ?? order.phoneHome ?? ""),
|
||||
homePhone: formatFromApiPhone(order.phoneHome),
|
||||
phoneAdditional: formatFromApiPhone(order.phoneAdditional),
|
||||
status,
|
||||
note: order.notes ?? "",
|
||||
notes: order.notes ?? "",
|
||||
loanAmount: toNum(order.loanAmount),
|
||||
loanHistory: order.loanOrderRequiredDoc?.name || (order.loanOrderRequiredDocId ? String(order.loanOrderRequiredDocId) : ""),
|
||||
loanOrderRequiredDoc: order.loanOrderRequiredDoc ?? undefined,
|
||||
satisfiable: order.satisfiable ?? "",
|
||||
dateOfBirth: formatFromApiDate(order.bornAt),
|
||||
birthDate: formatFromApiDate(order.bornAt),
|
||||
bornPlace: order.bornPlace ?? "",
|
||||
passportBirthPlace: order.bornPlace ?? "",
|
||||
education: order.education ?? "",
|
||||
marriageStatus: order.marriageStatus ?? "",
|
||||
maritalStatus: order.marriageStatus ?? "",
|
||||
residence: order.passportAddress ?? "",
|
||||
registeredAddress: order.passportAddress ?? "",
|
||||
currentResidence: order.realAddress ?? "",
|
||||
currentAddress: order.realAddress ?? "",
|
||||
email: order.email ?? "",
|
||||
passportSerie: order.passportSerie ?? "",
|
||||
passportNumber: order.passportId ?? "",
|
||||
passportDateOfIssue: formatFromApiDate(order.passportGivenAt),
|
||||
passportGivenBy: order.passportGivenBy ?? "",
|
||||
passportIssuedBy: order.passportGivenBy ?? "",
|
||||
passportPage1Url: order.passportOne ?? "",
|
||||
passportPage23Url: order.passportTwo ?? "",
|
||||
passportPage89Url: order.passportThree ?? "",
|
||||
passportPage32Url: order.passportFour ?? "",
|
||||
workCompany: order.workCompany ?? "",
|
||||
employer: order.workCompany ?? "",
|
||||
workHrPhone: formatFromApiPhone(order.workCompanyAccountantNumber),
|
||||
deptPhone: formatFromApiPhone(order.workCompanyAccountantNumber),
|
||||
workRegion: order.workRegion ?? "",
|
||||
workProvince: resolveLocalizedName(order.workProvinceName),
|
||||
workCity: resolveLocalizedName(order.workProvinceName),
|
||||
workProvince: resolveNestedName(order.workProvince) || resolveLocalizedName(order.workProvinceName),
|
||||
workCity: resolveNestedName(order.workProvince) || resolveLocalizedName(order.workProvinceName),
|
||||
salary: toNum(order.workSalary),
|
||||
position: order.workPosition ?? "",
|
||||
workStartedAt: formatFromApiDate(order.workStartedAt),
|
||||
employedSince: formatFromApiDate(order.workStartedAt),
|
||||
cardNumber: order.cardNumber ?? order.loanCardNumber ?? "",
|
||||
cardName: order.cardName ?? order.loanCardName ?? "",
|
||||
cardExpMonth: order.cardMonth ?? order.loanCardMonth ?? "",
|
||||
@@ -367,6 +419,7 @@ function mapBackendToUI(order: BackendLoanOrder): LoanOrder {
|
||||
guarantor1CardExpMonth: order.guarantorCardMonth ?? "",
|
||||
guarantor1CardExpYear: order.guarantorCardYear ?? "",
|
||||
guarantor1Salary: null,
|
||||
guarantor1Note: order.guarantorNote ?? "",
|
||||
guarantor2Name: order.guarantor2Name ?? "",
|
||||
guarantor2Surname: order.guarantor2Surname ?? "",
|
||||
guarantor2Patronic: order.guarantor2PatronicName ?? "",
|
||||
@@ -377,23 +430,14 @@ function mapBackendToUI(order: BackendLoanOrder): LoanOrder {
|
||||
guarantor2CardExpMonth: order.guarantor2CardMonth ?? "",
|
||||
guarantor2CardExpYear: order.guarantor2CardYear ?? "",
|
||||
guarantor2Note: order.guarantor2Note ?? "",
|
||||
loanHistory: order.loanOrderRequiredDocId ? String(order.loanOrderRequiredDocId) : "",
|
||||
createdBy: order.userName ?? "",
|
||||
fullName: [order.customerName, order.customerSurname].filter(Boolean).join(" "),
|
||||
registeredAddress: order.passportAddress ?? "",
|
||||
currentAddress: order.realAddress ?? "",
|
||||
birthDate: formatFromApiDate(order.bornAt),
|
||||
maritalStatus: order.marriageStatus ?? "",
|
||||
phoneAlt: formatFromApiPhone(order.phoneAdditional),
|
||||
employer: order.workCompany ?? "",
|
||||
deptPhone: formatFromApiPhone(order.workCompanyAccountantNumber),
|
||||
employedSince: formatFromApiDate(order.workStartedAt),
|
||||
passportIssuedBy: order.passportGivenBy ?? "",
|
||||
passportBirthPlace: order.bornPlace ?? "",
|
||||
loanCardNumber: order.loanCardNumber ?? "",
|
||||
loanCardName: order.loanCardName ?? "",
|
||||
loanCardMonth: order.loanCardMonth ?? "",
|
||||
loanCardYear: order.loanCardYear ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
function mapPayloadToBackend(payload: LoanOrderPayload | Partial<LoanOrderPayload>): Record<string, unknown> {
|
||||
export function mapPayloadToBackend(payload: LoanOrderPayload | Partial<LoanOrderPayload>): Record<string, unknown> {
|
||||
return {
|
||||
customerName: payload.firstName ?? "",
|
||||
customerSurname: payload.lastName ?? "",
|
||||
@@ -458,25 +502,28 @@ function mapPayloadToBackend(payload: LoanOrderPayload | Partial<LoanOrderPayloa
|
||||
passportFour: payload.passportFour || "",
|
||||
status: payload.status ?? "pending",
|
||||
satisfiable: "yes",
|
||||
source: "web",
|
||||
source: payload.source ?? "web",
|
||||
loanOrderRequiredDocId: payload.loanHistory ? Number(payload.loanHistory) : 0,
|
||||
userId: toNum(payload.userId) ?? 0,
|
||||
uniqueId: "541-shbfnkj",
|
||||
};
|
||||
}
|
||||
|
||||
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchLoanOrders(params: LoanOrdersParams = {}, signal?: AbortSignal): Promise<LoanOrdersResponse> {
|
||||
const { page, perPage, search, region, status, branch, archived } = params;
|
||||
const { page, perPage, limit, search, region, status, branch, branch_id, createdById, userId, user_id, archived } = params;
|
||||
const branchId = branch || branch_id;
|
||||
const uid = createdById || userId || user_id;
|
||||
|
||||
const { data } = await apiClient.get<LoanOrdersListResponse>("/loan-orders", {
|
||||
params: {
|
||||
page: page ?? 1,
|
||||
limit: perPage ?? 25,
|
||||
limit: perPage ?? limit ?? 25,
|
||||
search: search || undefined,
|
||||
region: region || undefined,
|
||||
status: status || undefined,
|
||||
branch_id: branch || undefined,
|
||||
branch_id: branchId || undefined,
|
||||
user_id: uid || undefined,
|
||||
archived: archived || undefined,
|
||||
},
|
||||
signal,
|
||||
@@ -486,7 +533,7 @@ export async function fetchLoanOrders(params: LoanOrdersParams = {}, signal?: Ab
|
||||
data: orders,
|
||||
total: data.count ?? orders.length,
|
||||
page: page ?? 1,
|
||||
perPage: perPage ?? 25,
|
||||
perPage: perPage ?? limit ?? 25,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -505,6 +552,11 @@ export async function updateLoanOrder(id: string, payload: Partial<LoanOrderPayl
|
||||
return mapBackendToUI(data);
|
||||
}
|
||||
|
||||
export async function patchLoanOrder(id: string, payload: Partial<LoanOrderPayload> | Record<string, unknown>): Promise<LoanOrder> {
|
||||
const { data } = await apiClient.patch<BackendLoanOrder>(`/loan-orders/${id}`, payload);
|
||||
return mapBackendToUI(data);
|
||||
}
|
||||
|
||||
export async function deleteLoanOrder(id: string): Promise<void> {
|
||||
await apiClient.delete(`/loan-orders/${id}`);
|
||||
}
|
||||
|
||||
@@ -13,11 +13,13 @@ export interface AddRoleUserPayload {
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export interface AddPermissionUserPayload {
|
||||
export interface AddPermissionRolePayload {
|
||||
permissionId: number;
|
||||
userId: number;
|
||||
roleId: number;
|
||||
}
|
||||
|
||||
export type AddPermissionUserPayload = AddPermissionRolePayload;
|
||||
|
||||
// Re-export so shared hooks can import from one place
|
||||
export type { BranchListParams, BranchListResponse };
|
||||
|
||||
@@ -67,13 +69,15 @@ export async function postRoleUser(payload: AddRoleUserPayload): Promise<void> {
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /permission-users
|
||||
* Assigns a permission to a user.
|
||||
* POST /permission-roles
|
||||
* Assigns a permission to a role.
|
||||
*/
|
||||
export async function postPermissionUser(payload: AddPermissionUserPayload): Promise<void> {
|
||||
await apiClient.post("/permission-users", payload);
|
||||
export async function postPermissionRole(payload: AddPermissionRolePayload): Promise<void> {
|
||||
await apiClient.post("/permission-roles", payload);
|
||||
}
|
||||
|
||||
export const postPermissionUser = postPermissionRole;
|
||||
|
||||
/**
|
||||
* Proxy for branch list fetching — kept here so shared hooks
|
||||
* don't import directly from the branches feature.
|
||||
|
||||
@@ -4,10 +4,10 @@ import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
postBranchUser,
|
||||
postRoleUser,
|
||||
postPermissionUser,
|
||||
postPermissionRole,
|
||||
type AddBranchUserPayload,
|
||||
type AddRoleUserPayload,
|
||||
type AddPermissionUserPayload,
|
||||
type AddPermissionRolePayload,
|
||||
} from "../api/sharedApi";
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
@@ -43,18 +43,17 @@ export function useAssignRoleToUser() {
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useAssignPermissionToUser ────────────────────────────────────────────────
|
||||
// ─── useAssignPermissionToRole ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* POST /permission-users — assigns a permission to the given staff user and refreshes the profile cache.
|
||||
* `userId` is supplied at mutate time (picked from the staff select).
|
||||
* POST /permission-roles — assigns a permission to the given role and refreshes the profile cache.
|
||||
*/
|
||||
export function useAssignPermissionToUser() {
|
||||
export function useAssignPermissionToRole() {
|
||||
const { t } = useTranslation();
|
||||
const invalidateProfile = useInvalidateProfile();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: AddPermissionUserPayload) => postPermissionUser(payload),
|
||||
mutationFn: (payload: AddPermissionRolePayload) => postPermissionRole(payload),
|
||||
onSuccess: () => {
|
||||
invalidateProfile();
|
||||
toast.success(t("profile.assign.success", "Üstünlikli birikdirildi"));
|
||||
@@ -62,6 +61,8 @@ export function useAssignPermissionToUser() {
|
||||
});
|
||||
}
|
||||
|
||||
export const useAssignPermissionToUser = useAssignPermissionToRole;
|
||||
|
||||
// ─── useAssignBranchToUser ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user