connected api with card balance and and requisites

This commit is contained in:
Jelaletdin12 committed 2026-08-29 12:28:24 +05:00
1 parent 7dfac2bd59
commit d8e903f24c
24 files changed
+2539 -2627

No files matched your search

+7
View File
@@ -16,6 +16,12 @@ export interface AuthUserBranch {
name: LocalizedText; name: LocalizedText;
} }
export interface AuthUserPermission {
id: number;
code?: string;
name?: string;
}
export interface AuthUser { export interface AuthUser {
id?: string | number; id?: string | number;
name: string; name: string;
@@ -26,6 +32,7 @@ export interface AuthUser {
role?: AuthUserRole; role?: AuthUserRole;
avatar?: string; avatar?: string;
branches?: AuthUserBranch[]; branches?: AuthUserBranch[];
permissions?: AuthUserPermission[];
createdAt?: string; createdAt?: string;
} }
+70 -78
View File
@@ -1,104 +1,96 @@
import apiClient from '@/lib/api/client' import apiClient from "@/lib/api/client";
// ─── Types ──────────────────────────────────────────────────────────────────── // ─── 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 { export interface CardBalance {
id: number id: number;
passport_series: string passportNumber: string;
passport_number: string cardLast4: string;
card_number: string expiryMonth: number;
card_expiry_month: string expiryYear: number;
card_expiry_year: string expiryAt: string;
balanceAmount: number;
balanceCurrency: string;
status: string;
checkedAt: string;
createdBy: CardBalanceUser;
createdAt: string;
updatedAt: string;
} }
/** LIST RESPONSE: GET /card-balances */
export interface CardBalanceListResponse { export interface CardBalanceListResponse {
data: CardBalance[] count: number;
total: number cardBalances: CardBalance[];
page: number
per_page: number
} }
export interface CreateCardBalancePayload { /** LIST PARAMS */
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
export type UpdateCardBalancePayload = CreateCardBalancePayload
export interface CardBalanceListParams { export interface CardBalanceListParams {
page?: number page?: number;
per_page?: number limit?: number;
search?: string 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[] = [ // ─── API Functions ─────────────────────────────────────────────────────────────
{
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',
},
]
export const cardBalancesApi = { export const cardBalancesApi = {
getAll: async (params?: CardBalanceListParams): Promise<CardBalanceListResponse> => { getList: async (params: CardBalanceListParams = {}, signal?: AbortSignal): Promise<CardBalanceListResponse> => {
// Mock data kullanmak için: const { page, limit, status, passport_number, created_by } = params;
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<CardBalanceListResponse>("/card-balances", {
params: {
const { data } = await apiClient.get('/card-balances', { params }) page,
return data limit,
status: status || undefined,
passport_number: passport_number || undefined,
created_by: created_by || undefined,
},
signal,
});
return data;
}, },
getById: async (id: number): Promise<CardBalance> => { getById: async (id: number): Promise<CardBalance> => {
// Mock data kullanmak için: const { data } = await apiClient.get<CardBalance>(`/card-balances/${id}`);
const mock = MOCK_CARD_BALANCES.find(b => b.id === id) return data;
if (mock) return mock
const { data } = await apiClient.get(`/card-balances/${id}`)
return data
}, },
create: async (payload: CreateCardBalancePayload): Promise<CardBalance> => { create: async (payload: CardBalancePayload): Promise<CardBalance> => {
const { data } = await apiClient.post('/card-balances', payload) const { data } = await apiClient.post<CardBalance>("/card-balances", payload);
return data return data;
}, },
update: async (id: number, payload: UpdateCardBalancePayload): Promise<CardBalance> => { update: async (id: number, payload: CardBalancePayload): Promise<CardBalance> => {
const { data } = await apiClient.put(`/card-balances/${id}`, payload) const { data } = await apiClient.put<CardBalance>(`/card-balances/${id}`, payload);
return data return data;
}, },
delete: async (id: number): Promise<void> => { 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 { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useForm } from "react-hook-form"; 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 { FormActions } from "@/components/formActions";
import { type CardBalance } from "@/features/cardBalance/api/cardBalanceApi"; import { type CardBalance } from "@/features/cardBalance/api/cardBalanceApi";
import { useCreateCardBalance, useUpdateCardBalance } from "@/features/cardBalance/hooks/useCardBalance"; 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 type { CardBalanceFormData } from "@/features/cardBalance/schemas/cardBalance.schema";
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
interface CardBalanceFormProps { interface CardBalanceFormProps {
mode: "create" | "edit"; mode: "create" | "edit";
@@ -27,28 +29,25 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
// ─── Constants ──────────────────────────────────────────────────────────────── // ─── Constants ────────────────────────────────────────────────────────────────
const PASSPORT_SERIES_OPTIONS = [ const STATUS_OPTIONS: SelectOption[] = [
{ value: "I-MR", label: "I-MR" }, { value: "pending", label: "Garaşylýar" },
{ value: "II-MR", label: "II-MR" }, { value: "approved", label: "Tassyklanan" },
{ value: "I-LB", label: "I-LB" }, { value: "rejected", label: "Ret edilen" },
{ 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 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"); const val = String(i + 1).padStart(2, "0");
return { value: val, label: val }; 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); const year = String(new Date().getFullYear() + i);
return { value: year, label: year }; return { value: year, label: year };
}); });
@@ -63,6 +62,22 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
const updateMutation = useUpdateCardBalance(initialData?.id ?? 0); const updateMutation = useUpdateCardBalance(initialData?.id ?? 0);
const isPending = createMutation.isPending || updateMutation.isPending; 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 { const {
watch, watch,
setValue, setValue,
@@ -71,20 +86,22 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
clearErrors, clearErrors,
setError, setError,
} = useForm<CardBalanceFormData>({ } = useForm<CardBalanceFormData>({
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...initialData } : DEFAULT_FORM_VALUES, defaultValues: initialData ? mapInitial(initialData) : DEFAULT_FORM_VALUES,
}); });
const form = watch(); const form = watch();
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]); const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
const setField = useCallback( const set = useCallback(
(field: keyof CardBalanceFormData) => (value: string) => { <K extends keyof CardBalanceFormData>(key: K, value: CardBalanceFormData[K]) => {
(setValue as (name: keyof CardBalanceFormData, val: string) => void)(field, value); (setValue as (name: K, val: CardBalanceFormData[K]) => void)(key, value);
clearErrors(field); clearErrors(key);
}, },
[setValue, clearErrors], [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 errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg);
const handleSubmit = async () => { const handleSubmit = async () => {
@@ -120,60 +137,101 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
</h1> </h1>
<div className="rounded-lg border border-border bg-card p-6"> <div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Row 1 */}
<FormInput <FormInput
type="searchable-select" type="select"
label={t("Passport series", "Pasport seriýasy")} label={t("Status", "Status")}
value={form.passport_series} value={form.status}
onChange={setField("passport_series")} onChange={setString("status")}
options={PASSPORT_SERIES_OPTIONS} options={STATUS_OPTIONS}
placeholder={t("Select to choose", "Saýlamak üçin basyň")} placeholder={t("Select", "Saýlamak üçin basyň")}
error={errMsg(errors.passport_series)} error={errMsg(errors.status)}
required required
/> />
<FormInput <FormInput
type="text" type="text"
label={t("Passport number", "Pasport belgisi")} label={t("Passport number", "Pasport belgisi")}
value={form.passport_number} value={form.passportNumber}
onChange={setField("passport_number")} onChange={setString("passportNumber")}
placeholder={t("Passport number", "Pasport belgisi")} placeholder={t("Passport number", "Pasport belgisi")}
error={errMsg(errors.passport_number)} error={errMsg(errors.passportNumber)}
required required
/> />
{/* Row 2 — card number full width + 2 selects */}
<FormInput <FormInput
type="text" type="text"
label={t("Card number", "Kart belgisi")} label={t("Card number", "Kart belgisi")}
value={form.card_number} value={form.cardNumber}
onChange={setField("card_number")} onChange={setString("cardNumber")}
placeholder={t("Card number", "Kart belgisi")} placeholder="9800 0000 0000 0000"
error={errMsg(errors.card_number)} error={errMsg(errors.cardNumber)}
required required
/> />
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<FormInput <FormInput
type="select" type="select"
label={t("Card expiry month", "Kart Möhleti (aý)")} label={t("Card expiry month", "Kart Möhleti (aý)")}
value={form.card_expiry_month} value={form.expiryMonth}
onChange={setField("card_expiry_month")} onChange={setString("expiryMonth")}
options={MONTH_OPTIONS} options={MONTH_OPTIONS}
placeholder={t("Select", "Saýlamak üçin basyň")} placeholder={t("Select", "Saýlamak üçin basyň")}
error={errMsg(errors.card_expiry_month)} error={errMsg(errors.expiryMonth)}
required required
/> />
<FormInput <FormInput
type="select" type="select"
label={t("Card expiry year", "Kart Möhleti (ýyl)")} label={t("Card expiry year", "Kart Möhleti (ýyl)")}
value={form.card_expiry_year} value={form.expiryYear}
onChange={setField("card_expiry_year")} onChange={setString("expiryYear")}
options={YEAR_OPTIONS} options={YEAR_OPTIONS}
placeholder={t("Select", "Saýlamak üçin basyň")} placeholder={t("Select", "Saýlamak üçin basyň")}
error={errMsg(errors.card_expiry_year)} error={errMsg(errors.expiryYear)}
required required
/> />
</div> </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> </div>
<FormActions <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 { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from 'sonner' import { toast } from "sonner";
import { useTranslation } from 'react-i18next' import { useTranslation } from "react-i18next";
import { import { cardBalancesApi, type CardBalanceListParams, type CardBalancePayload } from "../api/cardBalanceApi";
cardBalancesApi,
type CardBalanceListParams,
type CreateCardBalancePayload,
type UpdateCardBalancePayload,
} 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({ return useQuery({
queryKey: [QUERY_KEY, params], queryKey: cardBalanceKeys.list(params),
queryFn: () => cardBalancesApi.getAll(params), queryFn: ({ signal }) => cardBalancesApi.getList(params, signal),
}) placeholderData: (prev) => prev,
});
} }
// ─── Single ───────────────────────────────────────────────────────────────────
export function useCardBalance(id: number) { export function useCardBalance(id: number) {
return useQuery({ return useQuery({
queryKey: [QUERY_KEY, id], queryKey: cardBalanceKeys.detail(id),
queryFn: () => cardBalancesApi.getById(id), queryFn: () => cardBalancesApi.getById(id),
enabled: !!id, enabled: !!id,
}) });
} }
// ─── Create ───────────────────────────────────────────────────────────────────
export function useCreateCardBalance() { export function useCreateCardBalance() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
const { t } = useTranslation() const { t } = useTranslation();
return useMutation({ return useMutation({
mutationFn: (payload: CreateCardBalancePayload) => cardBalancesApi.create(payload), mutationFn: (payload: CardBalancePayload) => cardBalancesApi.create(payload),
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] }) queryClient.invalidateQueries({ queryKey: cardBalanceKeys.lists() });
toast.success(t('Card balance created successfully', 'Kart galyndysy üstünlikli döredildi')) toast.success(t("cardBalance.createSuccess", "Kart galyndysy üstünlikli döredildi"));
}, },
}) });
} }
// ─── Update ───────────────────────────────────────────────────────────────────
export function useUpdateCardBalance(id: number) { export function useUpdateCardBalance(id: number) {
const queryClient = useQueryClient() const queryClient = useQueryClient();
const { t } = useTranslation() const { t } = useTranslation();
return useMutation({ return useMutation({
mutationFn: (payload: UpdateCardBalancePayload) => cardBalancesApi.update(id, payload), mutationFn: (payload: CardBalancePayload) => cardBalancesApi.update(id, payload),
onSuccess: () => { onSuccess: (updated) => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] }) queryClient.invalidateQueries({ queryKey: cardBalanceKeys.lists() });
toast.success(t('Card balance updated successfully', 'Kart galyndysy üstünlikli üýtgedildi')) queryClient.setQueryData(cardBalanceKeys.detail(id), updated);
toast.success(t("cardBalance.updateSuccess", "Kart galyndysy üstünlikli üýtgedildi"));
}, },
}) });
} }
// ─── Delete ───────────────────────────────────────────────────────────────────
export function useDeleteCardBalance() { export function useDeleteCardBalance() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
const { t } = useTranslation() const { t } = useTranslation();
return useMutation({ return useMutation({
mutationFn: (id: number) => cardBalancesApi.delete(id), mutationFn: (id: number) => cardBalancesApi.delete(id),
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] }) queryClient.invalidateQueries({ queryKey: cardBalanceKeys.lists() });
toast.success(t('Card balance deleted successfully', 'Kart galyndysy üstünlikli öçürildi')) 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 { z } from "zod";
import type { CreateCardBalancePayload } from '../api/cardBalanceApi' import type { CardBalance, CardBalancePayload } from "../api/cardBalanceApi";
export const cardBalanceFormSchema = z.object({ export const cardBalanceFormSchema = z.object({
passport_series: z.string().min(1, 'validation.required'), status: z.string().min(1, "validation.required"),
passport_number: z.string().min(1, 'validation.required'), passportNumber: z.string().min(1, "validation.required"),
card_number: z.string().min(1, 'validation.required'), cardNumber: z.string().min(1, "validation.required"),
card_expiry_month: z.string().min(1, 'validation.required'), expiryMonth: z.string().min(1, "validation.required"),
card_expiry_year: 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 = { export const DEFAULT_FORM_VALUES: CardBalanceFormData = {
passport_series: '', status: "",
passport_number: '', passportNumber: "",
card_number: '', cardNumber: "",
card_expiry_month: '', expiryMonth: "",
card_expiry_year: '', 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 { return {
passport_series: data.passport_series, status: data.status,
passport_number: data.passport_number, passportNumber: data.passportNumber,
card_number: data.card_number, cardNumber: data.cardNumber,
card_expiry_month: data.card_expiry_month, expiryMonth: Number(data.expiryMonth),
card_expiry_year: data.card_expiry_year, 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 ──────────────────────────────────────────────────────────────────── // ─── 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 { export interface CardRequisite {
id: string id: number;
status: CardRequisiteStatus uniqueId: string;
note: string user: CardRequisiteUser;
created_at: string cardType: CardRequisiteCardType;
cardNumber: string;
// Card cardMonth: string;
card_type: string cardYear: string;
card_number: string region: string;
card_expiry_month: string branch: CardRequisiteBranch;
card_expiry_year: string customerName: string;
customerSurname: string;
// Location customerPatronicName: string;
province_id: string bornAt: string;
branch_id: string phone: string;
province_name?: string passportSerie: string;
branch_name?: string passportId: string;
passportOne: string;
// Personal passportTwo: string;
first_name: string passportThree: string;
last_name: string passportFour: string;
middle_name?: string status: string;
birth_date: string notes: string;
phone: string createdAt: string;
updatedAt: 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
} }
/** LIST RESPONSE: GET /card-rekwizit-orders */
export interface CardRequisiteListResponse { export interface CardRequisiteListResponse {
data: CardRequisite[] count: number;
total: number cardRekwizitOrders: CardRequisite[];
page: number
per_page: number
} }
export interface CreateCardRequisitePayload { /** LIST PARAMS */
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
export interface CardRequisiteListParams { export interface CardRequisiteListParams {
page?: number page?: number;
per_page?: number limit?: number;
search?: string status?: string;
branch_id?: number | string;
user_id?: number | string;
card_type_id?: number | string;
region?: string;
search?: string;
} }
// ─── Helpers ────────────────────────────────────────────────────────────────── /** CREATE / UPDATE PAYLOAD (camelCase, JSON) */
export interface CardRequisitePayload {
function buildFormData(payload: CreateCardRequisitePayload): FormData { bornAt: string;
const fd = new FormData() branchId: number;
cardMonth: string;
const textFields: (keyof Omit< cardNumber: string;
CreateCardRequisitePayload, cardTypeId: number;
'passport_page1' | 'passport_page2_3' | 'passport_page8_9' | 'passport_page32' cardYear: string;
>)[] = [ customerName: string;
'status', 'note', 'card_type', 'card_number', 'card_expiry_month', customerPatronicName: string;
'card_expiry_year', 'province_id', 'branch_id', 'first_name', 'last_name', customerSurname: string;
'middle_name', 'birth_date', 'phone', 'passport_series', 'passport_number', notes: string;
] passportFour: string;
passportId: string;
textFields.forEach((key) => { passportOne: string;
const val = payload[key] passportSerie: string;
if (val !== undefined && val !== null) fd.append(key, val) passportThree: string;
}) passportTwo: string;
phone: string;
if (payload.passport_page1) fd.append('passport_page1', payload.passport_page1) region: string;
if (payload.passport_page2_3) fd.append('passport_page2_3', payload.passport_page2_3) status: string;
if (payload.passport_page8_9) fd.append('passport_page8_9', payload.passport_page8_9) uniqueId: string;
if (payload.passport_page32) fd.append('passport_page32', payload.passport_page32) userId: number;
return fd
} }
// ─── Mock data ───────────────────────────────────────────────────────────────── // ─── API Functions ─────────────────────────────────────────────────────────────
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 ────────────────────────────────────────────────────────────
export const cardRequisitesApi = { export const cardRequisitesApi = {
getAll: async (params?: CardRequisiteListParams): Promise<CardRequisiteListResponse> => { getList: async (params: CardRequisiteListParams = {}, signal?: AbortSignal): Promise<CardRequisiteListResponse> => {
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz: const { page, limit, status, branch_id, user_id, card_type_id, region } = params;
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<CardRequisiteListResponse>("/card-rekwizit-orders", {
params: {
const { data } = await apiClient.get('/card-requisites', { params }) page,
return data 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> => { getById: async (id: number): Promise<CardRequisite> => {
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz: const { data } = await apiClient.get<CardRequisite>(`/card-rekwizit-orders/${id}`);
const mock = MOCK_CARD_REQUISITES.find(r => r.id === id) return data;
if (mock) return mock
const { data } = await apiClient.get(`/card-requisites/${id}`)
return data
}, },
create: async (payload: CreateCardRequisitePayload): Promise<CardRequisite> => { create: async (payload: CardRequisitePayload): Promise<CardRequisite> => {
const { data } = await apiClient.post('/card-requisites', buildFormData(payload), { const { data } = await apiClient.post<CardRequisite>("/card-rekwizit-orders", payload);
headers: { 'Content-Type': 'multipart/form-data' }, return data;
})
return data
}, },
update: async (id: string, payload: UpdateCardRequisitePayload): Promise<CardRequisite> => { update: async (id: number, payload: CardRequisitePayload): Promise<CardRequisite> => {
const { data } = await apiClient.post(`/card-requisites/${id}`, buildFormData(payload), { const { data } = await apiClient.put<CardRequisite>(`/card-rekwizit-orders/${id}`, payload);
headers: { 'Content-Type': 'multipart/form-data' }, return data;
})
return data
}, },
delete: async (id: string): Promise<void> => { delete: async (id: number): Promise<void> => {
await apiClient.delete(`/card-requisites/${id}`) 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 { CreditCard, User, FileText } from "lucide-react";
import type { LucideIcon } 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 { FormActions } from "@/components/formActions";
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2"; import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
import { BentoGrid, BentoCard } from "@/components/bento"; import { BentoGrid, BentoCard } from "@/components/bento";
@@ -15,6 +17,10 @@ import type { CardRequisite } from "../api/cardRequisitesApi";
import { useCreateCardRequisite, useUpdateCardRequisite } from "../hooks/useCardRequisites"; import { useCreateCardRequisite, useUpdateCardRequisite } from "../hooks/useCardRequisites";
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardRequisite.schema"; import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardRequisite.schema";
import type { CardRequisiteFormData } 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 ──────────────────────────────────────────────────────────────────── // ─── Types ────────────────────────────────────────────────────────────────────
@@ -36,17 +42,20 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
// ─── Constants ──────────────────────────────────────────────────────────────── // ─── Constants ────────────────────────────────────────────────────────────────
const STATUS_OPTIONS = [ const STATUS_OPTIONS: SelectOption[] = [
{ value: "pending", label: "Garaşylýar" }, { value: "pending", label: "Garaşylýar" },
{ value: "approved", label: "Tassyklanan" }, { value: "approved", label: "Tassyklanan" },
{ value: "rejected", label: "Ret edilen" }, { value: "rejected", label: "Ret edilen" },
]; ];
const CARD_TYPE_OPTIONS = [ const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const;
{ value: "altyn_asyr", label: "Altyn Asyr" },
{ value: "visa", label: "Visa" }, function getRegionOptions(t: TFunction): SelectOption[] {
{ value: "mastercard", label: "MasterCard" }, return REGION_CODES.map((code) => ({
]; value: code,
label: t(`cardRequisites.regions.${code}`, code),
}));
}
const PASSPORT_SERIES_OPTIONS = [ const PASSPORT_SERIES_OPTIONS = [
{ value: "I-MR", label: "I-MR" }, { value: "I-MR", label: "I-MR" },
@@ -58,50 +67,12 @@ const PASSPORT_SERIES_OPTIONS = [
{ value: "B", label: "B" }, { value: "B", label: "B" },
]; ];
const PROVINCE_OPTIONS = [ const MONTH_OPTIONS: SelectOption[] = Array.from({ length: 12 }, (_, i) => {
{ 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 val = String(i + 1).padStart(2, "0"); const val = String(i + 1).padStart(2, "0");
return { value: val, label: val }; 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); const year = String(new Date().getFullYear() + i);
return { value: year, label: year }; return { value: year, label: year };
}); });
@@ -109,24 +80,26 @@ const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
function mapInitial(data: CardRequisite): CardRequisiteFormData { function mapInitial(data: CardRequisite): CardRequisiteFormData {
return { return {
status: data.status ?? "pending", status: data.status ?? "pending",
note: data.note ?? "", notes: data.notes ?? "",
card_type: data.card_type ?? "", region: data.region ?? "",
card_number: data.card_number ?? "", cardTypeId: data.cardType?.id != null ? String(data.cardType.id) : "",
card_expiry_month: data.card_expiry_month ?? "", branchId: data.branch?.id != null ? String(data.branch.id) : "",
card_expiry_year: data.card_expiry_year ?? "", userId: data.user?.id != null ? String(data.user.id) : "",
province_id: data.province_id ?? "", uniqueId: data.uniqueId ?? "",
branch_id: data.branch_id ?? "", cardNumber: data.cardNumber ?? "",
first_name: data.first_name ?? "", cardMonth: data.cardMonth ?? "",
last_name: data.last_name ?? "", cardYear: data.cardYear ?? "",
middle_name: data.middle_name ?? "", customerName: data.customerName ?? "",
birth_date: data.birth_date ?? "", customerSurname: data.customerSurname ?? "",
customerPatronicName: data.customerPatronicName ?? "",
bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "",
phone: data.phone ?? "", phone: data.phone ?? "",
passport_series: data.passport_series ?? "", passportSerie: data.passportSerie ?? "",
passport_number: data.passport_number ?? "", passportId: data.passportId ?? "",
passport_page1: null, passportOne: data.passportOne ?? "",
passport_page2_3: null, passportTwo: data.passportTwo ?? "",
passport_page8_9: null, passportThree: data.passportThree ?? "",
passport_page32: null, passportFour: data.passportFour ?? "",
}; };
} }
@@ -148,9 +121,9 @@ const STEPS: StepDef[] = [
titleKey: "Card", titleKey: "Card",
titleFallback: "Kart", titleFallback: "Kart",
subtitleKey: "cardRequisiteForm.steps.card.subtitle", subtitleKey: "cardRequisiteForm.steps.card.subtitle",
subtitleFallback: "Görnüş & lokasiýa", subtitleFallback: "Görnüş & maglumatlar",
icon: CreditCard, icon: CreditCard,
validate: (form, mode) => validateStep(0, form, mode), validate: (form) => validateStep(0, form),
}, },
{ {
id: "personal", id: "personal",
@@ -159,7 +132,7 @@ const STEPS: StepDef[] = [
subtitleKey: "cardRequisiteForm.steps.personal.subtitle", subtitleKey: "cardRequisiteForm.steps.personal.subtitle",
subtitleFallback: "At & telefon", subtitleFallback: "At & telefon",
icon: User, icon: User,
validate: (form, mode) => validateStep(1, form, mode), validate: (form) => validateStep(1, form),
}, },
{ {
id: "passport", id: "passport",
@@ -168,7 +141,7 @@ const STEPS: StepDef[] = [
subtitleKey: "cardRequisiteForm.steps.passport.subtitle", subtitleKey: "cardRequisiteForm.steps.passport.subtitle",
subtitleFallback: "Resminamalar", subtitleFallback: "Resminamalar",
icon: FileText, icon: FileText,
validate: (form, mode) => validateStep(2, form, mode), validate: (form) => validateStep(2, form),
}, },
]; ];
@@ -179,12 +152,58 @@ interface StepContentProps {
errors: FlatErrors; errors: FlatErrors;
set: <K extends keyof CardRequisiteFormData>(k: K, v: CardRequisiteFormData[K]) => void; set: <K extends keyof CardRequisiteFormData>(k: K, v: CardRequisiteFormData[K]) => void;
t: TFunction; t: TFunction;
initialData?: CardRequisite;
} }
// ─── Step panels ────────────────────────────────────────────────────────────── // ─── Step panels ──────────────────────────────────────────────────────────────
function StepCard({ form, errors, set, t }: StepContentProps) { function StepCard({ form, errors, set, t, initialData }: StepContentProps) {
const branchOptions = BRANCH_OPTIONS[form.province_id] ?? []; 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 ( return (
<div className="space-y-4"> <div className="space-y-4">
@@ -192,103 +211,148 @@ function StepCard({ form, errors, set, t }: StepContentProps) {
<BentoCard> <BentoCard>
<FormInput <FormInput
type="select" type="select"
label={t("loanOrderForm.labels.status") || "Status"} label={t("cardRequisiteForm.labels.status") || "Statusy"}
required required
value={form.status} value={form.status}
onChange={(v) => set("status", v)} onChange={(v) => set("status", v)}
options={STATUS_OPTIONS} options={STATUS_OPTIONS}
error={errors.status}
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} 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>
<BentoCard> <BentoCard>
<FormInput <FormInput
type="text" type="text"
label={t("Note") || "Bellik"} label={t("Note") || "Bellik"}
value={form.note} value={form.notes}
onChange={(v) => set("note", v)} onChange={(v) => set("notes", v)}
placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."} placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."}
/> />
</BentoCard> </BentoCard>
</BentoGrid> </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> </div>
); );
} }
@@ -302,10 +366,10 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
type="text" type="text"
label={t("Name") || "Ady"} label={t("Name") || "Ady"}
required required
value={form.first_name} value={form.customerName}
onChange={(v) => set("first_name", v)} onChange={(v) => set("customerName", v)}
placeholder={t("Name") || "Ady"} placeholder={t("Name") || "Ady"}
error={errors.first_name} error={errors.customerName}
/> />
</BentoCard> </BentoCard>
<BentoCard> <BentoCard>
@@ -313,18 +377,18 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
type="text" type="text"
label={t("Surname") || "Familiýasy"} label={t("Surname") || "Familiýasy"}
required required
value={form.last_name} value={form.customerSurname}
onChange={(v) => set("last_name", v)} onChange={(v) => set("customerSurname", v)}
placeholder={t("Surname") || "Familiýasy"} placeholder={t("Surname") || "Familiýasy"}
error={errors.last_name} error={errors.customerSurname}
/> />
</BentoCard> </BentoCard>
<BentoCard> <BentoCard>
<FormInput <FormInput
type="text" type="text"
label={t("Patronic name") || "Atasynyň ady"} label={t("Patronic name") || "Atasynyň ady"}
value={form.middle_name} value={form.customerPatronicName}
onChange={(v) => set("middle_name", v)} onChange={(v) => set("customerPatronicName", v)}
placeholder={t("Patronic name") || "Atasynyň ady"} placeholder={t("Patronic name") || "Atasynyň ady"}
/> />
</BentoCard> </BentoCard>
@@ -336,9 +400,9 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
type="date" type="date"
label={t("Date of birth") || "Doglan güni"} label={t("Date of birth") || "Doglan güni"}
required required
value={form.birth_date} value={form.bornAt}
onChange={(v) => set("birth_date", v)} onChange={(v) => set("bornAt", v)}
error={errors.birth_date} error={errors.bornAt}
/> />
</BentoCard> </BentoCard>
<BentoCard> <BentoCard>
@@ -357,27 +421,7 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
); );
} }
function StepPassport({ function StepPassport({ form, errors, set, t }: StepContentProps) {
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)
: [];
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<BentoGrid cols={2}> <BentoGrid cols={2}>
@@ -386,11 +430,11 @@ function StepPassport({
type="searchable-select" type="searchable-select"
label={t("Passport serie") || "Pasport seriýasy"} label={t("Passport serie") || "Pasport seriýasy"}
required required
value={form.passport_series} value={form.passportSerie}
onChange={(v) => set("passport_series", v)} onChange={(v) => set("passportSerie", v)}
options={PASSPORT_SERIES_OPTIONS} options={PASSPORT_SERIES_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.passport_series} error={errors.passportSerie}
/> />
</BentoCard> </BentoCard>
<BentoCard> <BentoCard>
@@ -398,77 +442,49 @@ function StepPassport({
type="text" type="text"
label={t("Passport id") || "Pasport belgisi"} label={t("Passport id") || "Pasport belgisi"}
required required
value={form.passport_number} value={form.passportId}
onChange={(v) => set("passport_number", v)} onChange={(v) => set("passportId", v)}
placeholder={t("Passport id") || "Pasport belgisi"} placeholder={t("Passport id") || "Pasport belgisi"}
error={errors.passport_number} error={errors.passportId}
/> />
</BentoCard> </BentoCard>
</BentoGrid> </BentoGrid>
{existingFiles.length > 0 && (
<BentoGrid cols={4}>
{existingFiles.map(({ url, label }) => (
<BentoCard key={label} title={label}>
<a href={url} target="_blank" rel="noopener noreferrer" className="text-xs text-primary underline truncate block">
{t("loanOrderForm.fileLabels.viewFile") || "Faýly gör"}
</a>
</BentoCard>
))}
</BentoGrid>
)}
<BentoGrid cols={2}> <BentoGrid cols={2}>
<BentoCard> <BentoCard>
<FormInput <DocumentUpload
type="file" label={t("Passport (page 1)") || "Pasport (sahypa 1)"}
label={ value={form.passportOne}
mode === "edit" onChange={(v) => set("passportOne", v)}
? t("loanOrderForm.fileLabels.replacePage1") || "Pasport (sahypa 1) (çalyşmak)" error={errors.passportOne}
: t("Passport (page 1)") || "Pasport (sahypa 1)" accept="image/*"
}
required={mode === "create"}
accept="image/*,.pdf"
fileValue={form.passport_page1}
onFileChange={(f) => set("passport_page1", f)}
error={errors.passport_page1}
/> />
</BentoCard> </BentoCard>
<BentoCard> <BentoCard>
<FormInput <DocumentUpload
type="file" label={t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)"}
label={ value={form.passportTwo}
mode === "edit" onChange={(v) => set("passportTwo", v)}
? t("loanOrderForm.fileLabels.replacePage23") || "Pasport (2-3-nji sahypa) (çalyşmak)" error={errors.passportTwo}
: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)" accept="image/*"
}
required={mode === "create"}
accept="image/*,.pdf"
fileValue={form.passport_page2_3}
onFileChange={(f) => set("passport_page2_3", f)}
error={errors.passport_page2_3}
/> />
</BentoCard> </BentoCard>
<BentoCard> <BentoCard>
<FormInput <DocumentUpload
type="file"
label={t("Passport (page 8-9)") || "Pasport (8-9 sahypa)"} label={t("Passport (page 8-9)") || "Pasport (8-9 sahypa)"}
required={mode === "create"} value={form.passportThree}
accept="image/*,.pdf" onChange={(v) => set("passportThree", v)}
fileValue={form.passport_page8_9} error={errors.passportThree}
onFileChange={(f) => set("passport_page8_9", f)} accept="image/*"
error={errors.passport_page8_9}
/> />
</BentoCard> </BentoCard>
<BentoCard> <BentoCard>
<FormInput <DocumentUpload
type="file"
label={t("Passport (page 32)") || "Pasport (32-nji sahypa)"} label={t("Passport (page 32)") || "Pasport (32-nji sahypa)"}
required={mode === "create"} value={form.passportFour}
accept="image/*,.pdf" onChange={(v) => set("passportFour", v)}
fileValue={form.passport_page32} error={errors.passportFour}
onFileChange={(f) => set("passport_page32", f)} accept="image/*"
error={errors.passport_page32}
/> />
</BentoCard> </BentoCard>
</BentoGrid> </BentoGrid>
@@ -483,7 +499,7 @@ export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps)
const navigate = useNavigate(); const navigate = useNavigate();
const createMutation = useCreateCardRequisite(); const createMutation = useCreateCardRequisite();
const updateMutation = useUpdateCardRequisite(initialData?.id ?? ""); const updateMutation = useUpdateCardRequisite(initialData?.id ?? 0);
const isPending = createMutation.isPending || updateMutation.isPending; const isPending = createMutation.isPending || updateMutation.isPending;
const { const {
@@ -534,7 +550,7 @@ export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps)
return { ...fromRHF, ...allSubmittedErrors }; return { ...fromRHF, ...allSubmittedErrors };
}, [rhfErrors, 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 ───────────────────────────────────────────────────────────── // ── Navigation ─────────────────────────────────────────────────────────────
@@ -647,7 +663,7 @@ export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps)
{/* Step content */} {/* Step content */}
{currentStep === 0 && <StepCard {...stepProps} />} {currentStep === 0 && <StepCard {...stepProps} />}
{currentStep === 1 && <StepPersonal {...stepProps} />} {currentStep === 1 && <StepPersonal {...stepProps} />}
{currentStep === 2 && <StepPassport {...stepProps} mode={mode} initialData={initialData} />} {currentStep === 2 && <StepPassport {...stepProps} />}
{/* Actions */} {/* Actions */}
<FormActions <FormActions
@@ -1,96 +1,80 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from 'sonner' import { toast } from "sonner";
import { useTranslation } from 'react-i18next' import { useTranslation } from "react-i18next";
import { import { cardRequisitesApi, type CardRequisiteListParams, type CardRequisitePayload } from "../api/cardRequisitesApi";
cardRequisitesApi,
type CardRequisiteListParams,
type CreateCardRequisitePayload,
type UpdateCardRequisitePayload,
} 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 ───────────────────────────────────────────────────────────────────── // ─── List ─────────────────────────────────────────────────────────────────────
export function useCardRequisites(params?: CardRequisiteListParams) { export function useCardRequisites(params: CardRequisiteListParams = {}) {
return useQuery({ return useQuery({
queryKey: [QUERY_KEY, params], queryKey: cardRequisiteKeys.list(params),
queryFn: () => cardRequisitesApi.getAll(params), queryFn: ({ signal }) => cardRequisitesApi.getList(params, signal),
}) placeholderData: (prev) => prev,
});
} }
// ─── Single ─────────────────────────────────────────────────────────────────── // ─── Single ───────────────────────────────────────────────────────────────────
export function useCardRequisite(id: string) { export function useCardRequisite(id: number) {
return useQuery({ return useQuery({
queryKey: [QUERY_KEY, id], queryKey: cardRequisiteKeys.detail(id),
queryFn: () => cardRequisitesApi.getById(id), queryFn: () => cardRequisitesApi.getById(id),
enabled: !!id, enabled: !!id,
}) });
} }
// ─── Create ─────────────────────────────────────────────────────────────────── // ─── Create ───────────────────────────────────────────────────────────────────
export function useCreateCardRequisite() { export function useCreateCardRequisite() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
const { t } = useTranslation() const { t } = useTranslation();
return useMutation({ return useMutation({
mutationFn: (payload: CreateCardRequisitePayload) => cardRequisitesApi.create(payload), mutationFn: (payload: CardRequisitePayload) => cardRequisitesApi.create(payload),
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] }) queryClient.invalidateQueries({ queryKey: cardRequisiteKeys.lists() });
toast.success(t('Card requisite created successfully', 'Kart rekwiziti üstünlikli döredildi')) toast.success(t("cardRequisites.createSuccess", "Kart rekwiziti üstünlikli döredildi"));
}, },
}) });
} }
// ─── Update ─────────────────────────────────────────────────────────────────── // ─── Update ───────────────────────────────────────────────────────────────────
export function useUpdateCardRequisite(id: string) { export function useUpdateCardRequisite(id: number) {
const queryClient = useQueryClient() const queryClient = useQueryClient();
const { t } = useTranslation() const { t } = useTranslation();
return useMutation({ return useMutation({
mutationFn: (payload: UpdateCardRequisitePayload) => cardRequisitesApi.update(id, payload), mutationFn: (payload: CardRequisitePayload) => cardRequisitesApi.update(id, payload),
onSuccess: () => { onSuccess: (updated) => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] }) queryClient.invalidateQueries({ queryKey: cardRequisiteKeys.lists() });
toast.success(t('Card requisite updated successfully', 'Kart rekwiziti üstünlikli üýtgedildi')) queryClient.setQueryData(cardRequisiteKeys.detail(id), updated);
toast.success(t("cardRequisites.updateSuccess", "Kart rekwiziti üstünlikli üýtgedildi"));
}, },
}) });
} }
// ─── Delete ─────────────────────────────────────────────────────────────────── // ─── Delete ───────────────────────────────────────────────────────────────────
export function useDeleteCardRequisite() { export function useDeleteCardRequisite() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
const { t } = useTranslation() const { t } = useTranslation();
return useMutation({ return useMutation({
mutationFn: (id: string) => cardRequisitesApi.delete(id), mutationFn: (id: number) => cardRequisitesApi.delete(id),
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] }) queryClient.invalidateQueries({ queryKey: cardRequisiteKeys.lists() });
toast.success(t('Card requisite deleted successfully', 'Kart rekwiziti üstünlikli öçürildi')) 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 { z } from "zod";
import i18next from "i18next"; 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"]; const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
export const cardRequisiteFormSchema = z.object({ export const cardRequisiteFormSchema = z.object({
status: z.string().min(1, "validation.required"), status: z.string().min(1, "validation.required"),
note: z.string().optional(), notes: z.string().optional(),
card_type: z.string().min(1, "validation.required"), region: z.string().min(1, "validation.required"),
card_number: z.string().min(1, "validation.required"), cardTypeId: z.string().min(1, "validation.required"),
card_expiry_month: z.string().min(1, "validation.required"), branchId: z.string().min(1, "validation.required"),
card_expiry_year: z.string().min(1, "validation.required"), userId: z.string().min(1, "validation.required"),
province_id: z.string().min(1, "validation.required"), uniqueId: z.string().optional(),
branch_id: z.string().min(1, "validation.required"), cardNumber: z.string().optional(),
first_name: z.string().min(1, "validation.required"), cardMonth: z.string().optional(),
last_name: z.string().min(1, "validation.required"), cardYear: z.string().optional(),
middle_name: z.string().optional(), customerName: z.string().min(1, "validation.required"),
birth_date: 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 phone: z
.string() .string()
.min(1, "validation.required") .min(1, "validation.required")
@@ -36,12 +37,12 @@ export const cardRequisiteFormSchema = z.object({
}, },
{ message: "validation.invalidPhonePrefix" }, { message: "validation.invalidPhonePrefix" },
), ),
passport_series: z.string().min(1, "validation.required"), passportSerie: z.string().min(1, "validation.required"),
passport_number: z.string().min(1, "validation.required"), passportId: z.string().min(1, "validation.required"),
passport_page1: z.custom<File | null>().nullable(), passportOne: z.string().optional(),
passport_page2_3: z.custom<File | null>().nullable(), passportTwo: z.string().optional(),
passport_page8_9: z.custom<File | null>().nullable(), passportThree: z.string().optional(),
passport_page32: z.custom<File | null>().nullable(), passportFour: z.string().optional(),
}); });
export type CardRequisiteFormData = z.infer<typeof cardRequisiteFormSchema>; 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>>> = { export const stepSchemas: Record<number, z.ZodType<Partial<CardRequisiteFormData>>> = {
0: cardRequisiteFormSchema.pick({ 0: cardRequisiteFormSchema.pick({
status: true, status: true,
card_type: true, region: true,
card_number: true, cardTypeId: true,
card_expiry_month: true, branchId: true,
card_expiry_year: true, userId: true,
province_id: true, uniqueId: true,
branch_id: true, cardNumber: true,
cardMonth: true,
cardYear: true,
notes: true,
}), }),
1: cardRequisiteFormSchema.pick({ 1: cardRequisiteFormSchema.pick({
first_name: true, customerName: true,
last_name: true, customerSurname: true,
birth_date: true, customerPatronicName: true,
bornAt: true,
phone: true, phone: true,
}), }),
2: z.object({ 2: cardRequisiteFormSchema.pick({
passport_series: z.string().min(1, "validation.required"), passportSerie: true,
passport_number: z.string().min(1, "validation.required"), passportId: true,
passport_page1: fileRequired, passportOne: true,
passport_page2_3: fileRequired, passportTwo: true,
passport_page8_9: fileRequired, passportThree: true,
passport_page32: fileRequired, passportFour: true,
}), }),
}; };
@@ -76,26 +81,7 @@ function translateMsg(msg: string): string {
return msg.startsWith("validation.") ? i18next.t(msg, msg) : msg; return msg.startsWith("validation.") ? i18next.t(msg, msg) : msg;
} }
export function validateStep( export function validateStep(stepIndex: number, form: CardRequisiteFormData): Partial<Record<keyof CardRequisiteFormData, string>> {
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;
}
const schema = stepSchemas[stepIndex]; const schema = stepSchemas[stepIndex];
if (!schema) return {}; if (!schema) return {};
const result = schema.safeParse(form); const result = schema.safeParse(form);
@@ -110,46 +96,50 @@ export function validateStep(
export const DEFAULT_FORM_VALUES: CardRequisiteFormData = { export const DEFAULT_FORM_VALUES: CardRequisiteFormData = {
status: "pending", status: "pending",
note: "", notes: "",
card_type: "", region: "",
card_number: "", cardTypeId: "",
card_expiry_month: "", branchId: "",
card_expiry_year: "", userId: "",
province_id: "", uniqueId: "",
branch_id: "", cardNumber: "",
first_name: "", cardMonth: "",
last_name: "", cardYear: "",
middle_name: "", customerName: "",
birth_date: "", customerSurname: "",
customerPatronicName: "",
bornAt: "",
phone: "", phone: "",
passport_series: "", passportSerie: "",
passport_number: "", passportId: "",
passport_page1: null, passportOne: "",
passport_page2_3: null, passportTwo: "",
passport_page8_9: null, passportThree: "",
passport_page32: null, passportFour: "",
}; };
export function buildPayload(data: CardRequisiteFormData): CreateCardRequisitePayload { export function buildPayload(data: CardRequisiteFormData): CardRequisitePayload {
return { return {
status: data.status as CardRequisiteStatus, status: data.status,
note: data.note || undefined, notes: data.notes || "",
card_type: data.card_type, region: data.region,
card_number: data.card_number, cardTypeId: Number(data.cardTypeId),
card_expiry_month: data.card_expiry_month, branchId: Number(data.branchId),
card_expiry_year: data.card_expiry_year, userId: Number(data.userId),
province_id: data.province_id, customerName: data.customerName,
branch_id: data.branch_id, customerSurname: data.customerSurname,
first_name: data.first_name, customerPatronicName: data.customerPatronicName || "",
last_name: data.last_name, bornAt: data.bornAt,
middle_name: data.middle_name || undefined,
birth_date: data.birth_date,
phone: data.phone, phone: data.phone,
passport_series: data.passport_series, passportSerie: data.passportSerie,
passport_number: data.passport_number, passportId: data.passportId,
...(data.passport_page1 && { passport_page1: data.passport_page1 }), passportOne: data.passportOne || "",
...(data.passport_page2_3 && { passport_page2_3: data.passport_page2_3 }), passportTwo: data.passportTwo || "",
...(data.passport_page8_9 && { passport_page8_9: data.passport_page8_9 }), passportThree: data.passportThree || "",
...(data.passport_page32 && { passport_page32: data.passport_page32 }), 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 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 { export type LoanOrderMobileStatus = LoanOrderStatus;
id: string; export type LoanOrderMobile = LoanOrder;
loanType: string; export type LoanOrderMobileUser = LoanOrderUser;
createdAt: string; export type LoanOrderMobilePayload = LoanOrderPayload;
region: string; export type LoanOrderMobileListParams = LoanOrdersParams;
branch: string; export type LoanOrderMobilesResponse = LoanOrdersResponse;
branchId?: number | string; export type PaginatedResponse<T> = {
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> {
data: T[]; data: T[];
total: number; 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[] = [ 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;
id: "LOM-0001", const branchId = branch || branch_id;
loanType: "Sarp ediş karzy", const uid = createdById || userId || user_id;
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",
},
];
let mockStore = [...MOCK_DATA]; const { data } = await apiClient.get<LoanOrdersListResponse>("/loan-orders/mobile", {
let nextId = 8; params: {
page: page ?? 1,
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms)); limit: perPage ?? limit ?? 25,
search: search || undefined,
function applyMockFilters(params: LoanOrderMobileListParams): PaginatedResponse<LoanOrderMobile> { region: region || undefined,
const page = params.page ?? 1; status: status || undefined,
const perPage = params.perPage ?? 25; branch_id: branchId || undefined,
user_id: uid || undefined,
let result = [...mockStore]; archived: archived || undefined,
},
if (params.search) { signal,
const q = params.search.toLowerCase(); });
result = result.filter( const orders = (data.loanOrders ?? []).map(mapBackendToUI);
(r) => return {
r.firstName.toLowerCase().includes(q) || data: orders,
r.lastName.toLowerCase().includes(q) || total: data.count ?? orders.length,
r.phone.includes(q) || page: page ?? 1,
r.id.toLowerCase().includes(q), perPage: perPage ?? limit ?? 25,
);
}
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,
}; };
mockStore = [newOrder, ...mockStore];
return newOrder;
} }
export async function updateLoanOrderMobile(id: string, payload: Partial<LoanOrderMobilePayload>): Promise<LoanOrderMobile> { // ─── Branch options by region (Fallback) ──────────────────────────────────────
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 ─────────────────────────────────────────────────
export const BRANCHES_BY_REGION_MOBILE: Record<string, { value: string; label: string }[]> = { export const BRANCHES_BY_REGION_MOBILE: Record<string, { value: string; label: string }[]> = {
Aşgabat: [ 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: "Garaşsyzlyk şahamçasy", label: "Garaşsyzlyk şahamçasy" },
{ value: "Bitarap şahamça", label: "Bitarap şahamça" }, { value: "Bitarap şahamça", label: "Bitarap şahamça" },
{ value: "Aşgabat-1 şahamçasy", label: "Aşgabat-1 şahamçasy" }, { 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 { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from 'sonner' import { toast } from "sonner";
import { useTranslation } from 'react-i18next' import { useTranslation } from "react-i18next";
import { import {
fetchLoanOrderMobiles, fetchLoanOrderMobiles,
@@ -8,40 +8,42 @@ import {
getLoanOrderMobileById, getLoanOrderMobileById,
createLoanOrderMobile, createLoanOrderMobile,
updateLoanOrderMobile, updateLoanOrderMobile,
patchLoanOrderMobile,
type LoanOrderMobileListParams, type LoanOrderMobileListParams,
type LoanOrderMobilePayload, type LoanOrderMobilePayload,
} from '../api/loanOrderMobilesApi' } from "../api/loanOrderMobilesApi";
// ─── Query keys ──────────────────────────────────────────────────────────────── // ─── Query keys ────────────────────────────────────────────────────────────────
export const loanOrderMobileKeys = { export const loanOrderMobileKeys = {
all: ['loanOrderMobiles'] as const, all: ["loanOrderMobiles"] as const,
lists: () => [...loanOrderMobileKeys.all, 'list'] as const, lists: () => [...loanOrderMobileKeys.all, "list"] as const,
list: (params: LoanOrderMobileListParams) => [...loanOrderMobileKeys.lists(), params] 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, detail: (id: string) => [...loanOrderMobileKeys.details(), id] as const,
} };
// ─── Hooks ───────────────────────────────────────────────────────────────────── // ─── Hooks ─────────────────────────────────────────────────────────────────────
export function useLoanOrderMobiles(params: LoanOrderMobileListParams) { export function useLoanOrderMobiles(params: LoanOrderMobileListParams) {
return useQuery({ return useQuery({
queryKey: loanOrderMobileKeys.list(params), queryKey: loanOrderMobileKeys.list(params),
queryFn: () => fetchLoanOrderMobiles(params), queryFn: ({ signal }) => fetchLoanOrderMobiles(params, signal),
}) placeholderData: (prev) => prev,
});
} }
export function useDeleteLoanOrderMobile() { export function useDeleteLoanOrderMobile() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
const { t } = useTranslation() const { t } = useTranslation();
return useMutation({ return useMutation({
mutationFn: (id: string) => deleteLoanOrderMobile(id), mutationFn: (id: string) => deleteLoanOrderMobile(id),
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() }) queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() });
toast.success(t('loanOrderMobiles.deleteSuccess', 'Sargyt üstünlikli pozuldy')) toast.success(t("loanOrderMobiles.deleteSuccess", "Sargyt üstünlikli pozuldy"));
}, },
}) });
} }
export function useLoanOrderMobileById(id: string) { export function useLoanOrderMobileById(id: string) {
@@ -49,33 +51,47 @@ export function useLoanOrderMobileById(id: string) {
queryKey: loanOrderMobileKeys.detail(id), queryKey: loanOrderMobileKeys.detail(id),
queryFn: () => getLoanOrderMobileById(id), queryFn: () => getLoanOrderMobileById(id),
enabled: !!id, enabled: !!id,
}) });
} }
export function useCreateLoanOrderMobile() { export function useCreateLoanOrderMobile() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
const { t } = useTranslation() const { t } = useTranslation();
return useMutation({ return useMutation({
mutationFn: (payload: LoanOrderMobilePayload) => createLoanOrderMobile(payload), mutationFn: (payload: LoanOrderMobilePayload) => createLoanOrderMobile(payload),
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() }) queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() });
toast.success(t('loanOrderMobiles.createSuccess', 'Sargyt üstünlikli döredildi')) toast.success(t("loanOrderMobiles.createSuccess", "Sargyt üstünlikli döredildi"));
}, },
}) });
} }
export function useUpdateLoanOrderMobile() { export function useUpdateLoanOrderMobile() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
const { t } = useTranslation() const { t } = useTranslation();
return useMutation({ return useMutation({
mutationFn: ({ id, payload }: { id: string; payload: Partial<LoanOrderMobilePayload> }) => mutationFn: ({ id, payload }: { id: string; payload: Partial<LoanOrderMobilePayload> }) => updateLoanOrderMobile(id, payload),
updateLoanOrderMobile(id, payload),
onSuccess: (_, variables) => { onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() }) queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() });
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.detail(variables.id) }) queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.detail(variables.id) });
toast.success(t('loanOrderMobiles.updateSuccess', 'Sargyt üstünlikli üýtgedildi')) 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"; export * from "@/features/loanOrders/schemas/loanOrder.schema";
import i18next from "i18next"; export type { LoanOrderFormData as LoanOrderMobileFormData } from "@/features/loanOrders/schemas/loanOrder.schema";
export { loanOrderFormSchema as loanOrderMobileFormSchema } from "@/features/loanOrders/schemas/loanOrder.schema";
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,
};
}
+100 -48
View File
@@ -8,52 +8,81 @@ import type { LocalizedText } from "@/features/branches/api/branchesApi";
export type LoanOrderStatus = StatusValue; export type LoanOrderStatus = StatusValue;
export interface LoanOrderUser {
id?: number;
name?: string;
username?: string;
phone?: string;
email?: string;
}
export interface LoanOrder { export interface LoanOrder {
id: string; id: string;
uniqueId?: string | null;
source?: string | null;
user?: LoanOrderUser | null;
loanType: string; loanType: string;
createdAt: string; createdAt: string;
updatedAt?: string | null;
region: string; region: string;
branch: string; branch: string;
branchId?: number | string; branchId?: number | string;
loanTypeId?: number | string; loanTypeId?: number | string;
workCityId?: number | string; workCityId?: number | string;
workProvinceId?: number | string;
createdById?: number | string; createdById?: number | string;
createdBy?: string | null;
firstName: string; firstName: string;
lastName: string; lastName: string;
patronicName?: string | null;
fullName?: string | null;
phone: string; phone: string;
homePhone?: string | null;
phoneAdditional?: string | null;
status: LoanOrderStatus; status: LoanOrderStatus;
note?: string | null; note?: string | null;
notes?: string | null;
loanAmount?: number | null; loanAmount?: number | null;
loanHistory?: string | null; loanHistory?: string | null;
patronicName?: string | null; loanOrderRequiredDoc?: { id: number; name: string } | null;
satisfiable?: string | null;
education?: string | null; education?: string | null;
marriageStatus?: string | null; marriageStatus?: string | null;
maritalStatus?: string | null;
dateOfBirth?: string | null; dateOfBirth?: string | null;
birthDate?: string | null;
residence?: string | null; residence?: string | null;
registeredAddress?: string | null;
currentResidence?: string | null; currentResidence?: string | null;
currentAddress?: string | null;
passportSerie?: string | null; passportSerie?: string | null;
passportNumber?: string | null; passportNumber?: string | null;
passportDateOfIssue?: string | null; passportDateOfIssue?: string | null;
passportGivenBy?: string | null; passportGivenBy?: string | null;
passportIssuedBy?: string | null;
bornPlace?: string | null; bornPlace?: string | null;
passportBirthPlace?: string | null;
passportPage1Url?: string | null; passportPage1Url?: string | null;
passportPage23Url?: string | null; passportPage23Url?: string | null;
passportPage89Url?: string | null; passportPage89Url?: string | null;
passportPage32Url?: string | null; passportPage32Url?: string | null;
email?: string | null; email?: string | null;
phoneAdditional?: string | null;
homePhone?: string | null;
workCompany?: string | null; workCompany?: string | null;
employer?: string | null;
workHrPhone?: string | null; workHrPhone?: string | null;
deptPhone?: string | null;
workRegion?: string | null; workRegion?: string | null;
workProvince?: string | null; workProvince?: string | null;
workCity?: string | null;
position?: string | null; position?: string | null;
salary?: number | null; salary?: number | null;
workStartedAt?: string | null; workStartedAt?: string | null;
employedSince?: string | null;
cardNumber?: string | null; cardNumber?: string | null;
cardName?: string | null; cardName?: string | null;
@@ -70,6 +99,7 @@ export interface LoanOrder {
guarantor1CardExpMonth?: string | null; guarantor1CardExpMonth?: string | null;
guarantor1CardExpYear?: string | null; guarantor1CardExpYear?: string | null;
guarantor1Salary?: number | null; guarantor1Salary?: number | null;
guarantor1Note?: string | null;
guarantor2Name?: string | null; guarantor2Name?: string | null;
guarantor2Surname?: string | null; guarantor2Surname?: string | null;
@@ -82,20 +112,13 @@ export interface LoanOrder {
guarantor2CardExpYear?: string | null; guarantor2CardExpYear?: string | null;
guarantor2Note?: string | null; guarantor2Note?: string | null;
loanCardNumber?: string | null;
loanCardName?: string | null;
loanCardMonth?: string | null;
loanCardYear?: string | null;
amount?: number | 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; phoneAlt?: string | null;
employer?: string | null;
deptPhone?: string | null;
workCity?: string | null;
employedSince?: string | null;
passportIssuedBy?: string | null;
passportBirthPlace?: string | null;
} }
export interface LoanOrdersParams { export interface LoanOrdersParams {
@@ -103,9 +126,14 @@ export interface LoanOrdersParams {
region?: string; region?: string;
status?: LoanOrderStatus | ""; status?: LoanOrderStatus | "";
branch?: string; branch?: string;
branch_id?: string | number;
createdById?: string | number;
userId?: string | number;
user_id?: string | number;
archived?: string; archived?: string;
page?: number; page?: number;
perPage?: number; perPage?: number;
limit?: number;
} }
export interface LoanOrdersResponse { export interface LoanOrdersResponse {
@@ -120,7 +148,7 @@ export interface LoanOrderPayload {
loanType: string; loanType: string;
region: string; region: string;
branch: string; branch: string;
userId: string; userId?: string | number;
firstName: string; firstName: string;
lastName: string; lastName: string;
patronicName?: string; patronicName?: string;
@@ -181,13 +209,14 @@ export interface LoanOrderPayload {
passportTwo?: string; passportTwo?: string;
passportThree?: string; passportThree?: string;
passportFour?: string; passportFour?: string;
source?: string;
} }
// ─── Backend types ───────────────────────────────────────────────────────────── // ─── 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; id?: number | string;
uniqueId?: string | null; uniqueId?: string | null;
region?: string | null; region?: string | null;
@@ -196,6 +225,7 @@ interface BackendLoanOrder {
branchName?: LocalizedText | string | null; branchName?: LocalizedText | string | null;
loanType?: NestedLocalized | number | string | null; loanType?: NestedLocalized | number | string | null;
loanTypeName?: LocalizedText | string | null; loanTypeName?: LocalizedText | string | null;
user?: LoanOrderUser | null;
userId?: number | null; userId?: number | null;
userName?: string | null; userName?: string | null;
customerName?: string | null; customerName?: string | null;
@@ -236,6 +266,7 @@ interface BackendLoanOrder {
workCompanyAccountantNumber?: string | null; workCompanyAccountantNumber?: string | null;
workRegion?: string | null; workRegion?: string | null;
workProvinceId?: number | null; workProvinceId?: number | null;
workProvince?: NestedLocalized | number | string | null;
workProvinceName?: LocalizedText | string | null; workProvinceName?: LocalizedText | string | null;
workSalary?: string | number | null; workSalary?: string | number | null;
workPosition?: string | null; workPosition?: string | null;
@@ -243,6 +274,7 @@ interface BackendLoanOrder {
satisfiable?: string | null; satisfiable?: string | null;
source?: string | null; source?: string | null;
loanOrderRequiredDocId?: number | null; loanOrderRequiredDocId?: number | null;
loanOrderRequiredDoc?: { id: number; name: string } | null;
guarantorName?: string | null; guarantorName?: string | null;
guarantorSurname?: string | null; guarantorSurname?: string | null;
guarantorPatronicName?: string | null; guarantorPatronicName?: string | null;
@@ -265,14 +297,14 @@ interface BackendLoanOrder {
guarantor2Note?: string | null; guarantor2Note?: string | null;
} }
interface LoanOrdersListResponse { export interface LoanOrdersListResponse {
count: number; count: number;
loanOrders: BackendLoanOrder[]; loanOrders: BackendLoanOrder[];
} }
// ─── Mapping helpers ─────────────────────────────────────────────────────────── // ─── Mapping helpers ───────────────────────────────────────────────────────────
function resolveLocalizedName(name: LocalizedText | string | null | undefined): string { export function resolveLocalizedName(name: LocalizedText | string | null | undefined): string {
if (!name) return ""; if (!name) return "";
if (typeof name === "string") return name; if (typeof name === "string") return name;
const lang = i18next.language || "en"; 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. */ /** 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 (value === null || value === undefined || value === "") return "";
if (typeof value === "string") return value; if (typeof value === "string") return value;
if (typeof value === "number") return ""; 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. */ /** 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 (value === null || value === undefined || value === "") return null;
if (typeof value === "number") return value; if (typeof value === "number") return value;
if (typeof value === "string") { if (typeof value === "string") {
@@ -301,58 +333,78 @@ function resolveNestedId(value: NestedLocalized | number | string | null | undef
return null; 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; if (value === null || value === undefined || value === "") return null;
const n = Number(value); const n = Number(value);
return Number.isNaN(n) ? null : n; return Number.isNaN(n) ? null : n;
} }
function mapBackendToUI(order: BackendLoanOrder): LoanOrder { export function mapBackendToUI(order: BackendLoanOrder): LoanOrder {
const rawStatus = order.status ?? ""; const rawStatus = order.status ?? "";
const status: LoanOrderStatus = isStatusValue(rawStatus) ? rawStatus : "pending"; const status: LoanOrderStatus = isStatusValue(rawStatus) ? rawStatus : "pending";
return { return {
id: String(order.id ?? order.uniqueId ?? ""), 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), loanType: resolveNestedName(order.loanType) || resolveLocalizedName(order.loanTypeName),
createdAt: order.createdAt ?? "", createdAt: order.createdAt ?? "",
updatedAt: order.updatedAt ?? "",
region: order.region ?? "", region: order.region ?? "",
branch: resolveNestedName(order.branch) || resolveLocalizedName(order.branchName), branch: resolveNestedName(order.branch) || resolveLocalizedName(order.branchName),
branchId: resolveNestedId(order.branch) ?? order.branchId ?? undefined, branchId: resolveNestedId(order.branch) ?? order.branchId ?? undefined,
loanTypeId: resolveNestedId(order.loanType) ?? undefined, loanTypeId: resolveNestedId(order.loanType) ?? undefined,
workCityId: order.workProvinceId ?? undefined, workCityId: resolveNestedId(order.workProvince) ?? order.workProvinceId ?? undefined,
createdById: order.userId ?? undefined, workProvinceId: resolveNestedId(order.workProvince) ?? order.workProvinceId ?? undefined,
createdById: order.user?.id ?? order.userId ?? undefined,
createdBy: order.user?.name ?? order.userName ?? "",
firstName: order.customerName ?? "", firstName: order.customerName ?? "",
lastName: order.customerSurname ?? "", lastName: order.customerSurname ?? "",
patronicName: order.customerPatronicName ?? "", patronicName: order.customerPatronicName ?? "",
fullName: [order.customerName, order.customerSurname].filter(Boolean).join(" "),
phone: formatFromApiPhone(order.phone ?? order.phoneHome ?? ""), phone: formatFromApiPhone(order.phone ?? order.phoneHome ?? ""),
homePhone: formatFromApiPhone(order.phoneHome), homePhone: formatFromApiPhone(order.phoneHome),
phoneAdditional: formatFromApiPhone(order.phoneAdditional), phoneAdditional: formatFromApiPhone(order.phoneAdditional),
status, status,
note: order.notes ?? "", note: order.notes ?? "",
notes: order.notes ?? "",
loanAmount: toNum(order.loanAmount), loanAmount: toNum(order.loanAmount),
loanHistory: order.loanOrderRequiredDoc?.name || (order.loanOrderRequiredDocId ? String(order.loanOrderRequiredDocId) : ""),
loanOrderRequiredDoc: order.loanOrderRequiredDoc ?? undefined,
satisfiable: order.satisfiable ?? "",
dateOfBirth: formatFromApiDate(order.bornAt), dateOfBirth: formatFromApiDate(order.bornAt),
birthDate: formatFromApiDate(order.bornAt),
bornPlace: order.bornPlace ?? "", bornPlace: order.bornPlace ?? "",
passportBirthPlace: order.bornPlace ?? "",
education: order.education ?? "", education: order.education ?? "",
marriageStatus: order.marriageStatus ?? "", marriageStatus: order.marriageStatus ?? "",
maritalStatus: order.marriageStatus ?? "",
residence: order.passportAddress ?? "", residence: order.passportAddress ?? "",
registeredAddress: order.passportAddress ?? "",
currentResidence: order.realAddress ?? "", currentResidence: order.realAddress ?? "",
currentAddress: order.realAddress ?? "",
email: order.email ?? "", email: order.email ?? "",
passportSerie: order.passportSerie ?? "", passportSerie: order.passportSerie ?? "",
passportNumber: order.passportId ?? "", passportNumber: order.passportId ?? "",
passportDateOfIssue: formatFromApiDate(order.passportGivenAt), passportDateOfIssue: formatFromApiDate(order.passportGivenAt),
passportGivenBy: order.passportGivenBy ?? "", passportGivenBy: order.passportGivenBy ?? "",
passportIssuedBy: order.passportGivenBy ?? "",
passportPage1Url: order.passportOne ?? "", passportPage1Url: order.passportOne ?? "",
passportPage23Url: order.passportTwo ?? "", passportPage23Url: order.passportTwo ?? "",
passportPage89Url: order.passportThree ?? "", passportPage89Url: order.passportThree ?? "",
passportPage32Url: order.passportFour ?? "", passportPage32Url: order.passportFour ?? "",
workCompany: order.workCompany ?? "", workCompany: order.workCompany ?? "",
employer: order.workCompany ?? "",
workHrPhone: formatFromApiPhone(order.workCompanyAccountantNumber), workHrPhone: formatFromApiPhone(order.workCompanyAccountantNumber),
deptPhone: formatFromApiPhone(order.workCompanyAccountantNumber),
workRegion: order.workRegion ?? "", workRegion: order.workRegion ?? "",
workProvince: resolveLocalizedName(order.workProvinceName), workProvince: resolveNestedName(order.workProvince) || resolveLocalizedName(order.workProvinceName),
workCity: resolveLocalizedName(order.workProvinceName), workCity: resolveNestedName(order.workProvince) || resolveLocalizedName(order.workProvinceName),
salary: toNum(order.workSalary), salary: toNum(order.workSalary),
position: order.workPosition ?? "", position: order.workPosition ?? "",
workStartedAt: formatFromApiDate(order.workStartedAt), workStartedAt: formatFromApiDate(order.workStartedAt),
employedSince: formatFromApiDate(order.workStartedAt),
cardNumber: order.cardNumber ?? order.loanCardNumber ?? "", cardNumber: order.cardNumber ?? order.loanCardNumber ?? "",
cardName: order.cardName ?? order.loanCardName ?? "", cardName: order.cardName ?? order.loanCardName ?? "",
cardExpMonth: order.cardMonth ?? order.loanCardMonth ?? "", cardExpMonth: order.cardMonth ?? order.loanCardMonth ?? "",
@@ -367,6 +419,7 @@ function mapBackendToUI(order: BackendLoanOrder): LoanOrder {
guarantor1CardExpMonth: order.guarantorCardMonth ?? "", guarantor1CardExpMonth: order.guarantorCardMonth ?? "",
guarantor1CardExpYear: order.guarantorCardYear ?? "", guarantor1CardExpYear: order.guarantorCardYear ?? "",
guarantor1Salary: null, guarantor1Salary: null,
guarantor1Note: order.guarantorNote ?? "",
guarantor2Name: order.guarantor2Name ?? "", guarantor2Name: order.guarantor2Name ?? "",
guarantor2Surname: order.guarantor2Surname ?? "", guarantor2Surname: order.guarantor2Surname ?? "",
guarantor2Patronic: order.guarantor2PatronicName ?? "", guarantor2Patronic: order.guarantor2PatronicName ?? "",
@@ -377,23 +430,14 @@ function mapBackendToUI(order: BackendLoanOrder): LoanOrder {
guarantor2CardExpMonth: order.guarantor2CardMonth ?? "", guarantor2CardExpMonth: order.guarantor2CardMonth ?? "",
guarantor2CardExpYear: order.guarantor2CardYear ?? "", guarantor2CardExpYear: order.guarantor2CardYear ?? "",
guarantor2Note: order.guarantor2Note ?? "", guarantor2Note: order.guarantor2Note ?? "",
loanHistory: order.loanOrderRequiredDocId ? String(order.loanOrderRequiredDocId) : "", loanCardNumber: order.loanCardNumber ?? "",
createdBy: order.userName ?? "", loanCardName: order.loanCardName ?? "",
fullName: [order.customerName, order.customerSurname].filter(Boolean).join(" "), loanCardMonth: order.loanCardMonth ?? "",
registeredAddress: order.passportAddress ?? "", loanCardYear: order.loanCardYear ?? "",
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 ?? "",
}; };
} }
function mapPayloadToBackend(payload: LoanOrderPayload | Partial<LoanOrderPayload>): Record<string, unknown> { export function mapPayloadToBackend(payload: LoanOrderPayload | Partial<LoanOrderPayload>): Record<string, unknown> {
return { return {
customerName: payload.firstName ?? "", customerName: payload.firstName ?? "",
customerSurname: payload.lastName ?? "", customerSurname: payload.lastName ?? "",
@@ -458,25 +502,28 @@ function mapPayloadToBackend(payload: LoanOrderPayload | Partial<LoanOrderPayloa
passportFour: payload.passportFour || "", passportFour: payload.passportFour || "",
status: payload.status ?? "pending", status: payload.status ?? "pending",
satisfiable: "yes", satisfiable: "yes",
source: "web", source: payload.source ?? "web",
loanOrderRequiredDocId: payload.loanHistory ? Number(payload.loanHistory) : 0, loanOrderRequiredDocId: payload.loanHistory ? Number(payload.loanHistory) : 0,
userId: toNum(payload.userId) ?? 0, userId: toNum(payload.userId) ?? 0,
uniqueId: "541-shbfnkj",
}; };
} }
// ─── API Functions ───────────────────────────────────────────────────────────── // ─── API Functions ─────────────────────────────────────────────────────────────
export async function fetchLoanOrders(params: LoanOrdersParams = {}, signal?: AbortSignal): Promise<LoanOrdersResponse> { 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", { const { data } = await apiClient.get<LoanOrdersListResponse>("/loan-orders", {
params: { params: {
page: page ?? 1, page: page ?? 1,
limit: perPage ?? 25, limit: perPage ?? limit ?? 25,
search: search || undefined, search: search || undefined,
region: region || undefined, region: region || undefined,
status: status || undefined, status: status || undefined,
branch_id: branch || undefined, branch_id: branchId || undefined,
user_id: uid || undefined,
archived: archived || undefined, archived: archived || undefined,
}, },
signal, signal,
@@ -486,7 +533,7 @@ export async function fetchLoanOrders(params: LoanOrdersParams = {}, signal?: Ab
data: orders, data: orders,
total: data.count ?? orders.length, total: data.count ?? orders.length,
page: page ?? 1, 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); 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> { export async function deleteLoanOrder(id: string): Promise<void> {
await apiClient.delete(`/loan-orders/${id}`); await apiClient.delete(`/loan-orders/${id}`);
} }
+10 -6
View File
@@ -13,11 +13,13 @@ export interface AddRoleUserPayload {
userId: number; userId: number;
} }
export interface AddPermissionUserPayload { export interface AddPermissionRolePayload {
permissionId: number; permissionId: number;
userId: number; roleId: number;
} }
export type AddPermissionUserPayload = AddPermissionRolePayload;
// Re-export so shared hooks can import from one place // Re-export so shared hooks can import from one place
export type { BranchListParams, BranchListResponse }; export type { BranchListParams, BranchListResponse };
@@ -67,13 +69,15 @@ export async function postRoleUser(payload: AddRoleUserPayload): Promise<void> {
} }
/** /**
* POST /permission-users * POST /permission-roles
* Assigns a permission to a user. * Assigns a permission to a role.
*/ */
export async function postPermissionUser(payload: AddPermissionUserPayload): Promise<void> { export async function postPermissionRole(payload: AddPermissionRolePayload): Promise<void> {
await apiClient.post("/permission-users", payload); await apiClient.post("/permission-roles", payload);
} }
export const postPermissionUser = postPermissionRole;
/** /**
* Proxy for branch list fetching — kept here so shared hooks * Proxy for branch list fetching — kept here so shared hooks
* don't import directly from the branches feature. * don't import directly from the branches feature.
@@ -4,10 +4,10 @@ import { useTranslation } from "react-i18next";
import { import {
postBranchUser, postBranchUser,
postRoleUser, postRoleUser,
postPermissionUser, postPermissionRole,
type AddBranchUserPayload, type AddBranchUserPayload,
type AddRoleUserPayload, type AddRoleUserPayload,
type AddPermissionUserPayload, type AddPermissionRolePayload,
} from "../api/sharedApi"; } from "../api/sharedApi";
// ─── Query Keys ─────────────────────────────────────────────────────────────── // ─── 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. * POST /permission-roles — assigns a permission to the given role and refreshes the profile cache.
* `userId` is supplied at mutate time (picked from the staff select).
*/ */
export function useAssignPermissionToUser() { export function useAssignPermissionToRole() {
const { t } = useTranslation(); const { t } = useTranslation();
const invalidateProfile = useInvalidateProfile(); const invalidateProfile = useInvalidateProfile();
return useMutation({ return useMutation({
mutationFn: (payload: AddPermissionUserPayload) => postPermissionUser(payload), mutationFn: (payload: AddPermissionRolePayload) => postPermissionRole(payload),
onSuccess: () => { onSuccess: () => {
invalidateProfile(); invalidateProfile();
toast.success(t("profile.assign.success", "Üstünlikli birikdirildi")); toast.success(t("profile.assign.success", "Üstünlikli birikdirildi"));
@@ -62,6 +61,8 @@ export function useAssignPermissionToUser() {
}); });
} }
export const useAssignPermissionToUser = useAssignPermissionToRole;
// ─── useAssignBranchToUser ──────────────────────────────────────────────────── // ─── useAssignBranchToUser ────────────────────────────────────────────────────
/** /**
+217 -92
View File
@@ -1,114 +1,232 @@
import { useState } from "react"; import { useState, useMemo, useCallback } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Download } from "lucide-react"; import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
import { DeleteDialog } from "@/components/deleteDialog";
import { DataTable, type ColumnDef } from "@/components/dataTable"; import { DataTable } from "@/components/dataTable";
import { DataTableToolbar, type ColumnMeta } from "@/components/dataTableToolbar"; import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
import { TableSearchInput } from "@/components/tableSearch"; import { TableSearchInput } from "@/components/tableSearch";
import { CreateButton } from "@/components/createButton"; import { CreateButton } from "@/components/createButton";
import { TableActions } from "@/components/tableActions"; import { TableActions } from "@/components/tableActions";
import type { VisibilityState } from "@tanstack/react-table"; import { DeleteDialog } from "@/components/deleteDialog";
import { useCardBalances, useDeleteCardBalance, useDownloadCardBalance } from "@/features/cardBalance/hooks/useCardBalance"; import { useCardBalances, useDeleteCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
import { type CardBalance } from "@/features/cardBalance/api/cardBalanceApi"; 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() { export default function CardBalancesPage() {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
const deleteMutation = useDeleteCardBalance();
const [deleteId, setDeleteId] = useState<number | null>(null);
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(PER_PAGE); const [perPage, setPerPage] = useState(25);
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [deleteId, setDeleteId] = useState<number | null>(null);
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({}); 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 [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
const deleteMutation = useDeleteCardBalance(); { fieldId: "status", value: "" },
const downloadMutation = useDownloadCardBalance(); { fieldId: "created_by", value: "" },
]);
// ── Columns ─────────────────────────────────────────────────────────────── // ── Infinite user dropdown for created_by filter ────────────────────────────
const columns: ColumnDef<CardBalance>[] = [ const [userSearch, setUserSearch] = useState("");
{ const {
id: "id", data: usersInfiniteData,
accessorKey: "id", fetchNextPage: fetchNextUsers,
header: t("ID", "ID"), hasNextPage: hasNextUsers,
cell: ({ row }) => ( isFetchingNextPage: isFetchingNextUsers,
<button className="text-primary font-medium hover:underline" onClick={() => navigate(`/card-balances/${row.original.id}`)}> isLoading: isUsersLoading,
{row.original.id} } = useInfiniteUsers(userSearch);
</button>
const userOptions = useMemo(
() =>
(usersInfiniteData?.pages ?? []).flatMap((page) =>
(page?.users ?? []).map((u) => ({
value: String(u.id),
label: u.name || u.username || String(u.id),
})),
), ),
}, [usersInfiniteData],
{ );
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}
/>
),
},
];
const columnMeta: ColumnMeta[] = columns // ── Query params & data ─────────────────────────────────────────────────────
.filter((c) => c.id !== "actions")
.map((c) => ({
id: c.id!,
label: typeof c.header === "string" ? c.header : c.id!,
}));
const total = data?.total ?? 0; const queryParams = useMemo(() => {
const totalPages = Math.ceil(total / perPage); 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; if (deleteId === null) return;
await deleteMutation.mutateAsync(deleteId); deleteMutation.mutate(deleteId);
setDeleteId(null); 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 ( return (
<div className="space-y-4"> <div className="space-y-4">
{/* Header */}
<div className="flex items-center justify-between"> <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>
<div className="flex items-center gap-3 justify-between"> <div className="flex items-center gap-3 justify-between">
<TableSearchInput <TableSearchInput
value={search} value={search}
@@ -116,25 +234,30 @@ export default function CardBalancesPage() {
setSearch(v); setSearch(v);
setPage(1); 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")} /> <CreateButton label={t("Create card balance", "Kart galyndysy dörediň")} onClick={() => navigate("/card-balances/create")} />
</div> </div>
<div className="bg-card border border-border rounded-xl p-4"> <div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar <DataTableToolbar
hideSearch
hideAction
searchValue={search} searchValue={search}
onSearchChange={(v) => { onSearchChange={(v) => {
setSearch(v); setSearch(v);
setPage(1); setPage(1);
}} }}
searchPlaceholder={t("common.search", "Gözlemek")} searchPlaceholder={t("cardBalance.searchPlaceholder", "Pasport belgisi boýunça gözle")}
columns={columnMeta} columns={toggleableColumns}
columnVisibility={columnVisibility} columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility} onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder} columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder} onColumnOrderChange={setColumnOrder}
hideSearch filterFields={filterFields}
hideAction activeFilters={activeFilters}
onFilterChange={handleFilterChange}
onFilterReset={handleFilterReset}
perPageOptions={[10, 25, 50, 100]} perPageOptions={[10, 25, 50, 100]}
perPage={perPage} perPage={perPage}
onPerPageChange={(v) => { onPerPageChange={(v) => {
@@ -143,9 +266,10 @@ export default function CardBalancesPage() {
}} }}
/> />
{/* Table */}
<DataTable <DataTable
columns={columns} columns={columns}
data={data?.data ?? []} data={data?.cardBalances ?? []}
isLoading={isLoading} isLoading={isLoading}
columnVisibility={columnVisibility} columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility} onColumnVisibilityChange={setColumnVisibility}
@@ -160,14 +284,15 @@ export default function CardBalancesPage() {
/> />
</div> </div>
{/* Delete dialog */}
<DeleteDialog <DeleteDialog
open={deleteId !== null} open={deleteId !== null}
onOpenChange={(o) => { onOpenChange={(o) => {
if (!o) setDeleteId(null); if (!o) setDeleteId(null);
}} }}
title={t("Are you sure?", "Eminsiňizmi?")} title={t("cardBalance.deleteConfirm", "Bu ýazgy pozulsynmy?")}
description={t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")} description={t("cardBalance.deleteDescription", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")}
onConfirm={handleDelete} onConfirm={confirmDelete}
isLoading={deleteMutation.isPending} isLoading={deleteMutation.isPending}
/> />
</div> </div>
@@ -1,7 +1,7 @@
import { useState } from "react"; import { useState } from "react";
import { useParams, useNavigate, Link } from "react-router-dom"; import { useParams, useNavigate, Link } from "react-router-dom";
import { useTranslation } from "react-i18next"; 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 { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
import { import {
@@ -14,25 +14,9 @@ import {
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
} from "@/components/ui/alert-dialog"; } from "@/components/ui/alert-dialog";
import { import { useCardBalance, useDeleteCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
useCardBalance, import { InfoRow } from "@/components/viewPageComponents";
useDeleteCardBalance, import { CardBalanceStatusBadge } from "@/features/cardBalance/components/cardBalanceStatusBadge";
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;
}
// ─── Page ───────────────────────────────────────────────────────────────────── // ─── Page ─────────────────────────────────────────────────────────────────────
@@ -42,67 +26,10 @@ export default function CardBalanceViewPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const [deleteOpen, setDeleteOpen] = useState(false); const [deleteOpen, setDeleteOpen] = useState(false);
const [opsSearch, setOpsSearch] = useState("");
const numericId = Number(id); const numericId = Number(id);
const { data, isLoading } = useCardBalance(numericId); const { data, isLoading } = useCardBalance(numericId);
const deleteMutation = useDeleteCardBalance(); 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 () => { const handleDelete = async () => {
await deleteMutation.mutateAsync(numericId); await deleteMutation.mutateAsync(numericId);
@@ -114,7 +41,7 @@ export default function CardBalanceViewPage() {
<div className="space-y-4"> <div className="space-y-4">
<Skeleton className="h-7 w-64" /> <Skeleton className="h-7 w-64" />
<div className="rounded-lg border border-border bg-card overflow-hidden"> <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"> <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-24" />
<Skeleton className="h-4 w-40" /> <Skeleton className="h-4 w-40" />
@@ -126,11 +53,7 @@ export default function CardBalanceViewPage() {
} }
if (!data) { if (!data) {
return ( return <div className="text-center py-24 text-muted-foreground">{t("Not found", "Tapylmady")}</div>;
<div className="text-center py-24 text-muted-foreground">
{t("Not found", "Tapylmady")}
</div>
);
} }
return ( return (
@@ -138,17 +61,9 @@ export default function CardBalanceViewPage() {
{/* Header */} {/* Header */}
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground"> <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> </h1>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => downloadMutation.mutate(numericId)}
disabled={downloadMutation.isPending}
>
<Download size={14} />
</Button>
<Button <Button
variant="outline" variant="outline"
size="sm" size="sm"
@@ -168,80 +83,37 @@ export default function CardBalanceViewPage() {
{/* Detail card */} {/* Detail card */}
<div className="rounded-lg border border-border bg-card overflow-hidden"> <div className="rounded-lg border border-border bg-card overflow-hidden">
<InfoRow label={t("ID", "ID")} value={data.id} /> <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 <InfoRow
label={t("Passport series", "Pasport seriýasy")} label={t("Created by", "Döreden")}
value={data.passport_series} value={data.createdBy?.name || data.createdBy?.username || undefined}
/> isLink
<InfoRow href={data.createdBy?.id != null ? `/all-users/${data.createdBy.id}` : undefined}
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}
/> />
<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> </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 */} {/* Delete dialog */}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}> <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle> <AlertDialogTitle>{t("Are you sure?", "Eminsiňizmi?")}</AlertDialogTitle>
{t("Are you sure?", "Eminsiňizmi?")}
</AlertDialogTitle>
<AlertDialogDescription> <AlertDialogDescription>
{t( {t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")}
"This action cannot be undone.",
"Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.",
)}
</AlertDialogDescription> </AlertDialogDescription>
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel>{t("Cancel", "Ýatyr")}</AlertDialogCancel> <AlertDialogCancel>{t("Cancel", "Ýatyr")}</AlertDialogCancel>
<AlertDialogAction <AlertDialogAction onClick={handleDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
onClick={handleDelete} {deleteMutation.isPending ? t("Deleting...", "Öçürilýär...") : t("Delete", "Öçür")}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteMutation.isPending
? t("Deleting...", "Öçürilýär...")
: t("Delete", "Öçür")}
</AlertDialogAction> </AlertDialogAction>
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
+328 -124
View File
@@ -1,155 +1,353 @@
import { useState } from "react"; import { useState, useMemo, useCallback } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Download, AlertCircle, CheckCircle2, XCircle } from "lucide-react"; import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
import { DeleteDialog } from "@/components/deleteDialog"; import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
import { DataTable, type ColumnDef } from "@/components/dataTable";
import { DataTableToolbar, type ColumnMeta } from "@/components/dataTableToolbar"; import { DataTable } from "@/components/dataTable";
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
import { TableSearchInput } from "@/components/tableSearch"; import { TableSearchInput } from "@/components/tableSearch";
import { CreateButton } from "@/components/createButton"; import { CreateButton } from "@/components/createButton";
import { TableActions } from "@/components/tableActions"; 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 { 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 }> = { const STATUS_CONFIG: Record<
pending: { label: "Garaşylýar", variant: "warning", icon: AlertCircle }, CardRequisiteStatus,
approved: { label: "Tassyklanan", variant: "success", icon: CheckCircle2 }, { labelKey: string; fallback: string; variant: StatusBadgeVariant; icon: React.ElementType }
rejected: { label: "Ret edilen", variant: "error", icon: XCircle }, > = {
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 }) { function CardRequisiteStatusBadge({ status }: { status: string }) {
const cfg = STATUS_CONFIG[status]; const { t } = useTranslation();
const cfg = STATUS_CONFIG[status as CardRequisiteStatus];
if (!cfg) return <span className="text-xs text-muted-foreground">{status}</span>; 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() { 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 navigate = useNavigate();
const deleteMutation = useDeleteCardRequisite();
const [deleteId, setDeleteId] = useState<number | null>(null);
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(PER_PAGE); const [perPage, setPerPage] = useState(25);
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [deleteId, setDeleteId] = useState<string | null>(null);
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({}); const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
const [columnOrder, setColumnOrder] = useState<string[]>([]); const [columnOrder, setColumnOrder] = useState<string[]>([...COLUMN_IDS]);
const { data, isLoading } = useCardRequisites({ const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
page, { fieldId: "status", value: "" },
per_page: perPage, { fieldId: "region", value: "" },
search, { fieldId: "branch_id", value: "" },
}); { fieldId: "card_type_id", value: "" },
const deleteMutation = useDeleteCardRequisite(); { fieldId: "user_id", value: "" },
const downloadMutation = useDownloadCardRequisite(); ]);
// ── Columns ────────────────────────────────────────────────────────────────── // ── Infinite dropdown hooks ─────────────────────────────────────────────────
const columns: ColumnDef<CardRequisite>[] = [ const [branchSearch, setBranchSearch] = useState("");
{ const {
id: "id", data: branchesInfiniteData,
accessorKey: "id", fetchNextPage: fetchNextBranches,
header: t("ID", "ID"), hasNextPage: hasNextBranches,
cell: ({ row }) => ( isFetchingNextPage: isFetchingNextBranches,
<button isLoading: isBranchesLoading,
className="text-primary font-medium hover:underline text-left" } = useInfiniteBranches(branchSearch);
onClick={() => navigate(`/card-requisites/${row.original.id}`)}
> const branchOptions = useMemo(
{row.original.id} () =>
</button> (branchesInfiniteData?.pages ?? []).flatMap((page) =>
(page?.branches ?? []).map((b) => ({
value: String(b.id),
label: b.name[lang] || b.name.tm || String(b.id),
})),
), ),
}, [branchesInfiniteData, lang],
{ );
id: "card_type",
accessorKey: "card_type", const [cardTypeSearch, setCardTypeSearch] = useState("");
header: t("Card type", "GÖRNÜŞI"), const {
cell: ({ row }) => <span className="text-primary font-medium">{row.original.card_type}</span>, data: cardTypesInfiniteData,
}, fetchNextPage: fetchNextCardTypes,
{ hasNextPage: hasNextCardTypes,
id: "created_at", isFetchingNextPage: isFetchingNextCardTypes,
accessorKey: "created_at", isLoading: isCardTypesLoading,
header: t("Created at", "DÖREDILEN WAGTY"), } = useInfiniteCardTypes(cardTypeSearch);
cell: ({ row }) => <span className="text-foreground">{row.original.created_at}</span>,
}, const cardTypeOptions = useMemo(
{ () =>
id: "province_name", (cardTypesInfiniteData?.pages ?? []).flatMap((page) =>
accessorKey: "province_name", (page?.paymentCards ?? []).map((ct) => ({
header: t("Province", "WELAÝAT"), value: String(ct.id),
cell: ({ row }) => <span className="text-foreground">{row.original.province_name ?? "—"}</span>, label: ct.title[lang] || ct.title.tm || String(ct.id),
}, })),
{
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}
/>
), ),
}, [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 const clientOptions = useMemo(
.filter((c) => c.id !== "actions") () =>
.map((c) => ({ (clientsInfiniteData?.pages ?? []).flatMap((page) =>
id: c.id!, (page?.users ?? []).map((u) => ({
label: typeof c.header === "string" ? c.header : c.id!, value: String(u.id),
})); label: u.name || u.username || String(u.id),
})),
),
[clientsInfiniteData],
);
// ── Pagination ──────────────────────────────────────────────────────────────── // ── Query params & data ─────────────────────────────────────────────────────
const total = data?.total ?? 0; const queryParams = useMemo(() => {
const totalPages = Math.ceil(total / perPage); 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 () => { const { data, isLoading } = useCardRequisites(queryParams);
if (!deleteId) return; const total = data?.count ?? 0;
await deleteMutation.mutateAsync(deleteId); 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); 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 ( return (
<div className="space-y-4"> <div className="space-y-4">
{/* Header */} {/* Header */}
<div className="flex items-center justify-between"> <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>
<div className="flex items-center gap-3 justify-between"> <div className="flex items-center gap-3 justify-between">
<TableSearchInput <TableSearchInput
value={search} value={search}
@@ -157,28 +355,33 @@ export default function CardRequisitesPage() {
setSearch(v); setSearch(v);
setPage(1); setPage(1);
}} }}
placeholder={t("common.search", "Gözlemek")} placeholder={t("cardRequisites.searchPlaceholder", "Gözlemek")}
/> />
<CreateButton <CreateButton
label={t("cardRequisites.createTitle", "Kart rekwiziti üçin sargyt dörediň")} label={t("cardRequisites.createTitle", "Kart rekwiziti üçin sargyt dörediň")}
onClick={() => navigate("/card-requisites/create")} onClick={() => navigate("/card-requisites/create")}
/> />
</div> </div>
<div className="bg-card border border-border rounded-xl p-4"> <div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar <DataTableToolbar
hideSearch
hideAction
searchValue={search} searchValue={search}
onSearchChange={(v) => { onSearchChange={(v) => {
setSearch(v); setSearch(v);
setPage(1); setPage(1);
}} }}
searchPlaceholder={t("common.search", "Gözlemek")} searchPlaceholder={t("cardRequisites.searchPlaceholder", "Gözlemek")}
columns={columnMeta} columns={toggleableColumns}
columnVisibility={columnVisibility} columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility} onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder} columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder} onColumnOrderChange={setColumnOrder}
hideSearch filterFields={filterFields}
hideAction activeFilters={activeFilters}
onFilterChange={handleFilterChange}
onFilterReset={handleFilterReset}
perPageOptions={[10, 25, 50, 100]} perPageOptions={[10, 25, 50, 100]}
perPage={perPage} perPage={perPage}
onPerPageChange={(v) => { onPerPageChange={(v) => {
@@ -190,29 +393,30 @@ export default function CardRequisitesPage() {
{/* Table */} {/* Table */}
<DataTable <DataTable
columns={columns} columns={columns}
data={data?.data ?? []} data={data?.cardRekwizitOrders ?? []}
isLoading={isLoading} isLoading={isLoading}
columnVisibility={columnVisibility} columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility} onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder} columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder} onColumnOrderChange={setColumnOrder}
enableRowSelection enableRowSelection
getRowId={(row) => row.id} getRowId={(row) => String(row.id)}
currentPage={page} currentPage={page}
totalPages={totalPages} totalPages={totalPages}
totalCount={total} totalCount={total}
onPageChange={setPage} onPageChange={setPage}
/> />
</div> </div>
{/* Delete dialog */} {/* Delete dialog */}
<DeleteDialog <DeleteDialog
open={deleteId !== null} open={deleteId !== null}
onOpenChange={(o) => { onOpenChange={(o) => {
if (!o) setDeleteId(null); if (!o) setDeleteId(null);
}} }}
title={t("Are you sure?", "Eminsiňizmi?")} title={t("cardRequisites.deleteConfirm", "Bu sargyt pozulsynmy?")}
description={t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.")} description={t("cardRequisites.deleteDescription", "Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.")}
onConfirm={handleDelete} onConfirm={confirmDelete}
isLoading={deleteMutation.isPending} isLoading={deleteMutation.isPending}
/> />
</div> </div>
@@ -1,17 +1,18 @@
import { useParams } from 'react-router-dom' import { useParams } from "react-router-dom";
import { useTranslation } from 'react-i18next' import { useTranslation } from "react-i18next";
import { PageSpinner } from '@/components/pageSpinner' import { PageSpinner } from "@/components/pageSpinner";
import { PageError } from '@/components/pageError' import { PageError } from "@/components/pageError";
import { CardRequisiteForm } from '@/features/cardRequisites/components/cardRequisiteForm' import { CardRequisiteForm } from "@/features/cardRequisites/components/cardRequisiteForm";
import { useCardRequisite } from '@/features/cardRequisites/hooks/useCardRequisites' import { useCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites";
export default function CardRequisiteEditPage() { export default function CardRequisiteEditPage() {
const { id } = useParams<{ id: string }>() const { id } = useParams<{ id: string }>();
const { t } = useTranslation() const { t } = useTranslation();
const { data, isLoading } = useCardRequisite(id ?? '') const numericId = Number(id);
const { data, isLoading } = useCardRequisite(numericId);
if (isLoading) return <PageSpinner /> if (isLoading) return <PageSpinner />;
if (!data) return <PageError message={t('common.notFound', 'Tapylmady')} /> 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 { useParams, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useCardRequisite, useDeleteCardRequisite, useDownloadCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites"; import { ArrowLeft, Pencil, Trash2 } from "lucide-react";
import type { CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Pencil, Trash2, Download } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton";
import { import {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
@@ -15,6 +14,9 @@ import {
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
} from "@/components/ui/alert-dialog"; } 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 { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react"; import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
import { BentoGrid, BentoCard, InfoRow, PassportImage } from "@/components/viewPageComponents"; import { BentoGrid, BentoCard, InfoRow, PassportImage } from "@/components/viewPageComponents";
@@ -33,12 +35,13 @@ const STATUS_ICON: Record<CardRequisiteStatus, React.ElementType> = {
rejected: XCircle, rejected: XCircle,
}; };
function CardRequisiteStatusBadge({ status }: { status: CardRequisiteStatus }) { function CardRequisiteStatusBadge({ status }: { status: string }) {
const { t } = useTranslation(); const { t } = useTranslation();
const variant = STATUS_VARIANT[status]; const key = status as CardRequisiteStatus;
const Icon = STATUS_ICON[status]; const variant = STATUS_VARIANT[key];
const Icon = STATUS_ICON[key];
if (!variant) return <span className="text-xs text-muted-foreground">{status}</span>; 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 ───────────────────────────────────────────────────────────────── // ─── 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 ───────────────────────────────────────────────────────────────────── // ─── Page ─────────────────────────────────────────────────────────────────────
export default function CardRequisiteViewPage() { export default function CardRequisiteViewPage() {
@@ -68,9 +78,10 @@ export default function CardRequisiteViewPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const { t } = useTranslation(); const { t } = useTranslation();
const { data, isLoading, isError } = useCardRequisite(id ?? ""); const numericId = Number(id);
const { data, isLoading, isError } = useCardRequisite(numericId);
const deleteMutation = useDeleteCardRequisite(); const deleteMutation = useDeleteCardRequisite();
const downloadMutation = useDownloadCardRequisite(); const [deleteOpen, setDeleteOpen] = useState(false);
if (isLoading) { if (isLoading) {
return <CardRequisiteViewSkeleton />; 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>; 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 ( return (
<div className="mx-auto flex flex-col gap-6"> <div className="mx-auto flex flex-col gap-6">
{/* ── Page header ──────────────────────────────────────────────────── */} {/* ── Page header ──────────────────────────────────────────────────── */}
<div className="flex items-start justify-between"> <div className="flex items-start justify-between">
<h1 className="text-xl font-bold text-foreground"> <div className="flex items-center gap-3">
{t("cardRequisite.viewTitle", "Kart rekwizit giňişleýin")}: {data.id} <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => navigate("/card-requisites")}>
</h1> <ArrowLeft className="size-4" />
<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} />
</Button> </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> <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} /> <Trash2 size={15} />
</Button> </Button>
</AlertDialogTitle> </AlertDialogTitle>
@@ -133,60 +147,78 @@ export default function CardRequisiteViewPage() {
<BentoGrid cols={3}> <BentoGrid cols={3}>
<BentoCard title={t("cardRequisite.metaSection", "Esasy maglumatlar")}> <BentoCard title={t("cardRequisite.metaSection", "Esasy maglumatlar")}>
<InfoRow label={t("common.id", "ID")} value={data.id} /> <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")}> <InfoRow label={t("cardRequisite.status", "Status")}>
<CardRequisiteStatusBadge status={data.status} /> <CardRequisiteStatusBadge status={data.status} />
</InfoRow> </InfoRow>
<InfoRow label={t("cardRequisite.note", "Bellik")} value={data.note || undefined} /> <InfoRow label={t("cardRequisite.note", "Bellik")} value={data.notes || undefined} />
<InfoRow
label={t("cardRequisite.createdBy", "Sargyt eden")}
value={data.first_name && data.last_name ? `${data.last_name}_${data.first_name}` : undefined}
isLink
/>
</BentoCard> </BentoCard>
<BentoCard title={t("cardRequisite.cardSection", "Kart")}> <BentoCard title={t("cardRequisite.cardSection", "Kart")}>
<InfoRow label={t("cardRequisite.cardNumber", "Kart belgisi")} value={data.card_number} /> <InfoRow
<InfoRow label={t("cardRequisite.cardExpireMonth", "Kart Möhleti (aý)")} value={data.card_expiry_month} /> label={t("cardRequisite.cardType", "Kart görnüşi")}
<InfoRow label={t("cardRequisite.cardExpireYear", "Kart Möhleti (ýyl)")} value={data.card_expiry_year} /> 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>
<BentoCard title={t("cardRequisite.locationSection", "Lokasiýa")}> <BentoCard title={t("cardRequisite.locationSection", "Lokasiýa")}>
<InfoRow label={t("cardRequisite.province", "Welaýat")} value={data.province_name ?? undefined} /> <InfoRow label={t("cardRequisite.region", "Welaýat")} value={data.region || undefined} />
<InfoRow label={t("cardRequisite.branch", "Şahamça")} value={data.branch_name ?? undefined} isLink /> <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> </BentoCard>
</BentoGrid> </BentoGrid>
{/* ── Row 2: Şahsy + Pasport maglumatlary ──────────────────────────── */} {/* ── Row 2: Şahsy + Ulanyjy + Pasport maglumatlary ─────────────────── */}
<BentoGrid cols={2}> <BentoGrid cols={2}>
<BentoCard title={t("cardRequisite.personalSection", "Şahsy maglumatlar")}> <BentoCard title={t("cardRequisite.personalSection", "Şahsy maglumatlar")}>
<InfoRow <InfoRow label={t("cardRequisite.fullName", "Doly ady")} value={fullName} />
label={t("cardRequisite.fullName", "Doly ady")} <InfoRow label={t("cardRequisite.birthDate", "Doglan güni")} value={formatDate(data.bornAt)} />
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.phone", "Telefon")} value={data.phone} /> <InfoRow label={t("cardRequisite.phone", "Telefon")} value={data.phone} />
</BentoCard> </BentoCard>
<BentoCard title={t("cardRequisite.passportSection", "Pasport")}> <BentoCard title={t("cardRequisite.userSection", "Ulanyjy")}>
<InfoRow label={t("cardRequisite.passportSeries", "Pasport seriýasy")} value={data.passport_series} /> <InfoRow
<InfoRow label={t("cardRequisite.passportNumber", "Pasport belgisi")} value={data.passport_number} /> 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> </BentoCard>
</BentoGrid> </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}> <BentoGrid cols={4}>
<BentoCard title={t("cardRequisite.passportFile1", "Sahypa 1")}> <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>
<BentoCard title={t("cardRequisite.passportFile2", "Sahypa 2-3")}> <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>
<BentoCard title={t("cardRequisite.passportFile3", "Sahypa 8-9")}> <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>
<BentoCard title={t("cardRequisite.passportFile4", "Sahypa 32")}> <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> </BentoCard>
</BentoGrid> </BentoGrid>
</div> </div>
@@ -1,16 +1,18 @@
import { useState, useMemo, useCallback } from "react"; import { useState, useMemo, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { AlertCircle, CheckCircle2, XCircle, CheckCheck } from "lucide-react"; import { AlertCircle, CheckCircle2, XCircle, CheckCheck } from "lucide-react";
import { useNavigate } from "react-router-dom";
import type { ColumnDef, VisibilityState } from "@tanstack/react-table"; import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
import { StatusBadge } from "@/components/ui/statusBadge";
import { DataTable } from "@/components/dataTable"; import { DataTable } from "@/components/dataTable";
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar"; import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
import { TableSearchInput } from "@/components/tableSearch"; import { TableSearchInput } from "@/components/tableSearch";
import { CreateButton } from "@/components/createButton"; import { CreateButton } from "@/components/createButton";
import { TableActions } from "@/components/tableActions"; import { TableActions } from "@/components/tableActions";
import { StatusBadge } from "@/components/ui/statusBadge";
import { useLoanOrderMobiles, useDeleteLoanOrderMobile } from "@/features/loanOrderMobiles/hooks/useLoanOrderMobiles"; import { useLoanOrderMobiles, useDeleteLoanOrderMobile } from "@/features/loanOrderMobiles/hooks/useLoanOrderMobiles";
import type { LoanOrderMobile, LoanOrderMobileStatus } from "@/features/loanOrderMobiles/api/loanOrderMobilesApi"; import type { LoanOrderMobile, LoanOrderMobileStatus } from "@/features/loanOrderMobiles/api/loanOrderMobilesApi";
import { useInfiniteBranches } from "@/features/branches/hooks/useBranches";
import { DeleteDialog } from "@/components/deleteDialog"; import { DeleteDialog } from "@/components/deleteDialog";
import { getStatusLabel, getStatusOptions, STATUS_BADGE_VARIANTS, type StatusValue } from "@/constants"; 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; 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_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const;
const REGION_OPTIONS = ["Balkan", "Ahal", "Daşoguz", "Lebap", "Mary", "Aşgabat"];
// ─── Page Component ──────────────────────────────────────────────────────────── // ─── Page Component ───────────────────────────────────────────────────────────
export default function LoanOrderMobilesPage() { 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 navigate = useNavigate();
const deleteMutation = useDeleteLoanOrderMobile(); const deleteMutation = useDeleteLoanOrderMobile();
const [deleteId, setDeleteId] = useState<string | null>(null); 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 [search, setSearch] = useState("");
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(25); const [perPage, setPerPage] = useState(25);
@@ -60,7 +81,6 @@ export default function LoanOrderMobilesPage() {
{ fieldId: "archived", value: "" }, { fieldId: "archived", value: "" },
]); ]);
// ── Query params ───────────────────────────────────────────────────────────
const queryParams = useMemo(() => { const queryParams = useMemo(() => {
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value])); const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
return { return {
@@ -77,7 +97,8 @@ export default function LoanOrderMobilesPage() {
const { data, isLoading } = useLoanOrderMobiles(queryParams); const { data, isLoading } = useLoanOrderMobiles(queryParams);
const totalPages = data ? Math.ceil(data.total / perPage) : 1; 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) => { const handleFilterChange = useCallback((fieldId: string, value: string) => {
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f))); setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
setPage(1); setPage(1);
@@ -98,68 +119,69 @@ export default function LoanOrderMobilesPage() {
setDeleteId(null); setDeleteId(null);
}, [deleteId, deleteMutation]); }, [deleteId, deleteMutation]);
// ── Columns ────────────────────────────────────────────────────────────────
const columns = useMemo<ColumnDef<LoanOrderMobile>[]>( const columns = useMemo<ColumnDef<LoanOrderMobile>[]>(
() => [ () => [
{ {
id: "id", id: "id",
accessorKey: "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>, cell: ({ row }) => <span className="text-xs font-mono text-muted-foreground">{row.original.id}</span>,
size: 130, size: 130,
}, },
{ {
id: "loanType", id: "loanType",
accessorKey: "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>, cell: ({ row }) => <span className="text-sm font-medium text-primary hover:underline cursor-pointer">{row.original.loanType}</span>,
}, },
{ {
id: "createdAt", id: "createdAt",
accessorKey: "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>, cell: ({ row }) => <span className="text-sm text-foreground whitespace-nowrap">{row.original.createdAt}</span>,
size: 160, size: 160,
}, },
{ {
id: "region", id: "region",
accessorKey: "region", accessorKey: "region",
header: t("loanOrderMobiles.columns.region", "WELAÝAT"), header: t("Region", "WELAÝAT"),
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.region}</span>, cell: ({ row }) => (
<span className="text-sm text-foreground">{t(`loanOrders.regions.${row.original.region}`, row.original.region)}</span>
),
size: 100, size: 100,
}, },
{ {
id: "branch", id: "branch",
accessorKey: "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>, cell: ({ row }) => <span className="text-sm text-emerald-500 font-medium">{row.original.branch}</span>,
size: 100, size: 100,
}, },
{ {
id: "firstName", id: "firstName",
accessorKey: "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>, cell: ({ row }) => <span className="text-sm text-foreground">{row.original.firstName}</span>,
size: 110, size: 110,
}, },
{ {
id: "lastName", id: "lastName",
accessorKey: "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>, cell: ({ row }) => <span className="text-sm text-foreground">{row.original.lastName}</span>,
size: 120, size: 120,
}, },
{ {
id: "phone", id: "phone",
accessorKey: "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>, cell: ({ row }) => <span className="text-sm font-mono text-foreground">{row.original.phone}</span>,
size: 110, size: 110,
}, },
{ {
id: "status", id: "status",
accessorKey: "status", accessorKey: "status",
header: t("loanOrderMobiles.columns.status", "STATUS"), header: t("Status", "STATUS"),
cell: ({ row }) => <LoanOrderStatusBadge status={row.original.status} />, cell: ({ row }) => <LoanOrderStatusBadge status={row.original.status} />,
size: 180, size: 180,
}, },
@@ -178,47 +200,51 @@ export default function LoanOrderMobilesPage() {
size: 100, 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(`loanOrders.columns.${id}`, id) })), [t]);
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`loanOrderMobiles.columns.${id}`, id) })), [t]);
const filterFields = useMemo<FilterField[]>( const filterFields = useMemo<FilterField[]>(
() => [ () => [
{ {
id: "region", id: "region",
label: t("loanOrderMobiles.filters.region", "WELAÝAT"), label: t("Region", "WELAÝAT"),
options: REGION_OPTIONS.map((v) => ({ value: v, label: t(v) })), options: regionOptions,
}, },
{ {
id: "status", id: "status",
label: t("loanOrderMobiles.filters.status", "STATUS"), label: t("Status", "STATUS"),
options: getStatusOptions(t, "loanOrderStatus"), options: getStatusOptions(t, "loanOrderStatus"),
}, },
{ {
id: "branch", id: "branch",
label: t("loanOrderMobiles.filters.branch", "ŞAHAMÇA"), label: t("Branch", "ŞAHAMÇA"),
options: [], type: "infinite-select",
options: branchOptions,
loading: isBranchesLoading,
isLoadingMore: isFetchingNextBranches,
hasNextPage: hasNextBranches,
onLoadMore: fetchNextBranches,
searchValue: branchSearch,
onSearchChange: setBranchSearch,
}, },
{ {
id: "archived", id: "archived",
label: t("loanOrderMobiles.filters.archived", "ARHIWLENEN"), label: t("loanOrders.filters.archived", "ARHIWLENEN"),
options: [ options: [
{ value: "true", label: t("common.yes", "Hawa") }, { value: "true", label: t("common.yes", "Hawa") },
{ value: "false", label: t("common.no", "Ýok") }, { value: "false", label: t("common.no", "Ýok") },
], ],
}, },
], ],
[t], [t, regionOptions, branchOptions, isBranchesLoading, isFetchingNextBranches, hasNextBranches, branchSearch],
); );
// ──────────────────────────────────────────────────────────────────────────
return ( return (
<div className="space-y-4"> <div className="space-y-4">
{/* Page Header */}
<div className="flex items-center justify-between"> <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>
<div className="flex items-center gap-3 justify-between"> <div className="flex items-center gap-3 justify-between">
@@ -228,23 +254,24 @@ export default function LoanOrderMobilesPage() {
setSearch(v); setSearch(v);
setPage(1); setPage(1);
}} }}
placeholder={t("common.search", "Gözlemek")} placeholder={t("loanOrderMobiles.searchPlaceholder", "Gözlemek")}
/> />
<CreateButton <CreateButton
label={t("loanOrderMobiles.createButton", "Karz sargyt dörediň")} label={t("loanOrderMobiles.createButton", "Karz sargyt dörediñ")}
onClick={() => navigate("/loan-order-mobiles/create")} onClick={() => navigate("/loan-order-mobiles/create")}
/> />
</div> </div>
{/* Table Card */}
<div className="bg-card border border-border rounded-xl p-4"> <div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar <DataTableToolbar
hideSearch
hideAction
searchValue={search} searchValue={search}
onSearchChange={(v) => { onSearchChange={(v) => {
setSearch(v); setSearch(v);
setPage(1); setPage(1);
}} }}
searchPlaceholder={t("common.search", "Gözlemek")} searchPlaceholder={t("loanOrderMobiles.searchPlaceholder", "Gözlemek")}
columns={toggleableColumns} columns={toggleableColumns}
columnVisibility={columnVisibility} columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility} onColumnVisibilityChange={setColumnVisibility}
@@ -260,8 +287,6 @@ export default function LoanOrderMobilesPage() {
setPerPage(v); setPerPage(v);
setPage(1); setPage(1);
}} }}
hideSearch
hideAction
/> />
<DataTable <DataTable
+65 -26
View File
@@ -24,7 +24,7 @@ import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions"; import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions";
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers"; import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
import { useInfiniteStaff } from "@/features/operators/hooks/useOperators"; 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"; import type { LocalizedText } from "@/features/branches/api/branchesApi";
type AssignDialogKind = "role" | "permission" | "branch"; 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 lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
const branches = user?.branches ?? []; const branches = user?.branches ?? [];
const permissions = user?.permissions ?? [];
// ── Form State for Editing ── // ── Form State for Editing ──
const [formData, setFormData] = useState({ const [formData, setFormData] = useState({
@@ -233,7 +234,22 @@ export default function ProfilePage() {
</InfoRow> </InfoRow>
<InfoRow label={t("users.sections.permissions", "Rugsatlar")}> <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> </InfoRow>
</BentoCard> </BentoCard>
@@ -336,26 +352,31 @@ const ASSIGN_DIALOG_FIELD_LABELS: Record<AssignDialogKind, string> = {
}; };
/** /**
* Dialog for assigning a role / permission / branch to a staff user. * Dialog for assigning a role / branch to a staff user, or assigning a permission to a role.
* Two selects: target user (GET /users/staff) and the resource to assign.
*/ */
function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () => void }) { function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () => void }) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText; const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
const [userSearch, setUserSearch] = useState(""); const isPermission = kind === "permission";
const [userValue, setUserValue] = useState("");
const [targetSearch, setTargetSearch] = useState("");
const [targetValue, setTargetValue] = useState("");
const [resourceSearch, setResourceSearch] = useState(""); const [resourceSearch, setResourceSearch] = useState("");
const [resourceValue, setResourceValue] = useState(""); const [resourceValue, setResourceValue] = useState("");
const [error, setError] = useState<string | undefined>(); 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 rolesQuery = useInfiniteRoles(resourceSearch, kind === "role");
const permissionsQuery = useInfinitePermissions(resourceSearch, kind === "permission"); const permissionsQuery = useInfinitePermissions(resourceSearch, kind === "permission");
const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch"); const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch");
const roleMutation = useAssignRoleToUser(); const roleMutation = useAssignRoleToUser();
const permissionMutation = useAssignPermissionToUser(); const permissionMutation = useAssignPermissionToRole();
const branchMutation = useAssignBranchToUser(); const branchMutation = useAssignBranchToUser();
const isPending = roleMutation.isPending || permissionMutation.isPending || branchMutation.isPending; const isPending = roleMutation.isPending || permissionMutation.isPending || branchMutation.isPending;
@@ -370,6 +391,24 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
[staffQuery.data], [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(() => { const resourceOptions: InfiniteSelectOption[] = useMemo(() => {
if (kind === "role") { if (kind === "role") {
return (rolesQuery.data?.pages ?? []) return (rolesQuery.data?.pages ?? [])
@@ -406,23 +445,23 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
}; };
const handleSubmit = () => { const handleSubmit = () => {
if (!userValue || !resourceValue) { if (!targetValue || !resourceValue) {
setError(t("common.errors.required", "Meýdança hökmany doldurylmaly")); setError(t("common.errors.required", "Meýdança hökmany doldurylmaly"));
return; return;
} }
setError(undefined); setError(undefined);
const userId = Number(userValue); const firstId = Number(targetValue);
const resourceId = Number(resourceValue); const secondId = Number(resourceValue);
const onSuccess = () => { const onSuccess = () => {
setUserValue(""); setTargetValue("");
setResourceValue(""); setResourceValue("");
onClose(); onClose();
}; };
if (kind === "role") roleMutation.mutate({ userId, roleId: resourceId }, { onSuccess }); if (kind === "role") roleMutation.mutate({ userId: firstId, roleId: secondId }, { onSuccess });
else if (kind === "permission") permissionMutation.mutate({ userId, permissionId: resourceId }, { onSuccess }); else if (kind === "permission") permissionMutation.mutate({ roleId: firstId, permissionId: secondId }, { onSuccess });
else branchMutation.mutate({ userId, branchId: resourceId }, { onSuccess }); else branchMutation.mutate({ userId: firstId, branchId: secondId }, { onSuccess });
}; };
return ( return (
@@ -438,20 +477,20 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
<div className="space-y-3"> <div className="space-y-3">
<InfiniteSelect <InfiniteSelect
required required
label={t("profile.assign.userLabel", "Ulanyjy (staff)")} label={targetLabel}
value={userValue} value={targetValue}
onChange={(v) => { onChange={(v) => {
setUserValue(v); setTargetValue(v);
if (error) setError(undefined); if (error) setError(undefined);
}} }}
options={staffOptions} options={targetOptions}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
loading={staffQuery.isLoading} loading={targetLoading}
isLoadingMore={staffQuery.isFetchingNextPage} isLoadingMore={targetLoadingMore}
hasNextPage={!!staffQuery.hasNextPage} hasNextPage={targetHasNextPage}
onLoadMore={() => staffQuery.fetchNextPage()} onLoadMore={loadMoreTargets}
searchValue={userSearch} searchValue={targetSearch}
onSearchChange={setUserSearch} onSearchChange={setTargetSearch}
/> />
<InfiniteSelect <InfiniteSelect
@@ -478,7 +517,7 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
<Button variant="ghost" size="sm" onClick={onClose} disabled={isPending}> <Button variant="ghost" size="sm" onClick={onClose} disabled={isPending}>
{t("common.cancel", "Yza")} {t("common.cancel", "Yza")}
</Button> </Button>
<Button size="sm" onClick={handleSubmit} disabled={!userValue || !resourceValue || isPending}> <Button size="sm" onClick={handleSubmit} disabled={!targetValue || !resourceValue || isPending}>
{t("common.save", "Ýatda sakla")} {t("common.save", "Ýatda sakla")}
</Button> </Button>
</AlertDialogFooter> </AlertDialogFooter>