connected api with card balance and and requisites
This commit is contained in:
@@ -16,6 +16,12 @@ export interface AuthUserBranch {
|
||||
name: LocalizedText;
|
||||
}
|
||||
|
||||
export interface AuthUserPermission {
|
||||
id: number;
|
||||
code?: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id?: string | number;
|
||||
name: string;
|
||||
@@ -26,6 +32,7 @@ export interface AuthUser {
|
||||
role?: AuthUserRole;
|
||||
avatar?: string;
|
||||
branches?: AuthUserBranch[];
|
||||
permissions?: AuthUserPermission[];
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -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 ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,114 +1,232 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Download } from "lucide-react";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ColumnMeta } from "@/components/dataTableToolbar";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import type { VisibilityState } from "@tanstack/react-table";
|
||||
import { useCardBalances, useDeleteCardBalance, useDownloadCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
||||
import { type CardBalance } from "@/features/cardBalance/api/cardBalanceApi";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { useCardBalances, useDeleteCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
||||
import type { CardBalance } from "@/features/cardBalance/api/cardBalanceApi";
|
||||
import { CardBalanceStatusBadge } from "@/features/cardBalance/components/cardBalanceStatusBadge";
|
||||
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||
|
||||
const PER_PAGE = 25;
|
||||
// ─── Column meta for toggle dropdown ─────────────────────────────────────────
|
||||
|
||||
const COLUMN_IDS = ["id", "passportNumber", "cardLast4", "expiry", "balance", "status", "createdBy", "createdAt"] as const;
|
||||
|
||||
export default function CardBalancesPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const deleteMutation = useDeleteCardBalance();
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(PER_PAGE);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [search, setSearch] = useState("");
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([...COLUMN_IDS]);
|
||||
|
||||
const { data, isLoading } = useCardBalances({ page, per_page: perPage, search });
|
||||
const deleteMutation = useDeleteCardBalance();
|
||||
const downloadMutation = useDownloadCardBalance();
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
{ fieldId: "status", value: "" },
|
||||
{ fieldId: "created_by", value: "" },
|
||||
]);
|
||||
|
||||
// ── Columns ───────────────────────────────────────────────────────────────
|
||||
// ── Infinite user dropdown for created_by filter ────────────────────────────
|
||||
|
||||
const columns: ColumnDef<CardBalance>[] = [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<button className="text-primary font-medium hover:underline" onClick={() => navigate(`/card-balances/${row.original.id}`)}>
|
||||
{row.original.id}
|
||||
</button>
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const {
|
||||
data: usersInfiniteData,
|
||||
fetchNextPage: fetchNextUsers,
|
||||
hasNextPage: hasNextUsers,
|
||||
isFetchingNextPage: isFetchingNextUsers,
|
||||
isLoading: isUsersLoading,
|
||||
} = useInfiniteUsers(userSearch);
|
||||
|
||||
const userOptions = useMemo(
|
||||
() =>
|
||||
(usersInfiniteData?.pages ?? []).flatMap((page) =>
|
||||
(page?.users ?? []).map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || u.username || String(u.id),
|
||||
})),
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "passport_series",
|
||||
accessorKey: "passport_series",
|
||||
header: t("Passport series", "PASPORT SERIYASY"),
|
||||
cell: ({ row }) => <span>{row.original.passport_series}</span>,
|
||||
},
|
||||
{
|
||||
id: "passport_number",
|
||||
accessorKey: "passport_number",
|
||||
header: t("Passport number", "PASPORT BELGISI"),
|
||||
cell: ({ row }) => <span>{row.original.passport_number}</span>,
|
||||
},
|
||||
{
|
||||
id: "card_number",
|
||||
accessorKey: "card_number",
|
||||
header: t("Card number", "KART BELGISI"),
|
||||
cell: ({ row }) => <span className="font-mono">{row.original.card_number}</span>,
|
||||
},
|
||||
{
|
||||
id: "card_expiry_month",
|
||||
accessorKey: "card_expiry_month",
|
||||
header: t("Expiry month", "KART MÖHLETI (AÝ)"),
|
||||
cell: ({ row }) => <span>{row.original.card_expiry_month}</span>,
|
||||
},
|
||||
{
|
||||
id: "card_expiry_year",
|
||||
accessorKey: "card_expiry_year",
|
||||
header: t("Expiry year", "KART MÖHLETI (ÝYL)"),
|
||||
cell: ({ row }) => <span>{row.original.card_expiry_year}</span>,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
extraActions={[{ icon: Download, title: t("Download", "Ýükle"), onClick: () => downloadMutation.mutate(row.original.id) }]}
|
||||
onView={() => navigate(`/card-balances/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/card-balances/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
[usersInfiniteData],
|
||||
);
|
||||
|
||||
const columnMeta: ColumnMeta[] = columns
|
||||
.filter((c) => c.id !== "actions")
|
||||
.map((c) => ({
|
||||
id: c.id!,
|
||||
label: typeof c.header === "string" ? c.header : c.id!,
|
||||
}));
|
||||
// ── Query params & data ─────────────────────────────────────────────────────
|
||||
|
||||
const total = data?.total ?? 0;
|
||||
const totalPages = Math.ceil(total / perPage);
|
||||
const queryParams = useMemo(() => {
|
||||
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
|
||||
return {
|
||||
page,
|
||||
limit: perPage,
|
||||
search: search || undefined,
|
||||
status: filterMap.status || undefined,
|
||||
created_by: filterMap.created_by ? Number(filterMap.created_by) : undefined,
|
||||
};
|
||||
}, [search, activeFilters, page, perPage]);
|
||||
|
||||
const handleDelete = async () => {
|
||||
const { data, isLoading } = useCardBalances(queryParams);
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
||||
|
||||
const statusOptions = useMemo(
|
||||
() => [
|
||||
{ value: "pending", label: t("cardBalance.status.pending", "Garaşylýar") },
|
||||
{ value: "approved", label: t("cardBalance.status.approved", "Tassyklanan") },
|
||||
{ value: "rejected", label: t("cardBalance.status.rejected", "Ret edilen") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setActiveFilters((prev) => prev.map((f) => ({ ...f, value: "" })));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleDelete = useCallback((id: number) => {
|
||||
setDeleteId(id);
|
||||
}, []);
|
||||
|
||||
const confirmDelete = useCallback(() => {
|
||||
if (deleteId === null) return;
|
||||
await deleteMutation.mutateAsync(deleteId);
|
||||
deleteMutation.mutate(deleteId);
|
||||
setDeleteId(null);
|
||||
};
|
||||
}, [deleteId, deleteMutation]);
|
||||
|
||||
// ── Columns ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const columns = useMemo<ColumnDef<CardBalance>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<button
|
||||
className="text-primary font-medium hover:underline text-left cursor-pointer"
|
||||
onClick={() => navigate(`/card-balances/${row.original.id}`)}
|
||||
>
|
||||
{row.original.id}
|
||||
</button>
|
||||
),
|
||||
size: 70,
|
||||
},
|
||||
{
|
||||
id: "passportNumber",
|
||||
accessorKey: "passportNumber",
|
||||
header: t("Passport number", "PASPORT BELGISI"),
|
||||
cell: ({ row }) => <span className="text-foreground">{row.original.passportNumber}</span>,
|
||||
},
|
||||
{
|
||||
id: "cardLast4",
|
||||
accessorKey: "cardLast4",
|
||||
header: t("Card last 4", "KART BELGISI (SOŇKY 4)"),
|
||||
cell: ({ row }) => <span className="font-mono">•••• •••• •••• {row.original.cardLast4}</span>,
|
||||
},
|
||||
{
|
||||
id: "expiry",
|
||||
accessorKey: "expiryMonth",
|
||||
header: t("Expiry", "KART MÖHLETI"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground whitespace-nowrap">
|
||||
{String(row.original.expiryMonth).padStart(2, "0")}/{row.original.expiryYear}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "balance",
|
||||
accessorKey: "balanceAmount",
|
||||
header: t("Balance", "GALYNDY"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground font-medium whitespace-nowrap">
|
||||
{row.original.balanceAmount} {row.original.balanceCurrency}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("Status", "STATUS"),
|
||||
cell: ({ row }) => <CardBalanceStatusBadge status={row.original.status} />,
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
id: "createdBy",
|
||||
accessorKey: "createdBy",
|
||||
header: t("Created by", "DÖREDEN"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground">{row.original.createdBy?.name || row.original.createdBy?.username || "—"}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: t("Created at", "DÖREDILEN WAGTY"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-muted-foreground text-sm whitespace-nowrap">{new Date(row.original.createdAt).toLocaleString()}</span>
|
||||
),
|
||||
size: 180,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
onView={() => navigate(`/card-balances/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/card-balances/${row.original.id}/edit`)}
|
||||
onDelete={() => handleDelete(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
],
|
||||
[t, navigate, handleDelete, deleteMutation.isPending],
|
||||
);
|
||||
|
||||
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`cardBalance.columns.${id}`, id) })), [t]);
|
||||
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "status",
|
||||
label: t("Status", "STATUS"),
|
||||
options: statusOptions,
|
||||
},
|
||||
{
|
||||
id: "created_by",
|
||||
label: t("Created by", "DÖREDEN"),
|
||||
type: "infinite-select",
|
||||
options: userOptions,
|
||||
loading: isUsersLoading,
|
||||
isLoadingMore: isFetchingNextUsers,
|
||||
hasNextPage: hasNextUsers,
|
||||
onLoadMore: fetchNextUsers,
|
||||
searchValue: userSearch,
|
||||
onSearchChange: setUserSearch,
|
||||
},
|
||||
],
|
||||
[t, statusOptions, userOptions, isUsersLoading, isFetchingNextUsers, hasNextUsers, userSearch],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("Card balances", "Kart galyndylary")}</h1>
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("cardBalance.title", "Kart galyndylary")}</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 justify-between">
|
||||
<TableSearchInput
|
||||
value={search}
|
||||
@@ -116,25 +234,30 @@ export default function CardBalancesPage() {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder={t("common.search", "Gözlemek")}
|
||||
placeholder={t("cardBalance.searchPlaceholder", "Pasport belgisi boýunça gözle")}
|
||||
/>
|
||||
<CreateButton label={t("Create card balance", "Kart galyndysy dörediň")} onClick={() => navigate("/card-balances/create")} />
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-xl p-4">
|
||||
<DataTableToolbar
|
||||
hideSearch
|
||||
hideAction
|
||||
searchValue={search}
|
||||
onSearchChange={(v) => {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={columnMeta}
|
||||
searchPlaceholder={t("cardBalance.searchPlaceholder", "Pasport belgisi boýunça gözle")}
|
||||
columns={toggleableColumns}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
hideSearch
|
||||
hideAction
|
||||
filterFields={filterFields}
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
perPageOptions={[10, 25, 50, 100]}
|
||||
perPage={perPage}
|
||||
onPerPageChange={(v) => {
|
||||
@@ -143,9 +266,10 @@ export default function CardBalancesPage() {
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Table */}
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.cardBalances ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
@@ -160,14 +284,15 @@ export default function CardBalancesPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Delete dialog */}
|
||||
<DeleteDialog
|
||||
open={deleteId !== null}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setDeleteId(null);
|
||||
}}
|
||||
title={t("Are you sure?", "Eminsiňizmi?")}
|
||||
description={t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")}
|
||||
onConfirm={handleDelete}
|
||||
title={t("cardBalance.deleteConfirm", "Bu ýazgy pozulsynmy?")}
|
||||
description={t("cardBalance.deleteDescription", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")}
|
||||
onConfirm={confirmDelete}
|
||||
isLoading={deleteMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate, Link } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Download, Trash2, Pencil } from "lucide-react";
|
||||
import { Trash2, Pencil } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import {
|
||||
@@ -14,25 +14,9 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
useCardBalance,
|
||||
useDeleteCardBalance,
|
||||
useDownloadCardBalance,
|
||||
} from "@/features/cardBalance/hooks/useCardBalance";
|
||||
import { InfoRow, CollapsibleSection, StatusBadge, EmptyState } from "@/components/viewPageComponents";
|
||||
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
||||
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
||||
|
||||
// ─── Types for operations table ───────────────────────────────────────────────
|
||||
|
||||
interface Operation {
|
||||
id: number;
|
||||
action_name: string;
|
||||
performed_by: string;
|
||||
target: string;
|
||||
status: "FINISHED" | "PENDING" | "FAILED";
|
||||
date: string;
|
||||
}
|
||||
import { useCardBalance, useDeleteCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
||||
import { InfoRow } from "@/components/viewPageComponents";
|
||||
import { CardBalanceStatusBadge } from "@/features/cardBalance/components/cardBalanceStatusBadge";
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -42,67 +26,10 @@ export default function CardBalanceViewPage() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
const [opsSearch, setOpsSearch] = useState("");
|
||||
|
||||
const numericId = Number(id);
|
||||
const { data, isLoading } = useCardBalance(numericId);
|
||||
const deleteMutation = useDeleteCardBalance();
|
||||
const downloadMutation = useDownloadCardBalance();
|
||||
|
||||
// Placeholder operations — in real app fetch from API using numericId
|
||||
const operations: Operation[] = [];
|
||||
|
||||
const filteredOperations = operations.filter(
|
||||
(op) =>
|
||||
op.action_name.toLowerCase().includes(opsSearch.toLowerCase()) ||
|
||||
op.target.toLowerCase().includes(opsSearch.toLowerCase()),
|
||||
);
|
||||
|
||||
// ── Operations columns ──────────────────────────────────────────────────
|
||||
|
||||
const operationColumns: ColumnDef<Operation>[] = [
|
||||
{
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-primary font-semibold text-sm">
|
||||
{row.original.id}
|
||||
</span>
|
||||
),
|
||||
size: 80,
|
||||
},
|
||||
{
|
||||
accessorKey: "action_name",
|
||||
header: t("Action name", "AMALYŇ ADY"),
|
||||
cell: ({ row }) => <span className="text-sm">{row.original.action_name}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "performed_by",
|
||||
header: t("Performed by", "KIM TARAPYNDAN"),
|
||||
cell: ({ row }) => <span className="text-sm">{row.original.performed_by}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "target",
|
||||
header: t("Target", "AMALYŇ NYŞANY (TARGEDI)"),
|
||||
cell: ({ row }) => <span className="text-sm">{row.original.target}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: t("Status", "AMALYŇ STATUSY"),
|
||||
cell: ({ row }) => <StatusBadge status={row.original.status} />,
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
accessorKey: "date",
|
||||
header: t("Date", "SENE"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{row.original.date}
|
||||
</span>
|
||||
),
|
||||
size: 160,
|
||||
},
|
||||
];
|
||||
|
||||
const handleDelete = async () => {
|
||||
await deleteMutation.mutateAsync(numericId);
|
||||
@@ -114,7 +41,7 @@ export default function CardBalanceViewPage() {
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-7 w-64" />
|
||||
<div className="rounded-lg border border-border bg-card overflow-hidden">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<div key={i} className="grid grid-cols-[220px_1fr] items-center py-2.5 px-4 border-b border-border last:border-0">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-4 w-40" />
|
||||
@@ -126,11 +53,7 @@ export default function CardBalanceViewPage() {
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return (
|
||||
<div className="text-center py-24 text-muted-foreground">
|
||||
{t("Not found", "Tapylmady")}
|
||||
</div>
|
||||
);
|
||||
return <div className="text-center py-24 text-muted-foreground">{t("Not found", "Tapylmady")}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -138,17 +61,9 @@ export default function CardBalanceViewPage() {
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{t("Card balance detail", "Kart galyndysy giňişleýin")}:
|
||||
{t("Card balance detail", "Kart galyndysy giňişleýin")}: #{data.id}
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => downloadMutation.mutate(numericId)}
|
||||
disabled={downloadMutation.isPending}
|
||||
>
|
||||
<Download size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -168,80 +83,37 @@ export default function CardBalanceViewPage() {
|
||||
{/* Detail card */}
|
||||
<div className="rounded-lg border border-border bg-card overflow-hidden">
|
||||
<InfoRow label={t("ID", "ID")} value={data.id} />
|
||||
<InfoRow label={t("Passport number", "Pasport belgisi")} value={data.passportNumber} />
|
||||
<InfoRow label={t("Card last 4", "Kart belgisi (soňky 4)")} value={data.cardLast4} />
|
||||
<InfoRow label={t("Card expiry", "Kart möhleti")} value={`${String(data.expiryMonth).padStart(2, "0")}/${data.expiryYear}`} />
|
||||
<InfoRow label={t("Balance amount", "Galyndy möçberi")} value={`${data.balanceAmount} ${data.balanceCurrency}`} />
|
||||
<InfoRow label={t("Status", "Status")}>
|
||||
<CardBalanceStatusBadge status={data.status} />
|
||||
</InfoRow>
|
||||
<InfoRow label={t("Checked at", "Barlan wagty")} value={new Date(data.checkedAt).toLocaleString()} />
|
||||
<InfoRow
|
||||
label={t("Passport series", "Pasport seriýasy")}
|
||||
value={data.passport_series}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("Passport number", "Pasport belgisi")}
|
||||
value={data.passport_number}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("Card number", "Kart belgisi")}
|
||||
value={data.card_number}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("Card expiry month", "Kart Möhleti (aý)")}
|
||||
value={data.card_expiry_month}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("Card expiry year", "Kart Möhleti (ýyl)")}
|
||||
value={data.card_expiry_year}
|
||||
label={t("Created by", "Döreden")}
|
||||
value={data.createdBy?.name || data.createdBy?.username || undefined}
|
||||
isLink
|
||||
href={data.createdBy?.id != null ? `/all-users/${data.createdBy.id}` : undefined}
|
||||
/>
|
||||
<InfoRow label={t("Created at", "Döredilen wagty")} value={new Date(data.createdAt).toLocaleString()} />
|
||||
<InfoRow label={t("Updated at", "Täzelenen wagty")} value={new Date(data.updatedAt).toLocaleString()} />
|
||||
</div>
|
||||
|
||||
{/* Ammallar (Operations) collapsible section */}
|
||||
<CollapsibleSection title={t("Operations", "Ammallar")}>
|
||||
<DataTableToolbar
|
||||
searchValue={opsSearch}
|
||||
onSearchChange={setOpsSearch}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={[]}
|
||||
columnVisibility={{}}
|
||||
onColumnVisibilityChange={() => {}}
|
||||
columnOrder={[]}
|
||||
onColumnOrderChange={() => {}}
|
||||
/>
|
||||
{filteredOperations.length === 0 ? (
|
||||
<EmptyState
|
||||
label={t(
|
||||
"No operations found",
|
||||
"Berlen kriterýalara Amal gabat gelmedi.",
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<DataTable
|
||||
columns={operationColumns}
|
||||
data={filteredOperations}
|
||||
getRowId={(r) => String(r.id)}
|
||||
enableRowSelection
|
||||
/>
|
||||
)}
|
||||
</CollapsibleSection>
|
||||
|
||||
{/* Delete dialog */}
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{t("Are you sure?", "Eminsiňizmi?")}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogTitle>{t("Are you sure?", "Eminsiňizmi?")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t(
|
||||
"This action cannot be undone.",
|
||||
"Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.",
|
||||
)}
|
||||
{t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t("Cancel", "Ýatyr")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDelete}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleteMutation.isPending
|
||||
? t("Deleting...", "Öçürilýär...")
|
||||
: t("Delete", "Öçür")}
|
||||
<AlertDialogAction onClick={handleDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
|
||||
{deleteMutation.isPending ? t("Deleting...", "Öçürilýär...") : t("Delete", "Öçür")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
|
||||
@@ -1,155 +1,353 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Download, AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ColumnMeta } from "@/components/dataTableToolbar";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import type { VisibilityState } from "@tanstack/react-table";
|
||||
import { useCardRequisites, useDeleteCardRequisite, useDownloadCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites";
|
||||
import type { CardRequisite, CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { useCardRequisites, useDeleteCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites";
|
||||
import type { CardRequisite, CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi";
|
||||
import { resolveLocalizedName } from "@/features/cardRequisites/api/cardRequisitesApi";
|
||||
import { useInfiniteBranches } from "@/features/branches/hooks/useBranches";
|
||||
import { useInfiniteCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
||||
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||
|
||||
// ─── Status badge ─────────────────────────────────────────────────────────────
|
||||
// ─── Status Badge ─────────────────────────────────────────────────────────────
|
||||
|
||||
const STATUS_CONFIG: Record<CardRequisiteStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }> = {
|
||||
pending: { label: "Garaşylýar", variant: "warning", icon: AlertCircle },
|
||||
approved: { label: "Tassyklanan", variant: "success", icon: CheckCircle2 },
|
||||
rejected: { label: "Ret edilen", variant: "error", icon: XCircle },
|
||||
const STATUS_CONFIG: Record<
|
||||
CardRequisiteStatus,
|
||||
{ labelKey: string; fallback: string; variant: StatusBadgeVariant; icon: React.ElementType }
|
||||
> = {
|
||||
pending: { labelKey: "cardRequisites.status.pending", fallback: "Garaşylýar", variant: "warning", icon: AlertCircle },
|
||||
approved: { labelKey: "cardRequisites.status.approved", fallback: "Tassyklanan", variant: "success", icon: CheckCircle2 },
|
||||
rejected: { labelKey: "cardRequisites.status.rejected", fallback: "Ret edilen", variant: "error", icon: XCircle },
|
||||
};
|
||||
|
||||
function CardRequisiteStatusBadge({ status }: { status: CardRequisiteStatus }) {
|
||||
const cfg = STATUS_CONFIG[status];
|
||||
function CardRequisiteStatusBadge({ status }: { status: string }) {
|
||||
const { t } = useTranslation();
|
||||
const cfg = STATUS_CONFIG[status as CardRequisiteStatus];
|
||||
if (!cfg) return <span className="text-xs text-muted-foreground">{status}</span>;
|
||||
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />;
|
||||
return <StatusBadge label={t(cfg.labelKey, cfg.fallback)} variant={cfg.variant} icon={cfg.icon} />;
|
||||
}
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
// ─── Column meta for toggle dropdown ─────────────────────────────────────────
|
||||
|
||||
const PER_PAGE = 25;
|
||||
const COLUMN_IDS = ["id", "uniqueId", "cardType", "customer", "user", "region", "branch", "status"] as const;
|
||||
|
||||
// ─── Filter constants ─────────────────────────────────────────────────────────
|
||||
|
||||
const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const;
|
||||
|
||||
export default function CardRequisitesPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
const navigate = useNavigate();
|
||||
const deleteMutation = useDeleteCardRequisite();
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(PER_PAGE);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [search, setSearch] = useState("");
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([...COLUMN_IDS]);
|
||||
|
||||
const { data, isLoading } = useCardRequisites({
|
||||
page,
|
||||
per_page: perPage,
|
||||
search,
|
||||
});
|
||||
const deleteMutation = useDeleteCardRequisite();
|
||||
const downloadMutation = useDownloadCardRequisite();
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
{ fieldId: "status", value: "" },
|
||||
{ fieldId: "region", value: "" },
|
||||
{ fieldId: "branch_id", value: "" },
|
||||
{ fieldId: "card_type_id", value: "" },
|
||||
{ fieldId: "user_id", value: "" },
|
||||
]);
|
||||
|
||||
// ── Columns ──────────────────────────────────────────────────────────────────
|
||||
// ── Infinite dropdown hooks ─────────────────────────────────────────────────
|
||||
|
||||
const columns: ColumnDef<CardRequisite>[] = [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<button
|
||||
className="text-primary font-medium hover:underline text-left"
|
||||
onClick={() => navigate(`/card-requisites/${row.original.id}`)}
|
||||
>
|
||||
{row.original.id}
|
||||
</button>
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const {
|
||||
data: branchesInfiniteData,
|
||||
fetchNextPage: fetchNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
isFetchingNextPage: isFetchingNextBranches,
|
||||
isLoading: isBranchesLoading,
|
||||
} = useInfiniteBranches(branchSearch);
|
||||
|
||||
const branchOptions = useMemo(
|
||||
() =>
|
||||
(branchesInfiniteData?.pages ?? []).flatMap((page) =>
|
||||
(page?.branches ?? []).map((b) => ({
|
||||
value: String(b.id),
|
||||
label: b.name[lang] || b.name.tm || String(b.id),
|
||||
})),
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "card_type",
|
||||
accessorKey: "card_type",
|
||||
header: t("Card type", "GÖRNÜŞI"),
|
||||
cell: ({ row }) => <span className="text-primary font-medium">{row.original.card_type}</span>,
|
||||
},
|
||||
{
|
||||
id: "created_at",
|
||||
accessorKey: "created_at",
|
||||
header: t("Created at", "DÖREDILEN WAGTY"),
|
||||
cell: ({ row }) => <span className="text-foreground">{row.original.created_at}</span>,
|
||||
},
|
||||
{
|
||||
id: "province_name",
|
||||
accessorKey: "province_name",
|
||||
header: t("Province", "WELAÝAT"),
|
||||
cell: ({ row }) => <span className="text-foreground">{row.original.province_name ?? "—"}</span>,
|
||||
},
|
||||
{
|
||||
id: "branch_name",
|
||||
accessorKey: "branch_name",
|
||||
header: t("Branch", "ŞAHAMÇA"),
|
||||
cell: ({ row }) => <span className="text-primary font-medium">{row.original.branch_name ?? "—"}</span>,
|
||||
},
|
||||
{
|
||||
id: "first_name",
|
||||
accessorKey: "first_name",
|
||||
header: t("First name", "ADY"),
|
||||
cell: ({ row }) => <span>{row.original.first_name}</span>,
|
||||
},
|
||||
{
|
||||
id: "last_name",
|
||||
accessorKey: "last_name",
|
||||
header: t("Last name", "FAMILIÝASY"),
|
||||
cell: ({ row }) => <span>{row.original.last_name}</span>,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("Status", "STATUS"),
|
||||
cell: ({ row }) => <CardRequisiteStatusBadge status={row.original.status} />,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
extraActions={[{ icon: Download, title: t("Download", "Ýükle"), onClick: () => downloadMutation.mutate(row.original.id) }]}
|
||||
onView={() => navigate(`/card-requisites/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/card-requisites/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
[branchesInfiniteData, lang],
|
||||
);
|
||||
|
||||
const [cardTypeSearch, setCardTypeSearch] = useState("");
|
||||
const {
|
||||
data: cardTypesInfiniteData,
|
||||
fetchNextPage: fetchNextCardTypes,
|
||||
hasNextPage: hasNextCardTypes,
|
||||
isFetchingNextPage: isFetchingNextCardTypes,
|
||||
isLoading: isCardTypesLoading,
|
||||
} = useInfiniteCardTypes(cardTypeSearch);
|
||||
|
||||
const cardTypeOptions = useMemo(
|
||||
() =>
|
||||
(cardTypesInfiniteData?.pages ?? []).flatMap((page) =>
|
||||
(page?.paymentCards ?? []).map((ct) => ({
|
||||
value: String(ct.id),
|
||||
label: ct.title[lang] || ct.title.tm || String(ct.id),
|
||||
})),
|
||||
),
|
||||
},
|
||||
];
|
||||
[cardTypesInfiniteData, lang],
|
||||
);
|
||||
|
||||
// ── Column meta for toolbar ───────────────────────────────────────────────────
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const {
|
||||
data: clientsInfiniteData,
|
||||
fetchNextPage: fetchNextClients,
|
||||
hasNextPage: hasNextClients,
|
||||
isFetchingNextPage: isFetchingNextClients,
|
||||
isLoading: isClientsLoading,
|
||||
} = useInfiniteClients(userSearch);
|
||||
|
||||
const columnMeta: ColumnMeta[] = columns
|
||||
.filter((c) => c.id !== "actions")
|
||||
.map((c) => ({
|
||||
id: c.id!,
|
||||
label: typeof c.header === "string" ? c.header : c.id!,
|
||||
}));
|
||||
const clientOptions = useMemo(
|
||||
() =>
|
||||
(clientsInfiniteData?.pages ?? []).flatMap((page) =>
|
||||
(page?.users ?? []).map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || u.username || String(u.id),
|
||||
})),
|
||||
),
|
||||
[clientsInfiniteData],
|
||||
);
|
||||
|
||||
// ── Pagination ────────────────────────────────────────────────────────────────
|
||||
// ── Query params & data ─────────────────────────────────────────────────────
|
||||
|
||||
const total = data?.total ?? 0;
|
||||
const totalPages = Math.ceil(total / perPage);
|
||||
const queryParams = useMemo(() => {
|
||||
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
|
||||
return {
|
||||
search: search || undefined,
|
||||
status: filterMap.status || undefined,
|
||||
region: filterMap.region || undefined,
|
||||
branch_id: filterMap.branch_id ? Number(filterMap.branch_id) : undefined,
|
||||
card_type_id: filterMap.card_type_id ? Number(filterMap.card_type_id) : undefined,
|
||||
user_id: filterMap.user_id ? Number(filterMap.user_id) : undefined,
|
||||
page,
|
||||
limit: perPage,
|
||||
};
|
||||
}, [search, activeFilters, page, perPage]);
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
await deleteMutation.mutateAsync(deleteId);
|
||||
const { data, isLoading } = useCardRequisites(queryParams);
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
||||
|
||||
const regionOptions = useMemo(() => REGION_CODES.map((code) => ({ value: code, label: t(`loanOrders.regions.${code}`, code) })), [t]);
|
||||
|
||||
const statusOptions = useMemo(
|
||||
() => [
|
||||
{ value: "pending", label: t("cardRequisites.status.pending", "Garaşylýar") },
|
||||
{ value: "approved", label: t("cardRequisites.status.approved", "Tassyklanan") },
|
||||
{ value: "rejected", label: t("cardRequisites.status.rejected", "Ret edilen") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setActiveFilters((prev) => prev.map((f) => ({ ...f, value: "" })));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleDelete = useCallback((id: number) => {
|
||||
setDeleteId(id);
|
||||
}, []);
|
||||
|
||||
const confirmDelete = useCallback(() => {
|
||||
if (deleteId === null) return;
|
||||
deleteMutation.mutate(deleteId);
|
||||
setDeleteId(null);
|
||||
};
|
||||
}, [deleteId, deleteMutation]);
|
||||
|
||||
// ── Columns ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const columns = useMemo<ColumnDef<CardRequisite>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<button
|
||||
className="text-primary font-medium hover:underline text-left cursor-pointer"
|
||||
onClick={() => navigate(`/card-requisites/${row.original.id}`)}
|
||||
>
|
||||
{row.original.id}
|
||||
</button>
|
||||
),
|
||||
size: 70,
|
||||
},
|
||||
{
|
||||
id: "uniqueId",
|
||||
accessorKey: "uniqueId",
|
||||
header: t("Unique ID", "Unikal ID"),
|
||||
cell: ({ row }) => <span className="text-sm font-mono">{row.original.uniqueId || "—"}</span>,
|
||||
},
|
||||
{
|
||||
id: "cardType",
|
||||
accessorKey: "cardType",
|
||||
header: t("Card type", "GÖRNÜŞI"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-primary font-medium">{resolveLocalizedName(row.original.cardType?.name, lang) || "—"}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "customer",
|
||||
accessorKey: "customerName",
|
||||
header: t("Customer", "MÜŞDERI"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground">
|
||||
{row.original.customerSurname} {row.original.customerName}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "user",
|
||||
accessorKey: "user",
|
||||
header: t("User", "ULANYJY"),
|
||||
cell: ({ row }) => <span className="text-foreground">{row.original.user?.name || row.original.user?.username || "—"}</span>,
|
||||
},
|
||||
{
|
||||
id: "region",
|
||||
accessorKey: "region",
|
||||
header: t("Region", "WELAÝAT"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground">
|
||||
{row.original.region ? t(`loanOrders.regions.${row.original.region}`, row.original.region) : "—"}
|
||||
</span>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
id: "branch",
|
||||
accessorKey: "branch",
|
||||
header: t("Branch", "ŞAHAMÇA"),
|
||||
cell: ({ row }) => <span className="text-foreground">{resolveLocalizedName(row.original.branch?.name, lang) || "—"}</span>,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("Status", "STATUS"),
|
||||
cell: ({ row }) => <CardRequisiteStatusBadge status={row.original.status} />,
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
onView={() => navigate(`/card-requisites/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/card-requisites/${row.original.id}/edit`)}
|
||||
onDelete={() => handleDelete(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
],
|
||||
[t, lang, navigate, handleDelete, deleteMutation.isPending],
|
||||
);
|
||||
|
||||
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`cardRequisites.columns.${id}`, id) })), [t]);
|
||||
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "status",
|
||||
label: t("Status", "STATUS"),
|
||||
options: statusOptions,
|
||||
},
|
||||
{
|
||||
id: "region",
|
||||
label: t("Region", "WELAÝAT"),
|
||||
options: regionOptions,
|
||||
},
|
||||
{
|
||||
id: "branch_id",
|
||||
label: t("Branch", "ŞAHAMÇA"),
|
||||
type: "infinite-select",
|
||||
options: branchOptions,
|
||||
loading: isBranchesLoading,
|
||||
isLoadingMore: isFetchingNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
onLoadMore: fetchNextBranches,
|
||||
searchValue: branchSearch,
|
||||
onSearchChange: setBranchSearch,
|
||||
},
|
||||
{
|
||||
id: "card_type_id",
|
||||
label: t("Card type", "KART GÖRNÜŞI"),
|
||||
type: "infinite-select",
|
||||
options: cardTypeOptions,
|
||||
loading: isCardTypesLoading,
|
||||
isLoadingMore: isFetchingNextCardTypes,
|
||||
hasNextPage: hasNextCardTypes,
|
||||
onLoadMore: fetchNextCardTypes,
|
||||
searchValue: cardTypeSearch,
|
||||
onSearchChange: setCardTypeSearch,
|
||||
},
|
||||
{
|
||||
id: "user_id",
|
||||
label: t("User", "ULANYJY"),
|
||||
type: "infinite-select",
|
||||
options: clientOptions,
|
||||
loading: isClientsLoading,
|
||||
isLoadingMore: isFetchingNextClients,
|
||||
hasNextPage: hasNextClients,
|
||||
onLoadMore: fetchNextClients,
|
||||
searchValue: userSearch,
|
||||
onSearchChange: setUserSearch,
|
||||
},
|
||||
],
|
||||
[
|
||||
t,
|
||||
statusOptions,
|
||||
regionOptions,
|
||||
branchOptions,
|
||||
isBranchesLoading,
|
||||
isFetchingNextBranches,
|
||||
hasNextBranches,
|
||||
branchSearch,
|
||||
cardTypeOptions,
|
||||
isCardTypesLoading,
|
||||
isFetchingNextCardTypes,
|
||||
hasNextCardTypes,
|
||||
cardTypeSearch,
|
||||
clientOptions,
|
||||
isClientsLoading,
|
||||
isFetchingNextClients,
|
||||
hasNextClients,
|
||||
userSearch,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("Card requisites", "Kart rekwizitler")}</h1>
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("cardRequisites.title", "Kart rekwizitler")}</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 justify-between">
|
||||
<TableSearchInput
|
||||
value={search}
|
||||
@@ -157,28 +355,33 @@ export default function CardRequisitesPage() {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder={t("common.search", "Gözlemek")}
|
||||
placeholder={t("cardRequisites.searchPlaceholder", "Gözlemek")}
|
||||
/>
|
||||
<CreateButton
|
||||
label={t("cardRequisites.createTitle", "Kart rekwiziti üçin sargyt dörediň")}
|
||||
onClick={() => navigate("/card-requisites/create")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-xl p-4">
|
||||
<DataTableToolbar
|
||||
hideSearch
|
||||
hideAction
|
||||
searchValue={search}
|
||||
onSearchChange={(v) => {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={columnMeta}
|
||||
searchPlaceholder={t("cardRequisites.searchPlaceholder", "Gözlemek")}
|
||||
columns={toggleableColumns}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
hideSearch
|
||||
hideAction
|
||||
filterFields={filterFields}
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
perPageOptions={[10, 25, 50, 100]}
|
||||
perPage={perPage}
|
||||
onPerPageChange={(v) => {
|
||||
@@ -190,29 +393,30 @@ export default function CardRequisitesPage() {
|
||||
{/* Table */}
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.cardRekwizitOrders ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
enableRowSelection
|
||||
getRowId={(row) => row.id}
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={totalPages}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Delete dialog */}
|
||||
<DeleteDialog
|
||||
open={deleteId !== null}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setDeleteId(null);
|
||||
}}
|
||||
title={t("Are you sure?", "Eminsiňizmi?")}
|
||||
description={t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.")}
|
||||
onConfirm={handleDelete}
|
||||
title={t("cardRequisites.deleteConfirm", "Bu sargyt pozulsynmy?")}
|
||||
description={t("cardRequisites.deleteDescription", "Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.")}
|
||||
onConfirm={confirmDelete}
|
||||
isLoading={deleteMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { PageSpinner } from '@/components/pageSpinner'
|
||||
import { PageError } from '@/components/pageError'
|
||||
import { CardRequisiteForm } from '@/features/cardRequisites/components/cardRequisiteForm'
|
||||
import { useCardRequisite } from '@/features/cardRequisites/hooks/useCardRequisites'
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PageSpinner } from "@/components/pageSpinner";
|
||||
import { PageError } from "@/components/pageError";
|
||||
import { CardRequisiteForm } from "@/features/cardRequisites/components/cardRequisiteForm";
|
||||
import { useCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites";
|
||||
|
||||
export default function CardRequisiteEditPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const { t } = useTranslation()
|
||||
const { data, isLoading } = useCardRequisite(id ?? '')
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const { t } = useTranslation();
|
||||
const numericId = Number(id);
|
||||
const { data, isLoading } = useCardRequisite(numericId);
|
||||
|
||||
if (isLoading) return <PageSpinner />
|
||||
if (!data) return <PageError message={t('common.notFound', 'Tapylmady')} />
|
||||
if (isLoading) return <PageSpinner />;
|
||||
if (!data) return <PageError message={t("common.notFound", "Tapylmady")} />;
|
||||
|
||||
return <CardRequisiteForm mode="edit" initialData={data} />
|
||||
return <CardRequisiteForm mode="edit" initialData={data} />;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useCardRequisite, useDeleteCardRequisite, useDownloadCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites";
|
||||
import type { CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { ArrowLeft, Pencil, Trash2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Pencil, Trash2, Download } from "lucide-react";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -15,6 +14,9 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { useCardRequisite, useDeleteCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites";
|
||||
import type { CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi";
|
||||
import { resolveLocalizedName } from "@/features/cardRequisites/api/cardRequisitesApi";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { BentoGrid, BentoCard, InfoRow, PassportImage } from "@/components/viewPageComponents";
|
||||
@@ -33,12 +35,13 @@ const STATUS_ICON: Record<CardRequisiteStatus, React.ElementType> = {
|
||||
rejected: XCircle,
|
||||
};
|
||||
|
||||
function CardRequisiteStatusBadge({ status }: { status: CardRequisiteStatus }) {
|
||||
function CardRequisiteStatusBadge({ status }: { status: string }) {
|
||||
const { t } = useTranslation();
|
||||
const variant = STATUS_VARIANT[status];
|
||||
const Icon = STATUS_ICON[status];
|
||||
const key = status as CardRequisiteStatus;
|
||||
const variant = STATUS_VARIANT[key];
|
||||
const Icon = STATUS_ICON[key];
|
||||
if (!variant) return <span className="text-xs text-muted-foreground">{status}</span>;
|
||||
return <StatusBadge label={t(`cardRequisite.status.${status}`)} variant={variant} icon={Icon} />;
|
||||
return <StatusBadge label={t(`cardRequisite.status.${key}`)} variant={variant} icon={Icon} />;
|
||||
}
|
||||
|
||||
// ─── Skeleton ─────────────────────────────────────────────────────────────────
|
||||
@@ -61,6 +64,13 @@ function CardRequisiteViewSkeleton() {
|
||||
);
|
||||
}
|
||||
|
||||
function formatDate(value?: string): string {
|
||||
if (!value) return "";
|
||||
const d = new Date(value);
|
||||
if (isNaN(d.getTime())) return value;
|
||||
return d.toLocaleDateString();
|
||||
}
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export default function CardRequisiteViewPage() {
|
||||
@@ -68,9 +78,10 @@ export default function CardRequisiteViewPage() {
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { data, isLoading, isError } = useCardRequisite(id ?? "");
|
||||
const numericId = Number(id);
|
||||
const { data, isLoading, isError } = useCardRequisite(numericId);
|
||||
const deleteMutation = useDeleteCardRequisite();
|
||||
const downloadMutation = useDownloadCardRequisite();
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
if (isLoading) {
|
||||
return <CardRequisiteViewSkeleton />;
|
||||
@@ -80,26 +91,29 @@ export default function CardRequisiteViewPage() {
|
||||
return <div className="flex items-center justify-center py-24 text-muted-foreground">{t("common.notFound", "Maglumat tapylmady")}</div>;
|
||||
}
|
||||
|
||||
const fullName = [data.customerName, data.customerPatronicName, data.customerSurname].filter(Boolean).join(" ");
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex flex-col gap-6">
|
||||
{/* ── Page header ──────────────────────────────────────────────────── */}
|
||||
<div className="flex items-start justify-between">
|
||||
<h1 className="text-xl font-bold text-foreground">
|
||||
{t("cardRequisite.viewTitle", "Kart rekwizit giňişleýin")}: {data.id}
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-8 w-8"
|
||||
onClick={() => downloadMutation.mutate(data.id)}
|
||||
disabled={downloadMutation.isPending}
|
||||
>
|
||||
<Download size={15} />
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => navigate("/card-requisites")}>
|
||||
<ArrowLeft className="size-4" />
|
||||
</Button>
|
||||
<AlertDialog>
|
||||
<h1 className="text-xl font-bold text-foreground">
|
||||
{t("cardRequisite.viewTitle", "Kart rekwizit giňişleýin")}: {data.id}
|
||||
</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogTitle asChild>
|
||||
<Button size="icon" variant="ghost" className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10">
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</Button>
|
||||
</AlertDialogTitle>
|
||||
@@ -133,60 +147,78 @@ export default function CardRequisiteViewPage() {
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard title={t("cardRequisite.metaSection", "Esasy maglumatlar")}>
|
||||
<InfoRow label={t("common.id", "ID")} value={data.id} />
|
||||
<InfoRow label={t("cardRequisite.createdAt", "Döredilen wagty")} value={data.created_at} />
|
||||
<InfoRow label={t("Unique ID", "Unikal ID")} value={data.uniqueId || undefined} />
|
||||
<InfoRow label={t("cardRequisite.createdAt", "Döredilen wagty")} value={new Date(data.createdAt).toLocaleString()} />
|
||||
<InfoRow label={t("cardRequisite.status", "Status")}>
|
||||
<CardRequisiteStatusBadge status={data.status} />
|
||||
</InfoRow>
|
||||
<InfoRow label={t("cardRequisite.note", "Bellik")} value={data.note || undefined} />
|
||||
<InfoRow
|
||||
label={t("cardRequisite.createdBy", "Sargyt eden")}
|
||||
value={data.first_name && data.last_name ? `${data.last_name}_${data.first_name}` : undefined}
|
||||
isLink
|
||||
/>
|
||||
<InfoRow label={t("cardRequisite.note", "Bellik")} value={data.notes || undefined} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardRequisite.cardSection", "Kart")}>
|
||||
<InfoRow label={t("cardRequisite.cardNumber", "Kart belgisi")} value={data.card_number} />
|
||||
<InfoRow label={t("cardRequisite.cardExpireMonth", "Kart Möhleti (aý)")} value={data.card_expiry_month} />
|
||||
<InfoRow label={t("cardRequisite.cardExpireYear", "Kart Möhleti (ýyl)")} value={data.card_expiry_year} />
|
||||
<InfoRow
|
||||
label={t("cardRequisite.cardType", "Kart görnüşi")}
|
||||
value={resolveLocalizedName(data.cardType?.name) || undefined}
|
||||
isLink
|
||||
href={data.cardType?.id != null ? `/settings/card/card-types/${data.cardType.id}` : undefined}
|
||||
/>
|
||||
<InfoRow label={t("cardRequisite.cardNumber", "Kart belgisi")} value={data.cardNumber || undefined} />
|
||||
<InfoRow label={t("cardRequisite.cardExpireMonth", "Kart Möhleti (aý)")} value={data.cardMonth || undefined} />
|
||||
<InfoRow label={t("cardRequisite.cardExpireYear", "Kart Möhleti (ýyl)")} value={data.cardYear || undefined} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardRequisite.locationSection", "Lokasiýa")}>
|
||||
<InfoRow label={t("cardRequisite.province", "Welaýat")} value={data.province_name ?? undefined} />
|
||||
<InfoRow label={t("cardRequisite.branch", "Şahamça")} value={data.branch_name ?? undefined} isLink />
|
||||
<InfoRow label={t("cardRequisite.region", "Welaýat")} value={data.region || undefined} />
|
||||
<InfoRow
|
||||
label={t("cardRequisite.branch", "Şahamça")}
|
||||
value={resolveLocalizedName(data.branch?.name) || undefined}
|
||||
isLink
|
||||
href={data.branch?.id != null ? `/settings/location/branches/${data.branch.id}` : undefined}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 2: Şahsy + Pasport maglumatlary ──────────────────────────── */}
|
||||
{/* ── Row 2: Şahsy + Ulanyjy + Pasport maglumatlary ─────────────────── */}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("cardRequisite.personalSection", "Şahsy maglumatlar")}>
|
||||
<InfoRow
|
||||
label={t("cardRequisite.fullName", "Doly ady")}
|
||||
value={[data.first_name, data.last_name, data.middle_name].filter(Boolean).join(" ")}
|
||||
/>
|
||||
<InfoRow label={t("cardRequisite.birthDate", "Doglan güni")} value={data.birth_date} />
|
||||
<InfoRow label={t("cardRequisite.fullName", "Doly ady")} value={fullName} />
|
||||
<InfoRow label={t("cardRequisite.birthDate", "Doglan güni")} value={formatDate(data.bornAt)} />
|
||||
<InfoRow label={t("cardRequisite.phone", "Telefon")} value={data.phone} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardRequisite.passportSection", "Pasport")}>
|
||||
<InfoRow label={t("cardRequisite.passportSeries", "Pasport seriýasy")} value={data.passport_series} />
|
||||
<InfoRow label={t("cardRequisite.passportNumber", "Pasport belgisi")} value={data.passport_number} />
|
||||
<BentoCard title={t("cardRequisite.userSection", "Ulanyjy")}>
|
||||
<InfoRow
|
||||
label={t("cardRequisite.userName", "Ulanyjy ady")}
|
||||
value={data.user?.name || data.user?.username || undefined}
|
||||
isLink
|
||||
href={data.user?.id != null ? `/clients/${data.user.id}` : undefined}
|
||||
/>
|
||||
<InfoRow label={t("cardRequisite.userPhone", "Ulanyjy telefon")} value={data.user?.phone || undefined} />
|
||||
<InfoRow label={t("cardRequisite.userEmail", "Ulanyjy e-poçta")} value={data.user?.email || undefined} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 3: Passport images ────────────────────────────────────────── */}
|
||||
{/* ── Row 3: Pasport maglumatlary ───────────────────────────────────── */}
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard title={t("cardRequisite.passportSection", "Pasport")}>
|
||||
<InfoRow label={t("cardRequisite.passportSeries", "Pasport seriýasy")} value={data.passportSerie} />
|
||||
<InfoRow label={t("cardRequisite.passportNumber", "Pasport belgisi")} value={data.passportId} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 4: Passport images ────────────────────────────────────────── */}
|
||||
<BentoGrid cols={4}>
|
||||
<BentoCard title={t("cardRequisite.passportFile1", "Sahypa 1")}>
|
||||
<PassportImage label={t("cardRequisite.passportFile1", "Pasport (sahypa 1)")} src={data.passport_page1_url} />
|
||||
<PassportImage label={t("cardRequisite.passportFile1", "Pasport (sahypa 1)")} src={data.passportOne} />
|
||||
</BentoCard>
|
||||
<BentoCard title={t("cardRequisite.passportFile2", "Sahypa 2-3")}>
|
||||
<PassportImage label={t("cardRequisite.passportFile2", "Pasport (2-3-nji sahypa)")} src={data.passport_page2_3_url} />
|
||||
<PassportImage label={t("cardRequisite.passportFile2", "Pasport (2-3-nji sahypa)")} src={data.passportTwo} />
|
||||
</BentoCard>
|
||||
<BentoCard title={t("cardRequisite.passportFile3", "Sahypa 8-9")}>
|
||||
<PassportImage label={t("cardRequisite.passportFile3", "Pasport (8-9 sahypa)")} src={data.passport_page8_9_url} />
|
||||
<PassportImage label={t("cardRequisite.passportFile3", "Pasport (8-9 sahypa)")} src={data.passportThree} />
|
||||
</BentoCard>
|
||||
<BentoCard title={t("cardRequisite.passportFile4", "Sahypa 32")}>
|
||||
<PassportImage label={t("cardRequisite.passportFile4", "Pasport (32-nji sahypa)")} src={data.passport_page32_url} />
|
||||
<PassportImage label={t("cardRequisite.passportFile4", "Pasport (32-nji sahypa)")} src={data.passportFour} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AlertCircle, CheckCircle2, XCircle, CheckCheck } from "lucide-react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
import { StatusBadge } from "@/components/ui/statusBadge";
|
||||
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import { StatusBadge } from "@/components/ui/statusBadge";
|
||||
import { useLoanOrderMobiles, useDeleteLoanOrderMobile } from "@/features/loanOrderMobiles/hooks/useLoanOrderMobiles";
|
||||
import type { LoanOrderMobile, LoanOrderMobileStatus } from "@/features/loanOrderMobiles/api/loanOrderMobilesApi";
|
||||
import { useInfiniteBranches } from "@/features/branches/hooks/useBranches";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { getStatusLabel, getStatusOptions, STATUS_BADGE_VARIANTS, type StatusValue } from "@/constants";
|
||||
|
||||
@@ -30,24 +32,43 @@ function LoanOrderStatusBadge({ status }: { status: LoanOrderMobileStatus }) {
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Column IDs ────────────────────────────────────────────────────────────────
|
||||
// ─── Column meta for toggle dropdown ─────────────────────────────────────────
|
||||
|
||||
const COLUMN_IDS = ["id", "loanType", "createdAt", "region", "branch", "firstName", "lastName", "phone", "status"] as const;
|
||||
|
||||
// ─── Filter options ────────────────────────────────────────────────────────────
|
||||
// ─── Filter fields ────────────────────────────────────────────────────────────
|
||||
|
||||
// ─── Filter options (Internal keys/values) ───────────────────────────────────
|
||||
const REGION_OPTIONS = ["Balkan", "Ahal", "Daşoguz", "Lebap", "Mary", "Aşgabat"];
|
||||
const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const;
|
||||
|
||||
// ─── Page Component ────────────────────────────────────────────────────────────
|
||||
// ─── Page Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export default function LoanOrderMobilesPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
const navigate = useNavigate();
|
||||
const deleteMutation = useDeleteLoanOrderMobile();
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
|
||||
// ── State ──────────────────────────────────────────────────────────────────
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const {
|
||||
data: branchesInfiniteData,
|
||||
fetchNextPage: fetchNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
isFetchingNextPage: isFetchingNextBranches,
|
||||
isLoading: isBranchesLoading,
|
||||
} = useInfiniteBranches(branchSearch);
|
||||
|
||||
const branchOptions = useMemo(
|
||||
() =>
|
||||
(branchesInfiniteData?.pages ?? []).flatMap((page) =>
|
||||
(page?.branches ?? []).map((b) => ({
|
||||
value: String(b.id),
|
||||
label: b.name[lang] || b.name.tm,
|
||||
})),
|
||||
),
|
||||
[branchesInfiniteData, lang],
|
||||
);
|
||||
|
||||
const [search, setSearch] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
@@ -60,7 +81,6 @@ export default function LoanOrderMobilesPage() {
|
||||
{ fieldId: "archived", value: "" },
|
||||
]);
|
||||
|
||||
// ── Query params ───────────────────────────────────────────────────────────
|
||||
const queryParams = useMemo(() => {
|
||||
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
|
||||
return {
|
||||
@@ -77,7 +97,8 @@ export default function LoanOrderMobilesPage() {
|
||||
const { data, isLoading } = useLoanOrderMobiles(queryParams);
|
||||
const totalPages = data ? Math.ceil(data.total / perPage) : 1;
|
||||
|
||||
// ── Handlers ───────────────────────────────────────────────────────────────
|
||||
const regionOptions = useMemo(() => REGION_CODES.map((code) => ({ value: code, label: t(`loanOrders.regions.${code}`, code) })), [t]);
|
||||
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
@@ -98,68 +119,69 @@ export default function LoanOrderMobilesPage() {
|
||||
setDeleteId(null);
|
||||
}, [deleteId, deleteMutation]);
|
||||
|
||||
// ── Columns ────────────────────────────────────────────────────────────────
|
||||
const columns = useMemo<ColumnDef<LoanOrderMobile>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("loanOrderMobiles.columns.id", "ID"),
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => <span className="text-xs font-mono text-muted-foreground">{row.original.id}</span>,
|
||||
size: 130,
|
||||
},
|
||||
{
|
||||
id: "loanType",
|
||||
accessorKey: "loanType",
|
||||
header: t("loanOrderMobiles.columns.loanType", "KARZ GÖRNÜŞI"),
|
||||
header: t("Loan type", "KARZ GÖRNÜŞI"),
|
||||
cell: ({ row }) => <span className="text-sm font-medium text-primary hover:underline cursor-pointer">{row.original.loanType}</span>,
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: t("loanOrderMobiles.columns.createdAt", "DÖREDILEN WAGTY"),
|
||||
header: t("Created at", "DÖREDILEN WAGTY"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground whitespace-nowrap">{row.original.createdAt}</span>,
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
id: "region",
|
||||
accessorKey: "region",
|
||||
header: t("loanOrderMobiles.columns.region", "WELAÝAT"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.region}</span>,
|
||||
header: t("Region", "WELAÝAT"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground">{t(`loanOrders.regions.${row.original.region}`, row.original.region)}</span>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
id: "branch",
|
||||
accessorKey: "branch",
|
||||
header: t("loanOrderMobiles.columns.branch", "ŞAHAMÇA"),
|
||||
header: t("Branch", "ŞAHAMÇA"),
|
||||
cell: ({ row }) => <span className="text-sm text-emerald-500 font-medium">{row.original.branch}</span>,
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
id: "firstName",
|
||||
accessorKey: "firstName",
|
||||
header: t("loanOrderMobiles.columns.firstName", "ADY"),
|
||||
header: t("Name", "ADY"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.firstName}</span>,
|
||||
size: 110,
|
||||
},
|
||||
{
|
||||
id: "lastName",
|
||||
accessorKey: "lastName",
|
||||
header: t("loanOrderMobiles.columns.lastName", "FAMILIÝASY"),
|
||||
header: t("Surname", "FAMILIÝASY"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.lastName}</span>,
|
||||
size: 120,
|
||||
},
|
||||
{
|
||||
id: "phone",
|
||||
accessorKey: "phone",
|
||||
header: t("loanOrderMobiles.columns.phone", "TELEFON"),
|
||||
header: t("Phone", "TELEFON"),
|
||||
cell: ({ row }) => <span className="text-sm font-mono text-foreground">{row.original.phone}</span>,
|
||||
size: 110,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("loanOrderMobiles.columns.status", "STATUS"),
|
||||
header: t("Status", "STATUS"),
|
||||
cell: ({ row }) => <LoanOrderStatusBadge status={row.original.status} />,
|
||||
size: 180,
|
||||
},
|
||||
@@ -178,47 +200,51 @@ export default function LoanOrderMobilesPage() {
|
||||
size: 100,
|
||||
},
|
||||
],
|
||||
[t, handleDelete, deleteMutation.isPending, navigate],
|
||||
[t, navigate, handleDelete, deleteMutation.isPending],
|
||||
);
|
||||
|
||||
// ── Column meta for toolbar ────────────────────────────────────────────────
|
||||
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`loanOrderMobiles.columns.${id}`, id) })), [t]);
|
||||
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`loanOrders.columns.${id}`, id) })), [t]);
|
||||
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "region",
|
||||
label: t("loanOrderMobiles.filters.region", "WELAÝAT"),
|
||||
options: REGION_OPTIONS.map((v) => ({ value: v, label: t(v) })),
|
||||
label: t("Region", "WELAÝAT"),
|
||||
options: regionOptions,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
label: t("loanOrderMobiles.filters.status", "STATUS"),
|
||||
label: t("Status", "STATUS"),
|
||||
options: getStatusOptions(t, "loanOrderStatus"),
|
||||
},
|
||||
{
|
||||
id: "branch",
|
||||
label: t("loanOrderMobiles.filters.branch", "ŞAHAMÇA"),
|
||||
options: [],
|
||||
label: t("Branch", "ŞAHAMÇA"),
|
||||
type: "infinite-select",
|
||||
options: branchOptions,
|
||||
loading: isBranchesLoading,
|
||||
isLoadingMore: isFetchingNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
onLoadMore: fetchNextBranches,
|
||||
searchValue: branchSearch,
|
||||
onSearchChange: setBranchSearch,
|
||||
},
|
||||
{
|
||||
id: "archived",
|
||||
label: t("loanOrderMobiles.filters.archived", "ARHIWLENEN"),
|
||||
label: t("loanOrders.filters.archived", "ARHIWLENEN"),
|
||||
options: [
|
||||
{ value: "true", label: t("common.yes", "Hawa") },
|
||||
{ value: "false", label: t("common.no", "Ýok") },
|
||||
],
|
||||
},
|
||||
],
|
||||
[t],
|
||||
[t, regionOptions, branchOptions, isBranchesLoading, isFetchingNextBranches, hasNextBranches, branchSearch],
|
||||
);
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Page Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("loanOrderMobiles.title", "Karz sargytlary")}</h1>
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("loanOrderMobiles.title", "Karz sargytlary (Mobile)")}</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 justify-between">
|
||||
@@ -228,23 +254,24 @@ export default function LoanOrderMobilesPage() {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder={t("common.search", "Gözlemek")}
|
||||
placeholder={t("loanOrderMobiles.searchPlaceholder", "Gözlemek")}
|
||||
/>
|
||||
<CreateButton
|
||||
label={t("loanOrderMobiles.createButton", "Karz sargyt dörediň")}
|
||||
label={t("loanOrderMobiles.createButton", "Karz sargyt dörediñ")}
|
||||
onClick={() => navigate("/loan-order-mobiles/create")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Table Card */}
|
||||
<div className="bg-card border border-border rounded-xl p-4">
|
||||
<DataTableToolbar
|
||||
hideSearch
|
||||
hideAction
|
||||
searchValue={search}
|
||||
onSearchChange={(v) => {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
searchPlaceholder={t("loanOrderMobiles.searchPlaceholder", "Gözlemek")}
|
||||
columns={toggleableColumns}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
@@ -260,8 +287,6 @@ export default function LoanOrderMobilesPage() {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
hideSearch
|
||||
hideAction
|
||||
/>
|
||||
|
||||
<DataTable
|
||||
|
||||
@@ -24,7 +24,7 @@ import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||
import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions";
|
||||
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
||||
import { useInfiniteStaff } from "@/features/operators/hooks/useOperators";
|
||||
import { useAssignRoleToUser, useAssignPermissionToUser, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments";
|
||||
import { useAssignRoleToUser, useAssignPermissionToRole, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
|
||||
type AssignDialogKind = "role" | "permission" | "branch";
|
||||
@@ -43,6 +43,7 @@ export default function ProfilePage() {
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
||||
|
||||
const branches = user?.branches ?? [];
|
||||
const permissions = user?.permissions ?? [];
|
||||
|
||||
// ── Form State for Editing ──
|
||||
const [formData, setFormData] = useState({
|
||||
@@ -233,7 +234,22 @@ export default function ProfilePage() {
|
||||
</InfoRow>
|
||||
|
||||
<InfoRow label={t("users.sections.permissions", "Rugsatlar")}>
|
||||
<span className="text-sm text-muted-foreground">—</span>
|
||||
{permissions.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{permissions.map((p) => (
|
||||
<Link
|
||||
key={p.id}
|
||||
to={`/settings/users/permissions/${p.id}`}
|
||||
className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1 hover:bg-muted transition-colors"
|
||||
>
|
||||
<KeyRound size={11} className="text-muted-foreground" />
|
||||
<span className="text-foreground font-medium">{p.name || p.code || p.id}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">—</span>
|
||||
)}
|
||||
</InfoRow>
|
||||
</BentoCard>
|
||||
|
||||
@@ -336,26 +352,31 @@ const ASSIGN_DIALOG_FIELD_LABELS: Record<AssignDialogKind, string> = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Dialog for assigning a role / permission / branch to a staff user.
|
||||
* Two selects: target user (GET /users/staff) and the resource to assign.
|
||||
* Dialog for assigning a role / branch to a staff user, or assigning a permission to a role.
|
||||
*/
|
||||
function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () => void }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
||||
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const [userValue, setUserValue] = useState("");
|
||||
const isPermission = kind === "permission";
|
||||
|
||||
const [targetSearch, setTargetSearch] = useState("");
|
||||
const [targetValue, setTargetValue] = useState("");
|
||||
const [resourceSearch, setResourceSearch] = useState("");
|
||||
const [resourceValue, setResourceValue] = useState("");
|
||||
const [error, setError] = useState<string | undefined>();
|
||||
|
||||
const staffQuery = useInfiniteStaff(userSearch);
|
||||
// Target query: Staff users when assigning role/branch to a user; Roles when assigning permission to a role.
|
||||
const staffQuery = useInfiniteStaff(targetSearch);
|
||||
const targetRolesQuery = useInfiniteRoles(targetSearch, isPermission);
|
||||
|
||||
// Resource query:
|
||||
const rolesQuery = useInfiniteRoles(resourceSearch, kind === "role");
|
||||
const permissionsQuery = useInfinitePermissions(resourceSearch, kind === "permission");
|
||||
const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch");
|
||||
|
||||
const roleMutation = useAssignRoleToUser();
|
||||
const permissionMutation = useAssignPermissionToUser();
|
||||
const permissionMutation = useAssignPermissionToRole();
|
||||
const branchMutation = useAssignBranchToUser();
|
||||
const isPending = roleMutation.isPending || permissionMutation.isPending || branchMutation.isPending;
|
||||
|
||||
@@ -370,6 +391,24 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
|
||||
[staffQuery.data],
|
||||
);
|
||||
|
||||
const targetRoleOptions: InfiniteSelectOption[] = useMemo(
|
||||
() =>
|
||||
(targetRolesQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.roles ?? [])
|
||||
.map((r) => ({ value: String(r.id), label: r.name || r.code || String(r.id) })),
|
||||
[targetRolesQuery.data],
|
||||
);
|
||||
|
||||
const targetOptions = isPermission ? targetRoleOptions : staffOptions;
|
||||
const targetLabel = isPermission ? t("users.fields.role", "Rol") : t("profile.assign.userLabel", "Ulanyjy (staff)");
|
||||
const targetLoading = isPermission ? targetRolesQuery.isLoading : staffQuery.isLoading;
|
||||
const targetLoadingMore = isPermission ? targetRolesQuery.isFetchingNextPage : staffQuery.isFetchingNextPage;
|
||||
const targetHasNextPage = isPermission ? !!targetRolesQuery.hasNextPage : !!staffQuery.hasNextPage;
|
||||
const loadMoreTargets = () => {
|
||||
if (isPermission) targetRolesQuery.fetchNextPage();
|
||||
else staffQuery.fetchNextPage();
|
||||
};
|
||||
|
||||
const resourceOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
if (kind === "role") {
|
||||
return (rolesQuery.data?.pages ?? [])
|
||||
@@ -406,23 +445,23 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!userValue || !resourceValue) {
|
||||
if (!targetValue || !resourceValue) {
|
||||
setError(t("common.errors.required", "Meýdança hökmany doldurylmaly"));
|
||||
return;
|
||||
}
|
||||
setError(undefined);
|
||||
|
||||
const userId = Number(userValue);
|
||||
const resourceId = Number(resourceValue);
|
||||
const firstId = Number(targetValue);
|
||||
const secondId = Number(resourceValue);
|
||||
const onSuccess = () => {
|
||||
setUserValue("");
|
||||
setTargetValue("");
|
||||
setResourceValue("");
|
||||
onClose();
|
||||
};
|
||||
|
||||
if (kind === "role") roleMutation.mutate({ userId, roleId: resourceId }, { onSuccess });
|
||||
else if (kind === "permission") permissionMutation.mutate({ userId, permissionId: resourceId }, { onSuccess });
|
||||
else branchMutation.mutate({ userId, branchId: resourceId }, { onSuccess });
|
||||
if (kind === "role") roleMutation.mutate({ userId: firstId, roleId: secondId }, { onSuccess });
|
||||
else if (kind === "permission") permissionMutation.mutate({ roleId: firstId, permissionId: secondId }, { onSuccess });
|
||||
else branchMutation.mutate({ userId: firstId, branchId: secondId }, { onSuccess });
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -438,20 +477,20 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
|
||||
<div className="space-y-3">
|
||||
<InfiniteSelect
|
||||
required
|
||||
label={t("profile.assign.userLabel", "Ulanyjy (staff)")}
|
||||
value={userValue}
|
||||
label={targetLabel}
|
||||
value={targetValue}
|
||||
onChange={(v) => {
|
||||
setUserValue(v);
|
||||
setTargetValue(v);
|
||||
if (error) setError(undefined);
|
||||
}}
|
||||
options={staffOptions}
|
||||
options={targetOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
loading={staffQuery.isLoading}
|
||||
isLoadingMore={staffQuery.isFetchingNextPage}
|
||||
hasNextPage={!!staffQuery.hasNextPage}
|
||||
onLoadMore={() => staffQuery.fetchNextPage()}
|
||||
searchValue={userSearch}
|
||||
onSearchChange={setUserSearch}
|
||||
loading={targetLoading}
|
||||
isLoadingMore={targetLoadingMore}
|
||||
hasNextPage={targetHasNextPage}
|
||||
onLoadMore={loadMoreTargets}
|
||||
searchValue={targetSearch}
|
||||
onSearchChange={setTargetSearch}
|
||||
/>
|
||||
|
||||
<InfiniteSelect
|
||||
@@ -478,7 +517,7 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
|
||||
<Button variant="ghost" size="sm" onClick={onClose} disabled={isPending}>
|
||||
{t("common.cancel", "Yza")}
|
||||
</Button>
|
||||
<Button size="sm" onClick={handleSubmit} disabled={!userValue || !resourceValue || isPending}>
|
||||
<Button size="sm" onClick={handleSubmit} disabled={!targetValue || !resourceValue || isPending}>
|
||||
{t("common.save", "Ýatda sakla")}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
|
||||
Reference in New Issue
Block a user