From d8e903f24c595616c43525b911b5faf4d9dd4a7f Mon Sep 17 00:00:00 2001 From: Jelaletdin12 Date: Sat, 29 Aug 2026 12:28:24 +0500 Subject: [PATCH] connected api with card balance and and requisites --- src/app/store/authStore.ts | 7 + .../cardBalance/api/cardBalanceApi.ts | 148 +-- .../components/cardBalanceForm.tsx | 152 ++- .../components/cardBalanceStatusBadge.tsx | 20 + .../cardBalance/hooks/useCardBalance.ts | 102 +- .../cardBalance/schemas/cardBalance.schema.ts | 68 +- .../cardRequisites/api/cardRequisitesApi.ts | 353 ++--- .../components/cardRequisiteForm.tsx | 502 +++---- .../cardRequisites/hooks/useCardRequisites.ts | 100 +- .../schemas/cardRequisite.schema.ts | 172 ++- .../api/loanOrderMobilesApi.ts | 544 +------- .../components/loanOrderMobileForm.tsx | 1155 ++++++++++------- .../hooks/useLoanOrderMobiles.ts | 76 +- .../schemas/loanOrderMobile.schema.ts | 296 +---- src/features/loanOrders/api/loanOrdersApi.ts | 148 ++- src/features/shared/api/sharedApi.ts | 16 +- .../shared/hooks/useSharedUserAssignments.ts | 15 +- .../cardDepartment/cardBalance/index.tsx | 309 +++-- .../cardDepartment/cardBalanceView/index.tsx | 178 +-- .../cardDepartment/cardRequisites/index.tsx | 452 +++++-- .../cardRequisitesEdit/index.tsx | 25 +- .../cardRequisitesView/index.tsx | 132 +- .../loanDepartment/loanOrderMobile/index.tsx | 107 +- src/pages/profile/index.tsx | 91 +- 24 files changed, 2540 insertions(+), 2628 deletions(-) create mode 100644 src/features/cardBalance/components/cardBalanceStatusBadge.tsx diff --git a/src/app/store/authStore.ts b/src/app/store/authStore.ts index ee43f75..89c962a 100644 --- a/src/app/store/authStore.ts +++ b/src/app/store/authStore.ts @@ -16,6 +16,12 @@ export interface AuthUserBranch { name: LocalizedText; } +export interface AuthUserPermission { + id: number; + code?: string; + name?: string; +} + export interface AuthUser { id?: string | number; name: string; @@ -26,6 +32,7 @@ export interface AuthUser { role?: AuthUserRole; avatar?: string; branches?: AuthUserBranch[]; + permissions?: AuthUserPermission[]; createdAt?: string; } diff --git a/src/features/cardBalance/api/cardBalanceApi.ts b/src/features/cardBalance/api/cardBalanceApi.ts index a9a6fd2..1174164 100644 --- a/src/features/cardBalance/api/cardBalanceApi.ts +++ b/src/features/cardBalance/api/cardBalanceApi.ts @@ -1,104 +1,96 @@ -import apiClient from '@/lib/api/client' +import apiClient from "@/lib/api/client"; // ─── Types ──────────────────────────────────────────────────────────────────── +export type CardBalanceStatus = "pending" | "approved" | "rejected"; + +export interface CardBalanceUser { + id: number; + name: string; + username: string; + phone: string; + email: string; +} + +/** Raw backend entity (GET responses mirror this shape). */ export interface CardBalance { - id: number - passport_series: string - passport_number: string - card_number: string - card_expiry_month: string - card_expiry_year: string + id: number; + passportNumber: string; + cardLast4: string; + expiryMonth: number; + expiryYear: number; + expiryAt: string; + balanceAmount: number; + balanceCurrency: string; + status: string; + checkedAt: string; + createdBy: CardBalanceUser; + createdAt: string; + updatedAt: string; } +/** LIST RESPONSE: GET /card-balances */ export interface CardBalanceListResponse { - data: CardBalance[] - total: number - page: number - per_page: number + count: number; + cardBalances: CardBalance[]; } -export interface CreateCardBalancePayload { - passport_series: string - passport_number: string - card_number: string - card_expiry_month: string - card_expiry_year: string -} - -export type UpdateCardBalancePayload = CreateCardBalancePayload - +/** LIST PARAMS */ export interface CardBalanceListParams { - page?: number - per_page?: number - search?: string + page?: number; + limit?: number; + status?: string; + passport_number?: string; + created_by?: number | string; } -// ─── API ───────────────────────────────────────────────────────────────────── +/** CREATE / UPDATE PAYLOAD (camelCase, JSON) */ +export interface CardBalancePayload { + balanceAmount: number; + balanceCurrency: string; + cardNumber: string; + checkedAt: string; + createdBy: number; + expiryMonth: number; + expiryYear: number; + passportNumber: string; + status: string; +} -const MOCK_CARD_BALANCES: CardBalance[] = [ - { - id: 1, - passport_series: 'AA', - passport_number: '1112223', - card_number: '8600123412341234', - card_expiry_month: '10', - card_expiry_year: '2028', - }, - { - id: 2, - passport_series: 'I-MR', - passport_number: '9988776', - card_number: '9860123456789012', - card_expiry_month: '05', - card_expiry_year: '2027', - }, - { - id: 3, - passport_series: 'II-LB', - passport_number: '4455667', - card_number: '4400556677889900', - card_expiry_month: '12', - card_expiry_year: '2026', - }, -] +// ─── API Functions ───────────────────────────────────────────────────────────── export const cardBalancesApi = { - getAll: async (params?: CardBalanceListParams): Promise => { - // Mock data kullanmak için: - return { data: MOCK_CARD_BALANCES, total: MOCK_CARD_BALANCES.length, page: params?.page || 1, per_page: params?.per_page || 25 } - - const { data } = await apiClient.get('/card-balances', { params }) - return data + getList: async (params: CardBalanceListParams = {}, signal?: AbortSignal): Promise => { + const { page, limit, status, passport_number, created_by } = params; + const { data } = await apiClient.get("/card-balances", { + params: { + page, + limit, + status: status || undefined, + passport_number: passport_number || undefined, + created_by: created_by || undefined, + }, + signal, + }); + return data; }, getById: async (id: number): Promise => { - // Mock data kullanmak için: - const mock = MOCK_CARD_BALANCES.find(b => b.id === id) - if (mock) return mock - - const { data } = await apiClient.get(`/card-balances/${id}`) - return data + const { data } = await apiClient.get(`/card-balances/${id}`); + return data; }, - create: async (payload: CreateCardBalancePayload): Promise => { - const { data } = await apiClient.post('/card-balances', payload) - return data + create: async (payload: CardBalancePayload): Promise => { + const { data } = await apiClient.post("/card-balances", payload); + return data; }, - update: async (id: number, payload: UpdateCardBalancePayload): Promise => { - const { data } = await apiClient.put(`/card-balances/${id}`, payload) - return data + update: async (id: number, payload: CardBalancePayload): Promise => { + const { data } = await apiClient.put(`/card-balances/${id}`, payload); + return data; }, delete: async (id: number): Promise => { - await apiClient.delete(`/card-balances/${id}`) + await apiClient.delete(`/card-balances/${id}`); }, - - download: async (id: number): Promise => { - const { data } = await apiClient.get(`/card-balances/${id}/download`, { - responseType: 'blob', - }) - return data - }, -} \ No newline at end of file +}; diff --git a/src/features/cardBalance/components/cardBalanceForm.tsx b/src/features/cardBalance/components/cardBalanceForm.tsx index 09c6cd7..791861f 100644 --- a/src/features/cardBalance/components/cardBalanceForm.tsx +++ b/src/features/cardBalance/components/cardBalanceForm.tsx @@ -1,13 +1,15 @@ -import { useCallback, useMemo } from "react"; +import { useState, useCallback, useMemo } from "react"; import { useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; import { useForm } from "react-hook-form"; -import { FormInput } from "@/components/formInput"; +import { FormInput, type SelectOption } from "@/components/formInput"; +import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect"; import { FormActions } from "@/components/formActions"; import { type CardBalance } from "@/features/cardBalance/api/cardBalanceApi"; import { useCreateCardBalance, useUpdateCardBalance } from "@/features/cardBalance/hooks/useCardBalance"; -import { cardBalanceFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "@/features/cardBalance/schemas/cardBalance.schema"; +import { cardBalanceFormSchema, DEFAULT_FORM_VALUES, mapInitial, buildPayload } from "@/features/cardBalance/schemas/cardBalance.schema"; import type { CardBalanceFormData } from "@/features/cardBalance/schemas/cardBalance.schema"; +import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers"; interface CardBalanceFormProps { mode: "create" | "edit"; @@ -27,28 +29,25 @@ function flattenErrors(errors: Record) // ─── Constants ──────────────────────────────────────────────────────────────── -const PASSPORT_SERIES_OPTIONS = [ - { value: "I-MR", label: "I-MR" }, - { value: "II-MR", label: "II-MR" }, - { value: "I-LB", label: "I-LB" }, - { value: "II-LB", label: "II-LB" }, - { value: "III-LB", label: "III-LB" }, - { value: "I-BN", label: "I-BN" }, - { value: "II-BN", label: "II-BN" }, - { value: "I-AH", label: "I-AH" }, - { value: "I-AS", label: "I-AS" }, - { value: "I-DZ", label: "I-DZ" }, - { value: "II-DZ", label: "II-DZ" }, - { value: "A", label: "A" }, - { value: "B", label: "B" }, +const STATUS_OPTIONS: SelectOption[] = [ + { value: "pending", label: "Garaşylýar" }, + { value: "approved", label: "Tassyklanan" }, + { value: "rejected", label: "Ret edilen" }, ]; -const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => { +const CURRENCY_OPTIONS: SelectOption[] = [ + { value: "TMT", label: "TMT" }, + { value: "USD", label: "USD" }, + { value: "RUB", label: "RUB" }, + { value: "EUR", label: "EUR" }, +]; + +const MONTH_OPTIONS: SelectOption[] = Array.from({ length: 12 }, (_, i) => { const val = String(i + 1).padStart(2, "0"); return { value: val, label: val }; }); -const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => { +const YEAR_OPTIONS: SelectOption[] = Array.from({ length: 20 }, (_, i) => { const year = String(new Date().getFullYear() + i); return { value: year, label: year }; }); @@ -63,6 +62,22 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) { const updateMutation = useUpdateCardBalance(initialData?.id ?? 0); const isPending = createMutation.isPending || updateMutation.isPending; + const [userSearch, setUserSearch] = useState(""); + const userQuery = useInfiniteUsers(userSearch); + + const userOptions: InfiniteSelectOption[] = useMemo(() => { + const opts: InfiniteSelectOption[] = (userQuery.data?.pages ?? []) + .flatMap((p) => p?.users ?? []) + .map((u) => ({ value: String(u.id), label: u.name || u.username || String(u.id) })); + if (initialData?.createdBy?.id && !opts.some((o) => o.value === String(initialData.createdBy.id))) { + opts.unshift({ + value: String(initialData.createdBy.id), + label: initialData.createdBy.name || String(initialData.createdBy.id), + }); + } + return opts; + }, [userQuery, initialData]); + const { watch, setValue, @@ -71,20 +86,22 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) { clearErrors, setError, } = useForm({ - defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...initialData } : DEFAULT_FORM_VALUES, + defaultValues: initialData ? mapInitial(initialData) : DEFAULT_FORM_VALUES, }); const form = watch(); const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); - const setField = useCallback( - (field: keyof CardBalanceFormData) => (value: string) => { - (setValue as (name: keyof CardBalanceFormData, val: string) => void)(field, value); - clearErrors(field); + const set = useCallback( + (key: K, value: CardBalanceFormData[K]) => { + (setValue as (name: K, val: CardBalanceFormData[K]) => void)(key, value); + clearErrors(key); }, [setValue, clearErrors], ); + const setString = (key: keyof CardBalanceFormData) => (value: string) => set(key, value as CardBalanceFormData[typeof key]); + const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg); const handleSubmit = async () => { @@ -120,60 +137,101 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
- {/* Row 1 */} - {/* Row 2 — card number full width + 2 selects */} -
+ + + + + + 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 + />
= { + 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 {status}; + return ; +} diff --git a/src/features/cardBalance/hooks/useCardBalance.ts b/src/features/cardBalance/hooks/useCardBalance.ts index f157d89..024acb7 100644 --- a/src/features/cardBalance/hooks/useCardBalance.ts +++ b/src/features/cardBalance/hooks/useCardBalance.ts @@ -1,84 +1,80 @@ -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { toast } from 'sonner' -import { useTranslation } from 'react-i18next' -import { - cardBalancesApi, - type CardBalanceListParams, - type CreateCardBalancePayload, - type UpdateCardBalancePayload, -} from '../api/cardBalanceApi' +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { useTranslation } from "react-i18next"; +import { cardBalancesApi, type CardBalanceListParams, type CardBalancePayload } from "../api/cardBalanceApi"; -const QUERY_KEY = 'card-balances' +// ─── Query Keys ─────────────────────────────────────────────────────────────── -export function useCardBalances(params?: CardBalanceListParams) { +export const cardBalanceKeys = { + all: ["cardBalances"] as const, + lists: () => [...cardBalanceKeys.all, "list"] as const, + list: (params: CardBalanceListParams) => [...cardBalanceKeys.lists(), params] as const, + details: () => [...cardBalanceKeys.all, "detail"] as const, + detail: (id: number) => [...cardBalanceKeys.details(), id] as const, +}; + +// ─── List ───────────────────────────────────────────────────────────────────── + +export function useCardBalances(params: CardBalanceListParams = {}) { return useQuery({ - queryKey: [QUERY_KEY, params], - queryFn: () => cardBalancesApi.getAll(params), - }) + queryKey: cardBalanceKeys.list(params), + queryFn: ({ signal }) => cardBalancesApi.getList(params, signal), + placeholderData: (prev) => prev, + }); } +// ─── Single ─────────────────────────────────────────────────────────────────── + export function useCardBalance(id: number) { return useQuery({ - queryKey: [QUERY_KEY, id], + queryKey: cardBalanceKeys.detail(id), queryFn: () => cardBalancesApi.getById(id), enabled: !!id, - }) + }); } +// ─── Create ─────────────────────────────────────────────────────────────────── + export function useCreateCardBalance() { - const queryClient = useQueryClient() - const { t } = useTranslation() + const queryClient = useQueryClient(); + const { t } = useTranslation(); return useMutation({ - mutationFn: (payload: CreateCardBalancePayload) => cardBalancesApi.create(payload), + mutationFn: (payload: CardBalancePayload) => cardBalancesApi.create(payload), onSuccess: () => { - queryClient.invalidateQueries({ queryKey: [QUERY_KEY] }) - toast.success(t('Card balance created successfully', 'Kart galyndysy üstünlikli döredildi')) + queryClient.invalidateQueries({ queryKey: cardBalanceKeys.lists() }); + toast.success(t("cardBalance.createSuccess", "Kart galyndysy üstünlikli döredildi")); }, - }) + }); } +// ─── Update ─────────────────────────────────────────────────────────────────── + export function useUpdateCardBalance(id: number) { - const queryClient = useQueryClient() - const { t } = useTranslation() + const queryClient = useQueryClient(); + const { t } = useTranslation(); return useMutation({ - mutationFn: (payload: UpdateCardBalancePayload) => cardBalancesApi.update(id, payload), - onSuccess: () => { - queryClient.invalidateQueries({ queryKey: [QUERY_KEY] }) - toast.success(t('Card balance updated successfully', 'Kart galyndysy üstünlikli üýtgedildi')) + mutationFn: (payload: CardBalancePayload) => cardBalancesApi.update(id, payload), + onSuccess: (updated) => { + queryClient.invalidateQueries({ queryKey: cardBalanceKeys.lists() }); + queryClient.setQueryData(cardBalanceKeys.detail(id), updated); + toast.success(t("cardBalance.updateSuccess", "Kart galyndysy üstünlikli üýtgedildi")); }, - }) + }); } +// ─── Delete ─────────────────────────────────────────────────────────────────── + export function useDeleteCardBalance() { - const queryClient = useQueryClient() - const { t } = useTranslation() + const queryClient = useQueryClient(); + const { t } = useTranslation(); return useMutation({ mutationFn: (id: number) => cardBalancesApi.delete(id), onSuccess: () => { - queryClient.invalidateQueries({ queryKey: [QUERY_KEY] }) - toast.success(t('Card balance deleted successfully', 'Kart galyndysy üstünlikli öçürildi')) + queryClient.invalidateQueries({ queryKey: cardBalanceKeys.lists() }); + toast.success(t("cardBalance.deleteSuccess", "Kart galyndysy üstünlikli öçürildi")); }, - }) + }); } - -export function useDownloadCardBalance() { - const { t } = useTranslation() - - return useMutation({ - mutationFn: async (id: number) => { - const blob = await cardBalancesApi.download(id) - const url = URL.createObjectURL(blob) - const a = document.createElement('a') - a.href = url - a.download = `card-balance-${id}.pdf` - a.click() - URL.revokeObjectURL(url) - }, - onSuccess: () => { - toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi')) - }, - }) -} \ No newline at end of file diff --git a/src/features/cardBalance/schemas/cardBalance.schema.ts b/src/features/cardBalance/schemas/cardBalance.schema.ts index 9bbf526..8b783bd 100644 --- a/src/features/cardBalance/schemas/cardBalance.schema.ts +++ b/src/features/cardBalance/schemas/cardBalance.schema.ts @@ -1,30 +1,56 @@ -import { z } from 'zod' -import type { CreateCardBalancePayload } from '../api/cardBalanceApi' +import { z } from "zod"; +import type { CardBalance, CardBalancePayload } from "../api/cardBalanceApi"; export const cardBalanceFormSchema = z.object({ - passport_series: z.string().min(1, 'validation.required'), - passport_number: z.string().min(1, 'validation.required'), - card_number: z.string().min(1, 'validation.required'), - card_expiry_month: z.string().min(1, 'validation.required'), - card_expiry_year: z.string().min(1, 'validation.required'), -}) + status: z.string().min(1, "validation.required"), + passportNumber: z.string().min(1, "validation.required"), + cardNumber: z.string().min(1, "validation.required"), + expiryMonth: z.string().min(1, "validation.required"), + expiryYear: z.string().min(1, "validation.required"), + balanceAmount: z.string().min(1, "validation.required"), + balanceCurrency: z.string().min(1, "validation.required"), + checkedAt: z.string().min(1, "validation.required"), + createdBy: z.string().min(1, "validation.required"), +}); -export type CardBalanceFormData = z.infer +export type CardBalanceFormData = z.infer; export const DEFAULT_FORM_VALUES: CardBalanceFormData = { - passport_series: '', - passport_number: '', - card_number: '', - card_expiry_month: '', - card_expiry_year: '', + status: "", + passportNumber: "", + cardNumber: "", + expiryMonth: "", + expiryYear: "", + balanceAmount: "", + balanceCurrency: "", + checkedAt: "", + createdBy: "", +}; + +export function mapInitial(data: CardBalance): CardBalanceFormData { + return { + status: data.status ?? "", + passportNumber: data.passportNumber ?? "", + cardNumber: "", + expiryMonth: data.expiryMonth != null ? String(data.expiryMonth) : "", + expiryYear: data.expiryYear != null ? String(data.expiryYear) : "", + balanceAmount: data.balanceAmount != null ? String(data.balanceAmount) : "", + balanceCurrency: data.balanceCurrency ?? "", + checkedAt: data.checkedAt ? data.checkedAt.slice(0, 10) : "", + createdBy: data.createdBy?.id != null ? String(data.createdBy.id) : "", + }; } -export function buildPayload(data: CardBalanceFormData): CreateCardBalancePayload { +export function buildPayload(data: CardBalanceFormData): CardBalancePayload { return { - passport_series: data.passport_series, - passport_number: data.passport_number, - card_number: data.card_number, - card_expiry_month: data.card_expiry_month, - card_expiry_year: data.card_expiry_year, - } + status: data.status, + passportNumber: data.passportNumber, + cardNumber: data.cardNumber, + expiryMonth: Number(data.expiryMonth), + expiryYear: Number(data.expiryYear), + balanceAmount: Number(data.balanceAmount), + balanceCurrency: data.balanceCurrency, + checkedAt: new Date(data.checkedAt).toISOString(), + createdBy: Number(data.createdBy), + }; } diff --git a/src/features/cardRequisites/api/cardRequisitesApi.ts b/src/features/cardRequisites/api/cardRequisitesApi.ts index 4203261..f69ba51 100644 --- a/src/features/cardRequisites/api/cardRequisitesApi.ts +++ b/src/features/cardRequisites/api/cardRequisitesApi.ts @@ -1,259 +1,146 @@ -import apiClient from '@/lib/api/client' +import apiClient from "@/lib/api/client"; // ─── Types ──────────────────────────────────────────────────────────────────── -export type CardRequisiteStatus = 'pending' | 'approved' | 'rejected' +export interface LocalizedText { + tm: string; + ru: string; + en: string; +} +export function resolveLocalizedName(name: LocalizedText | string | null | undefined, lang = "en"): string { + if (!name) return ""; + if (typeof name === "string") return name; + return name[lang as keyof LocalizedText] ?? name.tm ?? name.en ?? name.ru ?? ""; +} + +export type CardRequisiteStatus = "pending" | "approved" | "rejected"; + +export interface CardRequisiteUser { + id: number; + name: string; + username: string; + phone: string; + email: string; +} + +export interface CardRequisiteCardType { + id: number; + name: LocalizedText; +} + +export interface CardRequisiteBranch { + id: number; + name: LocalizedText; +} + +/** Raw backend entity (GET responses mirror this shape). */ export interface CardRequisite { - id: string - status: CardRequisiteStatus - note: string - created_at: string - - // Card - card_type: string - card_number: string - card_expiry_month: string - card_expiry_year: string - - // Location - province_id: string - branch_id: string - province_name?: string - branch_name?: string - - // Personal - first_name: string - last_name: string - middle_name?: string - birth_date: string - phone: string - - // Passport - passport_series: string - passport_number: string - passport_page1_url?: string - passport_page2_3_url?: string - passport_page8_9_url?: string - passport_page32_url?: string + id: number; + uniqueId: string; + user: CardRequisiteUser; + cardType: CardRequisiteCardType; + cardNumber: string; + cardMonth: string; + cardYear: string; + region: string; + branch: CardRequisiteBranch; + customerName: string; + customerSurname: string; + customerPatronicName: string; + bornAt: string; + phone: string; + passportSerie: string; + passportId: string; + passportOne: string; + passportTwo: string; + passportThree: string; + passportFour: string; + status: string; + notes: string; + createdAt: string; + updatedAt: string; } +/** LIST RESPONSE: GET /card-rekwizit-orders */ export interface CardRequisiteListResponse { - data: CardRequisite[] - total: number - page: number - per_page: number + count: number; + cardRekwizitOrders: CardRequisite[]; } -export interface CreateCardRequisitePayload { - status: CardRequisiteStatus - note?: string - card_type: string - card_number: string - card_expiry_month: string - card_expiry_year: string - province_id: string - branch_id: string - first_name: string - last_name: string - middle_name?: string - birth_date: string - phone: string - passport_series: string - passport_number: string - passport_page1?: File - passport_page2_3?: File - passport_page8_9?: File - passport_page32?: File -} - -export type UpdateCardRequisitePayload = CreateCardRequisitePayload - +/** LIST PARAMS */ export interface CardRequisiteListParams { - page?: number - per_page?: number - search?: string + page?: number; + limit?: number; + status?: string; + branch_id?: number | string; + user_id?: number | string; + card_type_id?: number | string; + region?: string; + search?: string; } -// ─── Helpers ────────────────────────────────────────────────────────────────── - -function buildFormData(payload: CreateCardRequisitePayload): FormData { - const fd = new FormData() - - const textFields: (keyof Omit< - CreateCardRequisitePayload, - 'passport_page1' | 'passport_page2_3' | 'passport_page8_9' | 'passport_page32' - >)[] = [ - 'status', 'note', 'card_type', 'card_number', 'card_expiry_month', - 'card_expiry_year', 'province_id', 'branch_id', 'first_name', 'last_name', - 'middle_name', 'birth_date', 'phone', 'passport_series', 'passport_number', - ] - - textFields.forEach((key) => { - const val = payload[key] - if (val !== undefined && val !== null) fd.append(key, val) - }) - - if (payload.passport_page1) fd.append('passport_page1', payload.passport_page1) - if (payload.passport_page2_3) fd.append('passport_page2_3', payload.passport_page2_3) - if (payload.passport_page8_9) fd.append('passport_page8_9', payload.passport_page8_9) - if (payload.passport_page32) fd.append('passport_page32', payload.passport_page32) - - return fd +/** CREATE / UPDATE PAYLOAD (camelCase, JSON) */ +export interface CardRequisitePayload { + bornAt: string; + branchId: number; + cardMonth: string; + cardNumber: string; + cardTypeId: number; + cardYear: string; + customerName: string; + customerPatronicName: string; + customerSurname: string; + notes: string; + passportFour: string; + passportId: string; + passportOne: string; + passportSerie: string; + passportThree: string; + passportTwo: string; + phone: string; + region: string; + status: string; + uniqueId: string; + userId: number; } -// ─── Mock data ───────────────────────────────────────────────────────────────── - -const MOCK_CARD_REQUISITES: CardRequisite[] = [ - { - id: '1', - status: 'pending', - note: '', - card_type: 'UZCARD', - card_number: '8600123456789012', - card_expiry_month: '12', - card_expiry_year: '28', - province_id: '1', - branch_id: '1', - province_name: 'Toshkent', - branch_name: 'Filial 1', - first_name: 'Ali', - last_name: 'Valiyev', - middle_name: 'Akbarovich', - birth_date: '1990-05-15', - phone: '+998901234567', - passport_series: 'AA', - passport_number: '1234567', - created_at: '2025-01-15T10:30:00Z', - }, - { - id: '2', - status: 'approved', - note: 'Approved', - card_type: 'HUMO', - card_number: '9860123456789012', - card_expiry_month: '05', - card_expiry_year: '27', - province_id: '2', - branch_id: '3', - province_name: 'Samarqand', - branch_name: 'Filial 3', - first_name: 'Bobur', - last_name: 'Karimov', - middle_name: 'Rustamovich', - birth_date: '1985-08-22', - phone: '+998907654321', - passport_series: 'AB', - passport_number: '7654321', - created_at: '2025-02-20T14:00:00Z', - }, - { - id: '3', - status: 'rejected', - note: 'Hujjatlar not\'g\'ri', - card_type: 'VISA', - card_number: '4400123456789012', - card_expiry_month: '08', - card_expiry_year: '26', - province_id: '3', - branch_id: '5', - province_name: 'Buxoro', - branch_name: 'Filial 5', - first_name: 'Dilorom', - last_name: 'Rahimova', - middle_name: 'Shavkatovna', - birth_date: '1995-11-02', - phone: '+998903334455', - passport_series: 'AC', - passport_number: '1122334', - created_at: '2025-03-10T09:15:00Z', - }, - { - id: '4', - status: 'pending', - note: '', - card_type: 'UZCARD', - card_number: '5300123456789012', - card_expiry_month: '01', - card_expiry_year: '30', - province_id: '4', - branch_id: '7', - province_name: 'Farg\'ona', - branch_name: 'Filial 7', - first_name: 'Elyor', - last_name: 'Toshmatov', - middle_name: 'Olimovich', - birth_date: '2000-03-18', - phone: '+998905556677', - passport_series: 'KA', - passport_number: '9988776', - created_at: '2025-04-05T16:45:00Z', - }, - { - id: '5', - status: 'approved', - note: 'Tasdiqlangan', - card_type: 'HUMO', - card_number: '6200123456789012', - card_expiry_month: '03', - card_expiry_year: '29', - province_id: '5', - branch_id: '9', - province_name: 'Namangan', - branch_name: 'Filial 9', - first_name: 'Gulnora', - last_name: 'Abdullayeva', - middle_name: 'Anvarovna', - birth_date: '1992-07-30', - phone: '+998908889900', - passport_series: 'KB', - passport_number: '5566778', - created_at: '2025-05-12T11:30:00Z', - }, -] - -// ─── API functions ──────────────────────────────────────────────────────────── +// ─── API Functions ───────────────────────────────────────────────────────────── export const cardRequisitesApi = { - getAll: async (params?: CardRequisiteListParams): Promise => { - // Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz: - return { data: MOCK_CARD_REQUISITES, total: MOCK_CARD_REQUISITES.length, page: params?.page || 1, per_page: params?.per_page || 10 } - - const { data } = await apiClient.get('/card-requisites', { params }) - return data + getList: async (params: CardRequisiteListParams = {}, signal?: AbortSignal): Promise => { + const { page, limit, status, branch_id, user_id, card_type_id, region } = params; + const { data } = await apiClient.get("/card-rekwizit-orders", { + params: { + page, + limit, + status: status || undefined, + branch_id: branch_id || undefined, + user_id: user_id || undefined, + card_type_id: card_type_id || undefined, + region: region || undefined, + }, + signal, + }); + return data; }, - getById: async (id: string): Promise => { - // Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz: - const mock = MOCK_CARD_REQUISITES.find(r => r.id === id) - if (mock) return mock - - const { data } = await apiClient.get(`/card-requisites/${id}`) - return data + getById: async (id: number): Promise => { + const { data } = await apiClient.get(`/card-rekwizit-orders/${id}`); + return data; }, - create: async (payload: CreateCardRequisitePayload): Promise => { - const { data } = await apiClient.post('/card-requisites', buildFormData(payload), { - headers: { 'Content-Type': 'multipart/form-data' }, - }) - return data + create: async (payload: CardRequisitePayload): Promise => { + const { data } = await apiClient.post("/card-rekwizit-orders", payload); + return data; }, - update: async (id: string, payload: UpdateCardRequisitePayload): Promise => { - const { data } = await apiClient.post(`/card-requisites/${id}`, buildFormData(payload), { - headers: { 'Content-Type': 'multipart/form-data' }, - }) - return data + update: async (id: number, payload: CardRequisitePayload): Promise => { + const { data } = await apiClient.put(`/card-rekwizit-orders/${id}`, payload); + return data; }, - delete: async (id: string): Promise => { - await apiClient.delete(`/card-requisites/${id}`) + delete: async (id: number): Promise => { + await apiClient.delete(`/card-rekwizit-orders/${id}`); }, - - download: async (id: string): Promise => { - const { data } = await apiClient.get(`/card-requisites/${id}/download`, { - responseType: 'blob', - }) - return data - }, -} +}; diff --git a/src/features/cardRequisites/components/cardRequisiteForm.tsx b/src/features/cardRequisites/components/cardRequisiteForm.tsx index 73e595c..2e00c17 100644 --- a/src/features/cardRequisites/components/cardRequisiteForm.tsx +++ b/src/features/cardRequisites/components/cardRequisiteForm.tsx @@ -7,7 +7,9 @@ import { toast } from "sonner"; import { CreditCard, User, FileText } from "lucide-react"; import type { LucideIcon } from "lucide-react"; -import { FormInput } from "@/components/formInput"; +import { FormInput, type SelectOption } from "@/components/formInput"; +import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect"; +import { DocumentUpload } from "@/components/documentUpload"; import { FormActions } from "@/components/formActions"; import { StepBarCards, type StepCardItem } from "@/components/stepBarV2"; import { BentoGrid, BentoCard } from "@/components/bento"; @@ -15,6 +17,10 @@ import type { CardRequisite } from "../api/cardRequisitesApi"; import { useCreateCardRequisite, useUpdateCardRequisite } from "../hooks/useCardRequisites"; import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardRequisite.schema"; import type { CardRequisiteFormData } from "../schemas/cardRequisite.schema"; +import { useInfiniteCardTypes } from "@/features/cardTypes/hooks/useCardTypes"; +import { useInfiniteBranches } from "@/features/branches/hooks/useBranches"; +import { useInfiniteClients } from "@/features/clients/hooks/useClients"; +import { resolveLocalizedName } from "@/features/loanOrders/api/loanOrdersApi"; // ─── Types ──────────────────────────────────────────────────────────────────── @@ -36,17 +42,20 @@ function flattenErrors(errors: Record) // ─── Constants ──────────────────────────────────────────────────────────────── -const STATUS_OPTIONS = [ +const STATUS_OPTIONS: SelectOption[] = [ { value: "pending", label: "Garaşylýar" }, { value: "approved", label: "Tassyklanan" }, { value: "rejected", label: "Ret edilen" }, ]; -const CARD_TYPE_OPTIONS = [ - { value: "altyn_asyr", label: "Altyn Asyr" }, - { value: "visa", label: "Visa" }, - { value: "mastercard", label: "MasterCard" }, -]; +const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const; + +function getRegionOptions(t: TFunction): SelectOption[] { + return REGION_CODES.map((code) => ({ + value: code, + label: t(`cardRequisites.regions.${code}`, code), + })); +} const PASSPORT_SERIES_OPTIONS = [ { value: "I-MR", label: "I-MR" }, @@ -58,50 +67,12 @@ const PASSPORT_SERIES_OPTIONS = [ { value: "B", label: "B" }, ]; -const PROVINCE_OPTIONS = [ - { value: "1", label: "Aşgabat" }, - { value: "2", label: "Ahal" }, - { value: "3", label: "Balkan" }, - { value: "4", label: "Daşoguz" }, - { value: "5", label: "Lebap" }, - { value: "6", label: "Mary" }, -]; - -const BRANCH_OPTIONS: Record = { - "1": [ - { value: "11", label: "Köpetdag" }, - { value: "12", label: "Çandybil" }, - { value: "13", label: "Büzmeyin" }, - ], - "2": [ - { value: "21", label: "Änew" }, - { value: "22", label: "Tejen" }, - ], - "3": [ - { value: "31", label: "Balkanabat" }, - { value: "32", label: "Türkmenbaşy" }, - ], - "4": [ - { value: "41", label: "Daşoguz ş." }, - { value: "42", label: "Köneürgenç" }, - ], - "5": [ - { value: "51", label: "Türkmenabat" }, - { value: "52", label: "Hazar" }, - ], - "6": [ - { value: "61", label: "Mary ş." }, - { value: "62", label: "Ýolöten" }, - { value: "63", label: "Şatlyk" }, - ], -}; - -const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => { +const MONTH_OPTIONS: SelectOption[] = Array.from({ length: 12 }, (_, i) => { const val = String(i + 1).padStart(2, "0"); return { value: val, label: val }; }); -const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => { +const YEAR_OPTIONS: SelectOption[] = Array.from({ length: 20 }, (_, i) => { const year = String(new Date().getFullYear() + i); return { value: year, label: year }; }); @@ -109,24 +80,26 @@ const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => { function mapInitial(data: CardRequisite): CardRequisiteFormData { return { status: data.status ?? "pending", - note: data.note ?? "", - card_type: data.card_type ?? "", - card_number: data.card_number ?? "", - card_expiry_month: data.card_expiry_month ?? "", - card_expiry_year: data.card_expiry_year ?? "", - province_id: data.province_id ?? "", - branch_id: data.branch_id ?? "", - first_name: data.first_name ?? "", - last_name: data.last_name ?? "", - middle_name: data.middle_name ?? "", - birth_date: data.birth_date ?? "", + notes: data.notes ?? "", + region: data.region ?? "", + cardTypeId: data.cardType?.id != null ? String(data.cardType.id) : "", + branchId: data.branch?.id != null ? String(data.branch.id) : "", + userId: data.user?.id != null ? String(data.user.id) : "", + uniqueId: data.uniqueId ?? "", + cardNumber: data.cardNumber ?? "", + cardMonth: data.cardMonth ?? "", + cardYear: data.cardYear ?? "", + customerName: data.customerName ?? "", + customerSurname: data.customerSurname ?? "", + customerPatronicName: data.customerPatronicName ?? "", + bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "", phone: data.phone ?? "", - passport_series: data.passport_series ?? "", - passport_number: data.passport_number ?? "", - passport_page1: null, - passport_page2_3: null, - passport_page8_9: null, - passport_page32: null, + passportSerie: data.passportSerie ?? "", + passportId: data.passportId ?? "", + passportOne: data.passportOne ?? "", + passportTwo: data.passportTwo ?? "", + passportThree: data.passportThree ?? "", + passportFour: data.passportFour ?? "", }; } @@ -148,9 +121,9 @@ const STEPS: StepDef[] = [ titleKey: "Card", titleFallback: "Kart", subtitleKey: "cardRequisiteForm.steps.card.subtitle", - subtitleFallback: "Görnüş & lokasiýa", + subtitleFallback: "Görnüş & maglumatlar", icon: CreditCard, - validate: (form, mode) => validateStep(0, form, mode), + validate: (form) => validateStep(0, form), }, { id: "personal", @@ -159,7 +132,7 @@ const STEPS: StepDef[] = [ subtitleKey: "cardRequisiteForm.steps.personal.subtitle", subtitleFallback: "At & telefon", icon: User, - validate: (form, mode) => validateStep(1, form, mode), + validate: (form) => validateStep(1, form), }, { id: "passport", @@ -168,7 +141,7 @@ const STEPS: StepDef[] = [ subtitleKey: "cardRequisiteForm.steps.passport.subtitle", subtitleFallback: "Resminamalar", icon: FileText, - validate: (form, mode) => validateStep(2, form, mode), + validate: (form) => validateStep(2, form), }, ]; @@ -179,12 +152,58 @@ interface StepContentProps { errors: FlatErrors; set: (k: K, v: CardRequisiteFormData[K]) => void; t: TFunction; + initialData?: CardRequisite; } // ─── Step panels ────────────────────────────────────────────────────────────── -function StepCard({ form, errors, set, t }: StepContentProps) { - const branchOptions = BRANCH_OPTIONS[form.province_id] ?? []; +function StepCard({ form, errors, set, t, initialData }: StepContentProps) { + const [cardTypeSearch, setCardTypeSearch] = useState(""); + const [branchSearch, setBranchSearch] = useState(""); + const [clientSearch, setClientSearch] = useState(""); + + const cardTypeQuery = useInfiniteCardTypes(cardTypeSearch); + const branchQuery = useInfiniteBranches(branchSearch); + const clientQuery = useInfiniteClients(clientSearch); + + const regionOptions = useMemo(() => getRegionOptions(t), [t]); + + const cardTypeOptions: InfiniteSelectOption[] = useMemo(() => { + const opts: InfiniteSelectOption[] = (cardTypeQuery.data?.pages ?? []) + .flatMap((p) => p?.paymentCards ?? []) + .map((ct) => ({ value: String(ct.id), label: resolveLocalizedName(ct.title) || String(ct.id) })); + if (initialData?.cardType?.id && !opts.some((o) => o.value === String(initialData.cardType.id))) { + opts.unshift({ + value: String(initialData.cardType.id), + label: resolveLocalizedName(initialData.cardType.name) || String(initialData.cardType.id), + }); + } + return opts; + }, [cardTypeQuery, initialData]); + + const branchOptions: InfiniteSelectOption[] = useMemo(() => { + const langBranches = (branchQuery.data?.pages ?? []).flatMap((p) => p?.branches ?? []); + const opts: InfiniteSelectOption[] = langBranches + .filter((b) => (form.region ? b.region === form.region : true)) + .map((b) => ({ value: String(b.id), label: resolveLocalizedName(b.name) || String(b.id) })); + if (initialData?.branch?.id && !opts.some((o) => o.value === String(initialData.branch.id))) { + opts.unshift({ + value: String(initialData.branch.id), + label: resolveLocalizedName(initialData.branch.name) || String(initialData.branch.id), + }); + } + return opts; + }, [branchQuery, initialData, form.region]); + + const clientOptions: InfiniteSelectOption[] = useMemo(() => { + const opts: InfiniteSelectOption[] = (clientQuery.data?.pages ?? []) + .flatMap((p) => p?.users ?? []) + .map((u) => ({ value: String(u.id), label: u.name || u.username || String(u.id) })); + if (initialData?.user?.id && !opts.some((o) => o.value === String(initialData.user.id))) { + opts.unshift({ value: String(initialData.user.id), label: initialData.user.name || String(initialData.user.id) }); + } + return opts; + }, [clientQuery, initialData]); return (
@@ -192,103 +211,148 @@ function StepCard({ form, errors, set, t }: StepContentProps) { set("status", v)} options={STATUS_OPTIONS} - error={errors.status} placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} + error={errors.status} + /> + + + set("uniqueId", v)} + placeholder={t("cardRequisiteForm.placeholders.uniqueId") || "Unikal ID..."} + error={errors.uniqueId} + /> + + + + + + 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 + /> + + + set("cardNumber", v)} + placeholder="9800 0000 0000 0000" + error={errors.cardNumber} + /> + + + + + + set("cardMonth", v)} + options={MONTH_OPTIONS} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + error={errors.cardMonth} + /> + + + set("cardYear", v)} + options={YEAR_OPTIONS} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + error={errors.cardYear} + /> + + + + + + { + set("region", v); + set("branchId", ""); + }} + options={regionOptions} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + error={errors.region} + /> + + + 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 + /> + + + + + + 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 /> set("note", v)} + value={form.notes} + onChange={(v) => set("notes", v)} placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."} /> - - - - set("card_type", v)} - options={CARD_TYPE_OPTIONS} - placeholder="—" - error={errors.card_type} - /> - set("card_number", v)} - placeholder={t("Card number") || "Kart belgisi"} - error={errors.card_number} - /> - - - - set("card_expiry_month", v)} - options={MONTH_OPTIONS} - placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} - error={errors.card_expiry_month} - /> - set("card_expiry_year", v)} - options={YEAR_OPTIONS} - placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} - error={errors.card_expiry_year} - /> - - - - - - { - set("province_id", v); - set("branch_id", ""); - }} - options={PROVINCE_OPTIONS} - placeholder={t("Region") || "Aşgabat"} - error={errors.province_id} - /> - - - set("branch_id", v)} - options={branchOptions} - placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} - disabled={!form.province_id} - error={errors.branch_id} - /> - -
); } @@ -302,10 +366,10 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) { type="text" label={t("Name") || "Ady"} required - value={form.first_name} - onChange={(v) => set("first_name", v)} + value={form.customerName} + onChange={(v) => set("customerName", v)} placeholder={t("Name") || "Ady"} - error={errors.first_name} + error={errors.customerName} /> @@ -313,18 +377,18 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) { type="text" label={t("Surname") || "Familiýasy"} required - value={form.last_name} - onChange={(v) => set("last_name", v)} + value={form.customerSurname} + onChange={(v) => set("customerSurname", v)} placeholder={t("Surname") || "Familiýasy"} - error={errors.last_name} + error={errors.customerSurname} /> set("middle_name", v)} + value={form.customerPatronicName} + onChange={(v) => set("customerPatronicName", v)} placeholder={t("Patronic name") || "Atasynyň ady"} /> @@ -336,9 +400,9 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) { type="date" label={t("Date of birth") || "Doglan güni"} required - value={form.birth_date} - onChange={(v) => set("birth_date", v)} - error={errors.birth_date} + value={form.bornAt} + onChange={(v) => set("bornAt", v)} + error={errors.bornAt} /> @@ -357,27 +421,7 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) { ); } -function StepPassport({ - form, - errors, - set, - t, - mode, - initialData, -}: StepContentProps & { - mode: "create" | "edit"; - initialData?: CardRequisite; -}) { - const existingFiles = - mode === "edit" && initialData - ? [ - { url: initialData.passport_page1_url, label: t("Passport (page 1)") || "Pasport (sahypa 1)" }, - { url: initialData.passport_page2_3_url, label: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)" }, - { url: initialData.passport_page8_9_url, label: t("Passport (page 8-9)") || "Pasport (8-9 sahypa)" }, - { url: initialData.passport_page32_url, label: t("Passport (page 32)") || "Pasport (32-nji sahypa)" }, - ].filter((f): f is { url: string; label: string } => !!f.url) - : []; - +function StepPassport({ form, errors, set, t }: StepContentProps) { return (
@@ -386,11 +430,11 @@ function StepPassport({ type="searchable-select" label={t("Passport serie") || "Pasport seriýasy"} required - value={form.passport_series} - onChange={(v) => set("passport_series", v)} + value={form.passportSerie} + onChange={(v) => set("passportSerie", v)} options={PASSPORT_SERIES_OPTIONS} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} - error={errors.passport_series} + error={errors.passportSerie} /> @@ -398,77 +442,49 @@ function StepPassport({ type="text" label={t("Passport id") || "Pasport belgisi"} required - value={form.passport_number} - onChange={(v) => set("passport_number", v)} + value={form.passportId} + onChange={(v) => set("passportId", v)} placeholder={t("Passport id") || "Pasport belgisi"} - error={errors.passport_number} + error={errors.passportId} /> - {existingFiles.length > 0 && ( - - {existingFiles.map(({ url, label }) => ( - - - {t("loanOrderForm.fileLabels.viewFile") || "Faýly gör"} - - - ))} - - )} - - set("passport_page1", f)} - error={errors.passport_page1} + set("passportOne", v)} + error={errors.passportOne} + accept="image/*" /> - set("passport_page2_3", f)} - error={errors.passport_page2_3} + set("passportTwo", v)} + error={errors.passportTwo} + accept="image/*" /> - set("passport_page8_9", f)} - error={errors.passport_page8_9} + value={form.passportThree} + onChange={(v) => set("passportThree", v)} + error={errors.passportThree} + accept="image/*" /> - set("passport_page32", f)} - error={errors.passport_page32} + value={form.passportFour} + onChange={(v) => set("passportFour", v)} + error={errors.passportFour} + accept="image/*" /> @@ -483,7 +499,7 @@ export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps) const navigate = useNavigate(); const createMutation = useCreateCardRequisite(); - const updateMutation = useUpdateCardRequisite(initialData?.id ?? ""); + const updateMutation = useUpdateCardRequisite(initialData?.id ?? 0); const isPending = createMutation.isPending || updateMutation.isPending; const { @@ -534,7 +550,7 @@ export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps) return { ...fromRHF, ...allSubmittedErrors }; }, [rhfErrors, allSubmittedErrors]); - const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t]); + const stepProps = useMemo(() => ({ form, errors, set, t, initialData }), [form, errors, set, t, initialData]); // ── Navigation ───────────────────────────────────────────────────────────── @@ -647,7 +663,7 @@ export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps) {/* Step content */} {currentStep === 0 && } {currentStep === 1 && } - {currentStep === 2 && } + {currentStep === 2 && } {/* Actions */} [...cardRequisiteKeys.all, "list"] as const, + list: (params: CardRequisiteListParams) => [...cardRequisiteKeys.lists(), params] as const, + details: () => [...cardRequisiteKeys.all, "detail"] as const, + detail: (id: number) => [...cardRequisiteKeys.details(), id] as const, +}; // ─── List ───────────────────────────────────────────────────────────────────── -export function useCardRequisites(params?: CardRequisiteListParams) { +export function useCardRequisites(params: CardRequisiteListParams = {}) { return useQuery({ - queryKey: [QUERY_KEY, params], - queryFn: () => cardRequisitesApi.getAll(params), - }) + queryKey: cardRequisiteKeys.list(params), + queryFn: ({ signal }) => cardRequisitesApi.getList(params, signal), + placeholderData: (prev) => prev, + }); } // ─── Single ─────────────────────────────────────────────────────────────────── -export function useCardRequisite(id: string) { +export function useCardRequisite(id: number) { return useQuery({ - queryKey: [QUERY_KEY, id], + queryKey: cardRequisiteKeys.detail(id), queryFn: () => cardRequisitesApi.getById(id), enabled: !!id, - }) + }); } // ─── Create ─────────────────────────────────────────────────────────────────── export function useCreateCardRequisite() { - const queryClient = useQueryClient() - const { t } = useTranslation() + const queryClient = useQueryClient(); + const { t } = useTranslation(); return useMutation({ - mutationFn: (payload: CreateCardRequisitePayload) => cardRequisitesApi.create(payload), + mutationFn: (payload: CardRequisitePayload) => cardRequisitesApi.create(payload), onSuccess: () => { - queryClient.invalidateQueries({ queryKey: [QUERY_KEY] }) - toast.success(t('Card requisite created successfully', 'Kart rekwiziti üstünlikli döredildi')) + queryClient.invalidateQueries({ queryKey: cardRequisiteKeys.lists() }); + toast.success(t("cardRequisites.createSuccess", "Kart rekwiziti üstünlikli döredildi")); }, - }) + }); } // ─── Update ─────────────────────────────────────────────────────────────────── -export function useUpdateCardRequisite(id: string) { - const queryClient = useQueryClient() - const { t } = useTranslation() +export function useUpdateCardRequisite(id: number) { + const queryClient = useQueryClient(); + const { t } = useTranslation(); return useMutation({ - mutationFn: (payload: UpdateCardRequisitePayload) => cardRequisitesApi.update(id, payload), - onSuccess: () => { - queryClient.invalidateQueries({ queryKey: [QUERY_KEY] }) - toast.success(t('Card requisite updated successfully', 'Kart rekwiziti üstünlikli üýtgedildi')) + mutationFn: (payload: CardRequisitePayload) => cardRequisitesApi.update(id, payload), + onSuccess: (updated) => { + queryClient.invalidateQueries({ queryKey: cardRequisiteKeys.lists() }); + queryClient.setQueryData(cardRequisiteKeys.detail(id), updated); + toast.success(t("cardRequisites.updateSuccess", "Kart rekwiziti üstünlikli üýtgedildi")); }, - }) + }); } // ─── Delete ─────────────────────────────────────────────────────────────────── export function useDeleteCardRequisite() { - const queryClient = useQueryClient() - const { t } = useTranslation() + const queryClient = useQueryClient(); + const { t } = useTranslation(); return useMutation({ - mutationFn: (id: string) => cardRequisitesApi.delete(id), + mutationFn: (id: number) => cardRequisitesApi.delete(id), onSuccess: () => { - queryClient.invalidateQueries({ queryKey: [QUERY_KEY] }) - toast.success(t('Card requisite deleted successfully', 'Kart rekwiziti üstünlikli öçürildi')) + queryClient.invalidateQueries({ queryKey: cardRequisiteKeys.lists() }); + toast.success(t("cardRequisites.deleteSuccess", "Kart rekwiziti üstünlikli öçürildi")); }, - }) -} - -// ─── Download ───────────────────────────────────────────────────────────────── - -export function useDownloadCardRequisite() { - const { t } = useTranslation() - - return useMutation({ - mutationFn: async (id: string) => { - const blob = await cardRequisitesApi.download(id) - const url = URL.createObjectURL(blob) - const a = document.createElement('a') - a.href = url - a.download = `card-requisite-${id}.pdf` - a.click() - URL.revokeObjectURL(url) - }, - onSuccess: () => { - toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi')) - }, - }) + }); } diff --git a/src/features/cardRequisites/schemas/cardRequisite.schema.ts b/src/features/cardRequisites/schemas/cardRequisite.schema.ts index fbfb3bd..523c0f1 100644 --- a/src/features/cardRequisites/schemas/cardRequisite.schema.ts +++ b/src/features/cardRequisites/schemas/cardRequisite.schema.ts @@ -1,23 +1,24 @@ import { z } from "zod"; import i18next from "i18next"; -import type { CardRequisiteStatus, CreateCardRequisitePayload } from "../api/cardRequisitesApi"; +import type { CardRequisitePayload } from "../api/cardRequisitesApi"; -const fileRequired = z.custom((val) => val instanceof File, "validation.requiredFile"); const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"]; export const cardRequisiteFormSchema = z.object({ status: z.string().min(1, "validation.required"), - note: z.string().optional(), - card_type: z.string().min(1, "validation.required"), - card_number: z.string().min(1, "validation.required"), - card_expiry_month: z.string().min(1, "validation.required"), - card_expiry_year: z.string().min(1, "validation.required"), - province_id: z.string().min(1, "validation.required"), - branch_id: z.string().min(1, "validation.required"), - first_name: z.string().min(1, "validation.required"), - last_name: z.string().min(1, "validation.required"), - middle_name: z.string().optional(), - birth_date: z.string().min(1, "validation.required"), + notes: z.string().optional(), + region: z.string().min(1, "validation.required"), + cardTypeId: z.string().min(1, "validation.required"), + branchId: z.string().min(1, "validation.required"), + userId: z.string().min(1, "validation.required"), + uniqueId: z.string().optional(), + cardNumber: z.string().optional(), + cardMonth: z.string().optional(), + cardYear: z.string().optional(), + customerName: z.string().min(1, "validation.required"), + customerSurname: z.string().min(1, "validation.required"), + customerPatronicName: z.string().optional(), + bornAt: z.string().min(1, "validation.required"), phone: z .string() .min(1, "validation.required") @@ -36,12 +37,12 @@ export const cardRequisiteFormSchema = z.object({ }, { message: "validation.invalidPhonePrefix" }, ), - passport_series: z.string().min(1, "validation.required"), - passport_number: z.string().min(1, "validation.required"), - passport_page1: z.custom().nullable(), - passport_page2_3: z.custom().nullable(), - passport_page8_9: z.custom().nullable(), - passport_page32: z.custom().nullable(), + passportSerie: z.string().min(1, "validation.required"), + passportId: z.string().min(1, "validation.required"), + passportOne: z.string().optional(), + passportTwo: z.string().optional(), + passportThree: z.string().optional(), + passportFour: z.string().optional(), }); export type CardRequisiteFormData = z.infer; @@ -49,26 +50,30 @@ export type CardRequisiteFormData = z.infer; export const stepSchemas: Record>> = { 0: cardRequisiteFormSchema.pick({ status: true, - card_type: true, - card_number: true, - card_expiry_month: true, - card_expiry_year: true, - province_id: true, - branch_id: true, + region: true, + cardTypeId: true, + branchId: true, + userId: true, + uniqueId: true, + cardNumber: true, + cardMonth: true, + cardYear: true, + notes: true, }), 1: cardRequisiteFormSchema.pick({ - first_name: true, - last_name: true, - birth_date: true, + customerName: true, + customerSurname: true, + customerPatronicName: true, + bornAt: true, phone: true, }), - 2: z.object({ - passport_series: z.string().min(1, "validation.required"), - passport_number: z.string().min(1, "validation.required"), - passport_page1: fileRequired, - passport_page2_3: fileRequired, - passport_page8_9: fileRequired, - passport_page32: fileRequired, + 2: cardRequisiteFormSchema.pick({ + passportSerie: true, + passportId: true, + passportOne: true, + passportTwo: true, + passportThree: true, + passportFour: true, }), }; @@ -76,26 +81,7 @@ function translateMsg(msg: string): string { return msg.startsWith("validation.") ? i18next.t(msg, msg) : msg; } -export function validateStep( - stepIndex: number, - form: CardRequisiteFormData, - mode: "create" | "edit", -): Partial> { - 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> = {}; - for (const issue of result.error.issues) { - const key = issue.path[0] as keyof CardRequisiteFormData; - if (!errors[key]) errors[key] = translateMsg(issue.message); - } - return errors; - } - +export function validateStep(stepIndex: number, form: CardRequisiteFormData): Partial> { const schema = stepSchemas[stepIndex]; if (!schema) return {}; const result = schema.safeParse(form); @@ -110,46 +96,50 @@ export function validateStep( export const DEFAULT_FORM_VALUES: CardRequisiteFormData = { status: "pending", - note: "", - card_type: "", - card_number: "", - card_expiry_month: "", - card_expiry_year: "", - province_id: "", - branch_id: "", - first_name: "", - last_name: "", - middle_name: "", - birth_date: "", + notes: "", + region: "", + cardTypeId: "", + branchId: "", + userId: "", + uniqueId: "", + cardNumber: "", + cardMonth: "", + cardYear: "", + customerName: "", + customerSurname: "", + customerPatronicName: "", + bornAt: "", phone: "", - passport_series: "", - passport_number: "", - passport_page1: null, - passport_page2_3: null, - passport_page8_9: null, - passport_page32: null, + passportSerie: "", + passportId: "", + passportOne: "", + passportTwo: "", + passportThree: "", + passportFour: "", }; -export function buildPayload(data: CardRequisiteFormData): CreateCardRequisitePayload { +export function buildPayload(data: CardRequisiteFormData): CardRequisitePayload { return { - status: data.status as CardRequisiteStatus, - note: data.note || undefined, - card_type: data.card_type, - card_number: data.card_number, - card_expiry_month: data.card_expiry_month, - card_expiry_year: data.card_expiry_year, - province_id: data.province_id, - branch_id: data.branch_id, - first_name: data.first_name, - last_name: data.last_name, - middle_name: data.middle_name || undefined, - birth_date: data.birth_date, + status: data.status, + notes: data.notes || "", + region: data.region, + cardTypeId: Number(data.cardTypeId), + branchId: Number(data.branchId), + userId: Number(data.userId), + customerName: data.customerName, + customerSurname: data.customerSurname, + customerPatronicName: data.customerPatronicName || "", + bornAt: data.bornAt, phone: data.phone, - passport_series: data.passport_series, - passport_number: data.passport_number, - ...(data.passport_page1 && { passport_page1: data.passport_page1 }), - ...(data.passport_page2_3 && { passport_page2_3: data.passport_page2_3 }), - ...(data.passport_page8_9 && { passport_page8_9: data.passport_page8_9 }), - ...(data.passport_page32 && { passport_page32: data.passport_page32 }), + passportSerie: data.passportSerie, + passportId: data.passportId, + passportOne: data.passportOne || "", + passportTwo: data.passportTwo || "", + passportThree: data.passportThree || "", + passportFour: data.passportFour || "", + uniqueId: data.uniqueId || "", + cardNumber: data.cardNumber || "", + cardMonth: data.cardMonth || "", + cardYear: data.cardYear || "", }; } diff --git a/src/features/loanOrderMobiles/api/loanOrderMobilesApi.ts b/src/features/loanOrderMobiles/api/loanOrderMobilesApi.ts index 808a171..07be485 100644 --- a/src/features/loanOrderMobiles/api/loanOrderMobilesApi.ts +++ b/src/features/loanOrderMobiles/api/loanOrderMobilesApi.ts @@ -1,498 +1,84 @@ import apiClient from "@/lib/api/client"; -import type { StatusValue } from "@/constants"; +import { + mapBackendToUI, + getLoanOrderById, + createLoanOrder, + updateLoanOrder, + patchLoanOrder, + deleteLoanOrder, + type LoanOrder, + type LoanOrderStatus, + type LoanOrderUser, + type LoanOrderPayload, + type LoanOrdersParams, + type LoanOrdersResponse, + type BackendLoanOrder, + type LoanOrdersListResponse, +} from "@/features/loanOrders/api/loanOrdersApi"; -// ─── Types ───────────────────────────────────────────────────────────────────── +// ─── Type Aliases (Seamless backwards compatibility & domain clarity) ──────── -export type LoanOrderMobileStatus = StatusValue; +export type { LoanOrderStatus, LoanOrder, LoanOrderUser, LoanOrderPayload, LoanOrdersParams, LoanOrdersResponse }; -export interface LoanOrderMobile { - id: string; - loanType: string; - createdAt: string; - region: string; - branch: string; - branchId?: number | string; - loanTypeId?: number | string; - workCityId?: number | string; - createdById?: number | string; - firstName: string; - lastName: string; - phone: string; - status: LoanOrderMobileStatus; - createdBy?: string; - - // ── Detail fields ───────────────────────────────────────────────────────── - patronicName?: string | null; - education?: string | null; - marriageStatus?: string | null; - dateOfBirth?: string | null; - residence?: string | null; - currentResidence?: string | null; - - // Passport - passportSerie?: string | null; - passportNumber?: string | null; - passportDateOfIssue?: string | null; - passportGivenBy?: string | null; - bornPlace?: string | null; - passportPage1Url?: string | null; - passportPage23Url?: string | null; - passportPage89Url?: string | null; - passportPage32Url?: string | null; - - // Contact - email?: string | null; - phoneAdditional?: string | null; - homePhone?: string | null; - - // Employment - workCompany?: string | null; - workHrPhone?: string | null; - workRegion?: string | null; - workProvince?: string | null; - position?: string | null; - salary?: number | null; - workStartedAt?: string | null; - - // New fields - note?: string | null; - loanAmount?: number | null; - loanHistory?: string | null; - - // Card (Zähmet haky) - cardNumber?: string | null; - cardName?: string | null; - cardExpMonth?: string | null; - cardExpYear?: string | null; - - // Guarantor (Zamun) - guarantor1Name?: string | null; - guarantor1Surname?: string | null; - guarantor1Patronic?: string | null; - guarantor1PassportSerie?: string | null; - guarantor1PassportNumber?: string | null; - guarantor1CardNumber?: string | null; - guarantor1CardName?: string | null; - guarantor1CardExpMonth?: string | null; - guarantor1CardExpYear?: string | null; - guarantor1Salary?: number | null; -} - -export interface LoanOrderMobilePayload { - status: string; - loanType: string; - region: string; - branch: string; - firstName: string; - lastName: string; - patronicName?: string; - education: string; - marriageStatus: string; - dateOfBirth: string; - residence: string; - currentResidence?: string; - passportSerie: string; - passportNumber: string; - passportDateOfIssue: string; - passportGivenBy: string; - bornPlace?: string; - email?: string; - phone: string; - phoneAdditional?: string; - homePhone?: string; - workCompany: string; - workHrPhone?: string; - workRegion?: string; - workProvince?: string; - position: string; - salary: number; - workStartedAt: string; - - note?: string; - loanAmount?: number; - loanHistory?: string; - - cardNumber?: string; - cardName?: string; - cardExpMonth?: string; - cardExpYear?: string; - - guarantor1Name?: string; - guarantor1Surname?: string; - guarantor1Patronic?: string; - guarantor1PassportSerie?: string; - guarantor1PassportNumber?: string; - guarantor1CardNumber?: string; - guarantor1CardName?: string; - guarantor1CardExpMonth?: string; - guarantor1CardExpYear?: string; - guarantor1Salary?: number; -} - -export interface LoanOrderMobileListParams { - search?: string; - region?: string; - status?: LoanOrderMobileStatus; - branch?: string; - archived?: string; - page?: number; - perPage?: number; -} - -export interface PaginatedResponse { +export type LoanOrderMobileStatus = LoanOrderStatus; +export type LoanOrderMobile = LoanOrder; +export type LoanOrderMobileUser = LoanOrderUser; +export type LoanOrderMobilePayload = LoanOrderPayload; +export type LoanOrderMobileListParams = LoanOrdersParams; +export type LoanOrderMobilesResponse = LoanOrdersResponse; +export type PaginatedResponse = { data: T[]; total: number; + page?: number; + perPage?: number; +}; +export type BackendLoanOrderMobile = BackendLoanOrder; + +// ─── Shared CRUD API Functions (Re-exported from loanOrdersApi) ─────────────── + +export const getLoanOrderMobileById = getLoanOrderById; +export const updateLoanOrderMobile = updateLoanOrder; +export const patchLoanOrderMobile = patchLoanOrder; +export const deleteLoanOrderMobile = deleteLoanOrder; + +export async function createLoanOrderMobile(payload: LoanOrderPayload): Promise { + return createLoanOrder({ ...payload, source: payload.source ?? "mobile" }); } -// ─── Mock Data ───────────────────────────────────────────────────────────────── +// ─── Mobile-specific List API ────────────────────────────────────────────────── -const MOCK_DATA: LoanOrderMobile[] = [ - { - id: "LOM-0001", - loanType: "Sarp ediş karzy", - createdAt: "2025-01-15 09:42", - region: "Aşgabat", - branch: "Merkezi şahamça", - branchId: 1, - loanTypeId: 1, - workCityId: 1, - createdById: "U-1001", - firstName: "Oraz", - lastName: "Annaýew", - phone: "+99361123456", - status: "pending", - note: "Müşderi dokumentleri tassyklamady", - loanAmount: 15000, - loanHistory: "positive", - patronicName: "Myradowiç", - education: "high", - marriageStatus: "MARRIED", - dateOfBirth: "1992-04-18", - residence: "Aşgabat, Bitarap Türkmenistan şaýoly, 15", - currentResidence: "Aşgabat, Garaşsyzlyk köçesi, 5", - passportSerie: "I-AŞ", - passportNumber: "123456", - passportDateOfIssue: "2015-03-10", - passportGivenBy: "Aşgabat şäheriniň Içeri işler müdirligi", - bornPlace: "Aşgabat şäheri", - email: "oraz.annayew@email.com", - phoneAdditional: "+99365443322", - workCompany: "Türkmennebit", - workHrPhone: "+99312456789", - workRegion: "Aşgabat", - workProvince: "Büzmeýin etraby", - position: "Inžener", - salary: 2500, - workStartedAt: "2018-06-01", - cardNumber: "4111111111111111", - cardName: "ORAZ ANNAÝEW", - cardExpMonth: "12", - cardExpYear: "2027", - guarantor1Name: "Berdi", - guarantor1Surname: "Berdiýew", - guarantor1Patronic: "Annagulyýewiç", - guarantor1PassportSerie: "II-MR", - guarantor1PassportNumber: "654321", - guarantor1CardNumber: "4222222222222222", - guarantor1CardName: "BERDI BERDIÝEW", - guarantor1CardExpMonth: "06", - guarantor1CardExpYear: "2026", - guarantor1Salary: 3000, - }, - { - id: "LOM-0002", - loanType: "Awtoulag karzy", - createdAt: "2025-01-18 11:05", - region: "Ahal", - branch: "Änew şahamçasy", - branchId: 2, - loanTypeId: 2, - workCityId: 2, - createdById: "U-1002", - firstName: "Merjen", - lastName: "Hudaýewa", - phone: "+99362234567", - status: "approved", - loanAmount: 30000, - loanHistory: "new", - patronicName: "Myratowna", - education: "masters", - marriageStatus: "SINGLE", - dateOfBirth: "1995-11-20", - residence: "Änew şäher, Garaşsyzlyk köçesi, 10", - passportSerie: "I-MR", - passportNumber: "789012", - passportDateOfIssue: "2018-07-22", - passportGivenBy: "Ahal welaýatynyň Içeri işler müdirligi", - bornPlace: "Änew şäheri", - email: "merjen.hudayewa@email.com", - workCompany: "Änew etrap hasap bölümi", - position: "Hasapçy", - salary: 1800, - workStartedAt: "2019-03-15", - cardNumber: "4333333333333333", - cardName: "MERJEN HUDAÝEWA", - cardExpMonth: "09", - cardExpYear: "2028", - guarantor1Name: "Merdan", - guarantor1Surname: "Merdanow", - guarantor1PassportSerie: "I-AH", - guarantor1PassportNumber: "345678", - guarantor1CardNumber: "4444444444444444", - guarantor1CardName: "MERDAN MERDANOW", - guarantor1CardExpMonth: "03", - guarantor1CardExpYear: "2025", - guarantor1Salary: 2200, - }, - { - id: "LOM-0003", - loanType: "Ipoteka karzy", - createdAt: "2025-01-20 14:30", - region: "Balkan", - branch: "Balkanabat şahamçasy", - branchId: 3, - loanTypeId: 3, - workCityId: 7, - createdById: "U-1003", - firstName: "Serdar", - lastName: "Durdyýew", - phone: "+99363345678", - status: "pending", - loanAmount: 50000, - loanHistory: "positive", - patronicName: "Annagylyjowiç", - education: "high", - marriageStatus: "MARRIED", - dateOfBirth: "1988-07-12", - residence: "Balkanabat, Magtymguly köçesi, 25", - passportSerie: "II-AH", - passportNumber: "456123", - passportDateOfIssue: "2016-05-18", - passportGivenBy: "Balkan welaýatynyň Içeri işler müdirligi", - email: "serdar.durdyyew@email.com", - workCompany: "Balkan nebit", - position: "Operator", - salary: 3200, - workStartedAt: "2015-09-01", - cardNumber: "4555555555555555", - cardName: "SERDAR DURDYÝEW", - cardExpMonth: "04", - cardExpYear: "2029", - guarantor1Name: "Döwran", - guarantor1Surname: "Döwranow", - guarantor1PassportSerie: "I-LB", - guarantor1PassportNumber: "789456", - guarantor1CardNumber: "4666666666666666", - guarantor1CardName: "DÖWRAN DÖWRANOW", - guarantor1CardExpMonth: "11", - guarantor1CardExpYear: "2027", - guarantor1Salary: 3500, - }, - { - id: "LOM-0004", - loanType: "Telekeçilik karzy", - createdAt: "2025-01-22 08:15", - region: "Lebap", - branch: "Türkmenabat şahamçasy", - firstName: "Aýna", - lastName: "Meredowa", - phone: "+99365456789", - status: "rejected", - loanAmount: 25000, - patronicName: "Begenjowna", - education: "high", - marriageStatus: "DIVORCED", - dateOfBirth: "1991-02-28", - residence: "Türkmenabat, Lebap köçesi, 8", - passportSerie: "II-LB", - passportNumber: "321654", - passportDateOfIssue: "2017-11-05", - passportGivenBy: "Lebap welaýatynyň Içeri işler müdirligi", - workCompany: "Hususy telekeçi", - position: "Telekeçi", - salary: 4000, - workStartedAt: "2020-01-10", - cardNumber: "4777777777777777", - cardName: "AÝNA MEREDOWA", - cardExpMonth: "07", - cardExpYear: "2026", - }, - { - id: "LOM-0005", - loanType: "Sarp ediş karzy", - createdAt: "2025-01-25 16:00", - region: "Mary", - branch: "Mary-1 şahamçasy", - firstName: "Begmyrat", - lastName: "Oraz", - phone: "+99366567890", - status: "pending", - loanAmount: 8000, - loanHistory: "new", - patronicName: "Annageldiwiç", - education: "middle", - marriageStatus: "SINGLE", - dateOfBirth: "2000-08-15", - residence: "Mary şäher, Saýat köçesi, 3", - passportSerie: "I-BN", - passportNumber: "567890", - passportDateOfIssue: "2020-01-20", - passportGivenBy: "Mary welaýatynyň Içeri işler müdirligi", - workCompany: "Mary gurluşyk", - position: "Işçi", - salary: 1200, - workStartedAt: "2022-06-01", - }, - { - id: "LOM-0006", - loanType: "Bilim karzy", - createdAt: "2025-01-28 10:20", - region: "Daşoguz", - branch: "Daşoguz şahamçasy", - firstName: "Gülälek", - lastName: "Saparowa", - phone: "+99361678901", - status: "approved", - loanAmount: 12000, - patronicName: "Mämmedowna", - education: "phd", - marriageStatus: "MARRIED", - dateOfBirth: "1985-12-03", - residence: "Daşoguz, Gurbansoltan eje köçesi, 12", - passportSerie: "II-BN", - passportNumber: "901234", - passportDateOfIssue: "2014-08-30", - passportGivenBy: "Daşoguz welaýatynyň Içeri işler müdirligi", - email: "gulalek.saparowa@email.com", - workCompany: "Daşoguz uniwersiteti", - position: "Mugallym", - salary: 2000, - workStartedAt: "2016-09-01", - cardNumber: "4888888888888888", - cardName: "GÜLÄLEK SAPAROWA", - cardExpMonth: "02", - cardExpYear: "2028", - guarantor1Name: "Maksat", - guarantor1Surname: "Saparow", - guarantor1PassportSerie: "I-DZ", - guarantor1PassportNumber: "112233", - guarantor1CardNumber: "4999999999999999", - guarantor1CardName: "MAKSAT SAPAROW", - guarantor1CardExpMonth: "10", - guarantor1CardExpYear: "2027", - guarantor1Salary: 2500, - }, - { - id: "LOM-0007", - loanType: "Awtoulag karzy", - createdAt: "2025-02-01 13:45", - region: "Aşgabat", - branch: "Garaşsyzlyk şahamçasy", - firstName: "Myrat", - lastName: "Ataýew", - phone: "+99362789012", - status: "pending", - loanAmount: 35000, - patronicName: "Batyrowiç", - education: "high", - marriageStatus: "MARRIED", - dateOfBirth: "1989-09-22", - residence: "Aşgabat, Çandybil köçesi, 45", - passportSerie: "II-DZ", - passportNumber: "334455", - passportDateOfIssue: "2015-12-12", - passportGivenBy: "Aşgabat şäheriniň Içeri işler müdirligi", - workCompany: "Türkmenhowaýollar", - position: "Sürüji", - salary: 2800, - workStartedAt: "2017-04-01", - cardNumber: "4111111111112222", - cardName: "MYRAT ATAÝEW", - cardExpMonth: "08", - cardExpYear: "2027", - }, -]; +export async function fetchLoanOrderMobiles(params: LoanOrdersParams = {}, signal?: AbortSignal): Promise { + const { page, perPage, limit, search, region, status, branch, branch_id, createdById, userId, user_id, archived } = params; + const branchId = branch || branch_id; + const uid = createdById || userId || user_id; -let mockStore = [...MOCK_DATA]; -let nextId = 8; - -const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms)); - -function applyMockFilters(params: LoanOrderMobileListParams): PaginatedResponse { - const page = params.page ?? 1; - const perPage = params.perPage ?? 25; - - let result = [...mockStore]; - - if (params.search) { - const q = params.search.toLowerCase(); - result = result.filter( - (r) => - r.firstName.toLowerCase().includes(q) || - r.lastName.toLowerCase().includes(q) || - r.phone.includes(q) || - r.id.toLowerCase().includes(q), - ); - } - if (params.region) result = result.filter((r) => r.region === params.region); - if (params.status) result = result.filter((r) => r.status === params.status); - if (params.branch) result = result.filter((r) => r.branch === params.branch); - - const total = result.length; - const start = (page - 1) * perPage; - - return { data: result.slice(start, start + perPage), total }; -} - -// ─── API Functions ───────────────────────────────────────────────────────────── - -export async function fetchLoanOrderMobiles(params: LoanOrderMobileListParams): Promise> { - if (true) { - await delay(500); - return applyMockFilters(params); - } - const { data } = await apiClient.get>("/loan-order-mobiles", { params }); - return data; -} - -export async function deleteLoanOrderMobile(id: string): Promise { - await delay(300); - mockStore = mockStore.filter((r) => r.id !== id); -} - -export async function getLoanOrderMobileById(id: string): Promise { - 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 { - await delay(500); - const newOrder: LoanOrderMobile = { - ...payload, - id: `LOM-${String(nextId++).padStart(4, "0")}`, - createdAt: new Date().toISOString().slice(0, 16).replace("T", " "), - status: payload.status as LoanOrderMobileStatus, + const { data } = await apiClient.get("/loan-orders/mobile", { + params: { + page: page ?? 1, + limit: perPage ?? limit ?? 25, + search: search || undefined, + region: region || undefined, + status: status || undefined, + branch_id: branchId || undefined, + user_id: uid || undefined, + archived: archived || undefined, + }, + signal, + }); + const orders = (data.loanOrders ?? []).map(mapBackendToUI); + return { + data: orders, + total: data.count ?? orders.length, + page: page ?? 1, + perPage: perPage ?? limit ?? 25, }; - mockStore = [newOrder, ...mockStore]; - return newOrder; } -export async function updateLoanOrderMobile(id: string, payload: Partial): Promise { - await delay(500); - const idx = mockStore.findIndex((r) => r.id === id); - if (idx === -1) throw new Error("Not found"); - const updated = { ...mockStore[idx], ...payload } as LoanOrderMobile; - mockStore = mockStore.map((r) => (r.id === id ? updated : r)); - return updated; -} - -// ─── Branch options by region ───────────────────────────────────────────────── +// ─── Branch options by region (Fallback) ────────────────────────────────────── export const BRANCHES_BY_REGION_MOBILE: Record = { Aşgabat: [ - { value: "Merkezi şahamça", label: "Merkezi şahamça" }, + { value: "Merkezi şahamça", label: "Merkezi şahamçaaaaaaaaaaaaaaaaaa" }, { value: "Garaşsyzlyk şahamçasy", label: "Garaşsyzlyk şahamçasy" }, { value: "Bitarap şahamça", label: "Bitarap şahamça" }, { value: "Aşgabat-1 şahamçasy", label: "Aşgabat-1 şahamçasy" }, diff --git a/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx b/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx index 5aedbbf..74383e3 100644 --- a/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx +++ b/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx @@ -4,32 +4,46 @@ import { useTranslation } from "react-i18next"; import type { TFunction } from "i18next"; import { useForm } from "react-hook-form"; import { toast } from "sonner"; -import { FileText, User, Phone, CreditCard, Upload } from "lucide-react"; +import { CircleDot, Wallet, MapPin, User, CreditCard, FileText, Phone, Briefcase, ShieldCheck } from "lucide-react"; import type { LucideIcon } from "lucide-react"; -import { FormInput } from "@/components/formInput"; + +import { FormInput, type SelectOption } from "@/components/formInput"; +import { DocumentUpload } from "@/components/documentUpload"; +import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect"; import { FormActions } from "@/components/formActions"; import { StepBarCards, type StepCardItem } from "@/components/stepBarV2"; import { BentoGrid, BentoCard } from "@/components/bento"; + import { useCreateLoanOrderMobile, useUpdateLoanOrderMobile } from "@/features/loanOrderMobiles/hooks/useLoanOrderMobiles"; import type { LoanOrderMobile } from "@/features/loanOrderMobiles/api/loanOrderMobilesApi"; -import { BRANCHES_BY_REGION_MOBILE } from "@/features/loanOrderMobiles/api/loanOrderMobilesApi"; -import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "@/features/loanOrderMobiles/schemas/loanOrderMobile.schema"; -import type { LoanOrderMobileFormData } from "@/features/loanOrderMobiles/schemas/loanOrderMobile.schema"; +import { resolveLocalizedName } from "@/features/loanOrders/api/loanOrdersApi"; +import { + validateStep, + DEFAULT_FORM_VALUES, + buildPayload, + type LoanOrderMobileFormData, +} from "@/features/loanOrderMobiles/schemas/loanOrderMobile.schema"; + +import { useInfiniteBranches, useInfiniteProvinces } from "@/features/branches/hooks/useBranches"; +import { useInfiniteLoanTypes } from "@/features/loanTypes/hooks/useLoanTypes"; +import { useInfiniteClients } from "@/features/clients/hooks/useClients"; +import { useGetRequiredDocuments } from "@/features/requiredDocuments/hooks/useRequiredDocuments"; + import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants"; +import { formatFromApiDate, formatFromApiPhone } from "@/lib/utils"; // ─── Static options ─────────────────────────────────────────────────────────── -const REGION_OPTIONS = [ - { value: "Aşgabat", label: "Aşgabat" }, - { value: "Ahal", label: "Ahal" }, - { value: "Balkan", label: "Balkan" }, - { value: "Daşoguz", label: "Daşoguz" }, - { value: "Lebap", label: "Lebap" }, - { value: "Mary", label: "Mary" }, - { value: "Arkadag", label: "Arkadag" }, -]; +const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const; -const EDUCATION_OPTIONS = [ +function getRegionOptions(t: TFunction): SelectOption[] { + return REGION_CODES.map((code) => ({ + value: code, + label: t(`loanOrders.regions.${code}`, code), + })); +} + +const EDUCATION_OPTIONS: SelectOption[] = [ { value: "high", label: "Ýokary bilim" }, { value: "unfinished_high", label: "Gutarylmadyk ýokary bilim" }, { value: "masters", label: "Magistr" }, @@ -39,7 +53,7 @@ const EDUCATION_OPTIONS = [ { value: "school_dropout", label: "Gutarylmadyk orta bilim" }, ]; -const MARRIAGE_OPTIONS = [ +const MARRIAGE_OPTIONS: SelectOption[] = [ { value: "MARRIED", label: "Öýlenen / Durmuşa çykan" }, { value: "SINGLE", label: "Öýlenmedik / Durmuşa çykmadyk" }, { value: "DIVORCED", label: "Aýrylşan" }, @@ -47,20 +61,12 @@ const MARRIAGE_OPTIONS = [ { value: "LEGAL", label: "Raýat nika" }, ]; -const LOAN_TYPE_OPTIONS = [ - { value: "consumer", label: "Sarp ediş karzy" }, - { value: "mortgage", label: "Ipoteka" }, - { value: "car", label: "Awtoulag karzy" }, - { value: "student", label: "Talyplar üçin" }, - { value: "business", label: "Işewürlik karzy" }, -]; - -const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => ({ +const MONTH_OPTIONS: SelectOption[] = Array.from({ length: 12 }, (_, i) => ({ value: String(i + 1).padStart(2, "0"), label: String(i + 1).padStart(2, "0"), })); -const YEAR_OPTIONS = Array.from({ length: 15 }, (_, i) => ({ +const YEAR_OPTIONS: SelectOption[] = Array.from({ length: 15 }, (_, i) => ({ value: String(new Date().getFullYear() + i), label: String(new Date().getFullYear() + i), })); @@ -92,50 +98,95 @@ interface StepDef { const STEPS: StepDef[] = [ { - id: "loan", - titleKey: "loanOrderMobileForm.steps.loan.title", - titleFallback: "Karz", - subtitleKey: "loanOrderMobileForm.steps.loan.subtitle", - subtitleFallback: "Görnüş, möçber & lokasiýa", - icon: FileText, + id: "status", + titleKey: "Status", + titleFallback: "Status", + subtitleKey: "loanOrderForm.steps.status.subtitle", + subtitleFallback: "Ýagdaý we bellik", + icon: CircleDot, validate: (form, mode) => validateStep(0, form, mode), }, { - id: "personal", - titleKey: "loanOrderMobileForm.steps.personal.title", - titleFallback: "Şahsy & Pasport", - subtitleKey: "loanOrderMobileForm.steps.personal.subtitle", - subtitleFallback: "Şahsyýet & pasport", - icon: User, + id: "loan", + titleKey: "Loan", + titleFallback: "Karz", + subtitleKey: "loanOrderForm.steps.loan.subtitle", + subtitleFallback: "Görnüş we möçber", + icon: Wallet, validate: (form, mode) => validateStep(1, form, mode), }, { - id: "contact", - titleKey: "loanOrderMobileForm.steps.contact.title", - titleFallback: "Habarlaşmak & Iş", - subtitleKey: "loanOrderMobileForm.steps.contact.subtitle", - subtitleFallback: "Telefon & iş", - icon: Phone, + id: "location", + titleKey: "Location", + titleFallback: "Lokasiýa", + subtitleKey: "loanOrderForm.steps.location.subtitle", + subtitleFallback: "Welaýat we şahamça", + icon: MapPin, validate: (form, mode) => validateStep(2, form, mode), }, { - id: "card", - titleKey: "loanOrderMobileForm.steps.card.title", - titleFallback: "Kart & Zamun", - subtitleKey: "loanOrderMobileForm.steps.card.subtitle", - subtitleFallback: "Töleg & zamun", - icon: CreditCard, + id: "personal", + titleKey: "Personal data", + titleFallback: "Şahsy maglumatlar", + subtitleKey: "loanOrderForm.steps.personal.subtitle", + subtitleFallback: "At, bilim, maşgala", + icon: User, validate: (form, mode) => validateStep(3, form, mode), }, { - id: "files", - titleKey: "loanOrderMobileForm.steps.files.title", - titleFallback: "Faýllar & Status", - subtitleKey: "loanOrderMobileForm.steps.files.subtitle", - subtitleFallback: "Resminamalar", - icon: Upload, + id: "card", + titleKey: "Card (Salary)", + titleFallback: "Kart (Zähmet haky)", + subtitleKey: "loanOrderForm.steps.card.subtitle", + subtitleFallback: "Zähmet haky karty", + icon: CreditCard, validate: (form, mode) => validateStep(4, form, mode), }, + { + id: "passport", + titleKey: "Passport", + titleFallback: "Pasport", + subtitleKey: "loanOrderForm.steps.passport.subtitle", + subtitleFallback: "Seriýa, belgisi, senesi, suratlar", + icon: FileText, + validate: (form, mode) => validateStep(5, form, mode), + }, + { + id: "contact", + titleKey: "Contact data", + titleFallback: "Habarlaşmak", + subtitleKey: "loanOrderForm.steps.contact.subtitle", + subtitleFallback: "Telefon we e-poçta", + icon: Phone, + validate: (form, mode) => validateStep(6, form, mode), + }, + { + id: "job", + titleKey: "Work data", + titleFallback: "Iş maglumatlary", + subtitleKey: "loanOrderForm.steps.job.subtitle", + subtitleFallback: "Kärhana, wezipe, aýlyk", + icon: Briefcase, + validate: (form, mode) => validateStep(7, form, mode), + }, + { + id: "guarantor", + titleKey: "1. Guarantor", + titleFallback: "1. Zamun", + subtitleKey: "loanOrderForm.steps.guarantor.subtitle", + subtitleFallback: "Zamun maglumatlary", + icon: ShieldCheck, + validate: (form, mode) => validateStep(8, form, mode), + }, + { + id: "guarantor2", + titleKey: "2. Guarantor", + titleFallback: "2. Zamun", + subtitleKey: "loanOrderForm.steps.guarantor2.subtitle", + subtitleFallback: "2. Zamun maglumatlary", + icon: ShieldCheck, + validate: (form, mode) => validateStep(9, form, mode), + }, ]; // ─── Shared step content props ──────────────────────────────────────────────── @@ -149,147 +200,266 @@ interface StepContentProps { // ─── Step panels ────────────────────────────────────────────────────────────── -function StepLoan({ form, errors, set, t }: StepContentProps) { +function StepStatus({ form, errors, set, t }: StepContentProps) { + const statusOptions = useMemo(() => getStatusOptions(t, "loanOrderStatus"), [t]); + return ( -
- - - set("loanType", v)} - options={LOAN_TYPE_OPTIONS} - placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} - error={errors.loanType} - /> - + + + set("status", v)} + options={statusOptions} + error={errors.status} + placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} + /> + - - set("loanAmount", v)} - placeholder={t("loanOrderForm.placeholders.amount") || "0.00"} - error={errors.loanAmount} - /> - - - - - - { - set("region", v); - set("branch", ""); - }} - options={REGION_OPTIONS} - placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} - error={errors.region} - /> - - - - set("branch", v)} - options={BRANCHES_BY_REGION_MOBILE[form.region] ?? []} - placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} - disabled={!form.region} - error={errors.branch} - /> - - -
+ + set("note", v)} + placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."} + rows={3} + /> + + ); } -function StepPersonal({ form, errors, set, t }: StepContentProps) { +function StepLoan({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrderMobile }) { + const [loanTypeSearch, setLoanTypeSearch] = useState(""); + const loanTypesQuery = useInfiniteLoanTypes(loanTypeSearch); + + const loanTypeOptions: InfiniteSelectOption[] = useMemo(() => { + const opts: InfiniteSelectOption[] = (loanTypesQuery.data?.pages ?? []) + .flatMap((p) => p?.loanTypes ?? []) + .map((lt) => ({ value: String(lt.id), label: resolveLocalizedName(lt.title) || String(lt.id) })); + + if (initialData?.loanTypeId && !opts.some((o) => o.value === String(initialData.loanTypeId))) { + opts.unshift({ value: String(initialData.loanTypeId), label: initialData.loanType || String(initialData.loanTypeId) }); + } + return opts; + }, [loanTypesQuery, initialData]); + + return ( + + + set("loanType", v)} + options={loanTypeOptions} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + error={errors.loanType} + loading={loanTypesQuery.isLoading} + isLoadingMore={loanTypesQuery.isFetchingNextPage} + hasNextPage={!!loanTypesQuery.hasNextPage} + onLoadMore={() => loanTypesQuery.fetchNextPage()} + searchValue={loanTypeSearch} + onSearchChange={setLoanTypeSearch} + /> + + + + set("loanAmount", v)} + placeholder={t("loanOrderForm.placeholders.amount") || "0.00"} + error={errors.loanAmount} + /> + + + ); +} + +function StepLocation({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrderMobile }) { + const [branchSearch, setBranchSearch] = useState(""); + const branchQuery = useInfiniteBranches(branchSearch); + + const regionOptions = useMemo(() => getRegionOptions(t), [t]); + + const branchOptions: InfiniteSelectOption[] = useMemo(() => { + const opts: InfiniteSelectOption[] = (branchQuery.data?.pages ?? []) + .flatMap((p) => p?.branches ?? []) + .map((b) => ({ + value: String(b.id), + label: resolveLocalizedName(b.name) || b.uniqueCode || String(b.id), + })); + + if (initialData?.branchId && !opts.some((o) => o.value === String(initialData.branchId))) { + opts.unshift({ value: String(initialData.branchId), label: initialData.branch || String(initialData.branchId) }); + } + return opts; + }, [branchQuery, initialData]); + + return ( + + + { + set("region", v); + set("branch", ""); + }} + options={regionOptions} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + error={errors.region} + /> + + + + set("branch", v)} + options={branchOptions} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + disabled={!form.region} + error={errors.branch} + loading={branchQuery.isLoading} + isLoadingMore={branchQuery.isFetchingNextPage} + hasNextPage={!!branchQuery.hasNextPage} + onLoadMore={() => branchQuery.fetchNextPage()} + searchValue={branchSearch} + onSearchChange={setBranchSearch} + /> + + + ); +} + +function StepPersonal({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrderMobile }) { + const { data: requiredDocsData } = useGetRequiredDocuments({ page: 1, limit: 100 }); + + const [clientSearch, setClientSearch] = useState(""); + const clientsQuery = useInfiniteClients(clientSearch); + + const clientOptions: InfiniteSelectOption[] = useMemo(() => { + const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? []) + .flatMap((p) => p?.users ?? []) + .map((u) => ({ + value: String(u.id), + label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id), + })); + + if (initialData?.createdById && !opts.some((o) => o.value === String(initialData.createdById))) { + opts.unshift({ + value: String(initialData.createdById), + label: initialData.createdBy || String(initialData.createdById), + }); + } + return opts; + }, [clientsQuery.data, initialData]); + + const loanHistoryOptions = useMemo( + () => + (requiredDocsData?.loansDocuments ?? []).map((doc) => ({ + value: String(doc.id), + label: doc.name, + })), + [requiredDocsData], + ); + return (
- - - + + set("firstName", v)} - placeholder={t("Name") || "Ady"} - error={errors.firstName} - /> - - - set("lastName", v)} - placeholder={t("Surname") || "Familiýasy"} - error={errors.lastName} - /> - - - set("patronicName", v)} - placeholder={t("Patronic name") || "Atasynyň ady"} + value={form.userId} + onChange={(v) => set("userId", v)} + options={clientOptions} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + error={errors.userId} + loading={clientsQuery.isLoading} + isLoadingMore={clientsQuery.isFetchingNextPage} + hasNextPage={!!clientsQuery.hasNextPage} + onLoadMore={() => clientsQuery.fetchNextPage()} + searchValue={clientSearch} + onSearchChange={setClientSearch} /> +
+ set("firstName", v)} + placeholder={t("Name") || "Ady"} + error={errors.firstName} + /> + set("lastName", v)} + placeholder={t("Surname") || "Familiýasy"} + error={errors.lastName} + /> + set("patronicName", v)} + placeholder={t("Patronic name") || "Atasynyň ady"} + /> +
- - - set("education", v)} - options={EDUCATION_OPTIONS} - placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} - error={errors.education} - /> - - - set("marriageStatus", v)} - options={MARRIAGE_OPTIONS} - placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} - error={errors.marriageStatus} - /> - - - set("dateOfBirth", v)} - error={errors.dateOfBirth} - /> + + +
+ set("education", v)} + options={EDUCATION_OPTIONS} + placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} + error={errors.education} + /> + set("marriageStatus", v)} + options={MARRIAGE_OPTIONS} + placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} + error={errors.marriageStatus} + /> + set("dateOfBirth", v)} + error={errors.dateOfBirth} + /> +
- + - - - + + set("loanHistory", v)} - options={[]} - placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + options={loanHistoryOptions} + placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} /> +
+ ); +} +function StepCard({ form, errors, set, t }: StepContentProps) { + return ( + + + set("cardNumber", v)} + placeholder={t("Card number") || "Kart belgisi"} + error={errors.cardNumber} + /> + set("cardName", v)} + placeholder={t("Name on card") || "Kartdaky ady"} + error={errors.cardName} + /> + + + + set("cardExpMonth", v)} + options={MONTH_OPTIONS} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + error={errors.cardExpMonth} + /> + set("cardExpYear", v)} + options={YEAR_OPTIONS} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + error={errors.cardExpYear} + /> + + + ); +} + +function StepPassport({ form, errors, set, t, mode }: StepContentProps & { mode: "create" | "edit" }) { + return ( +
+ + + + set("passportOne", v)} + error={errors.passportOne} + required={mode === "create"} + accept="image/*" + /> + + + + set("passportTwo", v)} + error={errors.passportTwo} + required={mode === "create"} + accept="image/*" + /> + + + + set("passportThree", v)} + accept="image/*" + /> + + + + set("passportFour", v)} + accept="image/*" + /> + +
); } function StepContact({ form, errors, set, t }: StepContentProps) { return ( -
- - - set("phone", v)} - placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"} - error={errors.phone} - /> - set("email", v)} - placeholder={t("Email") || "E-poçta"} - /> - - - set("phoneAdditional", v)} - placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"} - error={errors.phoneAdditional} - /> - set("homePhone", v)} - placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"} - error={errors.homePhone} - /> - - + + + set("phone", v)} + placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"} + error={errors.phone} + /> + set("email", v)} + placeholder={t("Email") || "E-poçta"} + /> + + + set("phoneAdditional", v)} + placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"} + error={errors.phoneAdditional} + /> + set("homePhone", v)} + placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"} + error={errors.homePhone} + /> + + + ); +} + +function StepJob({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrderMobile }) { + const [provinceSearch, setProvinceSearch] = useState(""); + const provinceQuery = useInfiniteProvinces(provinceSearch); + + const regionOptions = useMemo(() => getRegionOptions(t), [t]); + + const provinceOptions: InfiniteSelectOption[] = useMemo(() => { + const opts: InfiniteSelectOption[] = (provinceQuery.data?.pages ?? []) + .flatMap((p) => p?.provinces ?? []) + .map((prov) => ({ value: String(prov.id), label: resolveLocalizedName(prov.name) || String(prov.id) })); + + if (initialData?.workCityId && !opts.some((o) => o.value === String(initialData.workCityId))) { + opts.unshift({ value: String(initialData.workCityId), label: initialData.workCity || String(initialData.workCityId) }); + } + return opts; + }, [provinceQuery, initialData]); + + return ( +
+ set("workRegion", v)} - options={REGION_OPTIONS} + options={regionOptions} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} /> - set("workProvince", v)} - options={[]} + options={provinceOptions} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + loading={provinceQuery.isLoading} + isLoadingMore={provinceQuery.isFetchingNextPage} + hasNextPage={!!provinceQuery.hasNextPage} + onLoadMore={() => provinceQuery.fetchNextPage()} + searchValue={provinceSearch} + onSearchChange={setProvinceSearch} /> @@ -503,54 +805,9 @@ function StepContact({ form, errors, set, t }: StepContentProps) { ); } -function StepCard({ form, errors, set, t }: StepContentProps) { +function StepGuarantor({ form, errors, set, t }: StepContentProps) { return (
- - - set("cardNumber", v)} - placeholder={t("Card number") || "Kart belgisi"} - error={errors.cardNumber} - /> - set("cardName", v)} - placeholder={t("Name on card") || "Kartdaky ady"} - error={errors.cardName} - /> - - - set("cardExpMonth", v)} - options={MONTH_OPTIONS} - placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} - error={errors.cardExpMonth} - /> - set("cardExpYear", v)} - options={YEAR_OPTIONS} - placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} - error={errors.cardExpYear} - /> - - - - + - + + set("guarantor1CardExpMonth", v)} @@ -645,7 +903,7 @@ function StepCard({ form, errors, set, t }: StepContentProps) { /> set("guarantor1CardExpYear", v)} @@ -653,13 +911,18 @@ function StepCard({ form, errors, set, t }: StepContentProps) { placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.guarantor1CardExpYear} /> + + + + + set("guarantor1Salary", v)} - placeholder={t("loanOrderForm.labels.guarantor1Salary") || "Ortaca zähmet haky"} + placeholder={t("Guarantor Salary") || "Zamunyň zähmet haky"} error={errors.guarantor1Salary} /> @@ -668,111 +931,116 @@ function StepCard({ form, errors, set, t }: StepContentProps) { ); } -function StepFiles({ - form, - errors, - set, - t, - mode, - initialData, -}: StepContentProps & { mode: "create" | "edit"; initialData?: LoanOrderMobile }) { - const statusOptions = useMemo(() => getStatusOptions(t, "loanOrderStatus"), [t]); - const existingFiles = - mode === "edit" && initialData - ? [ - { url: initialData.passportPage1Url, label: t("Passport (page 1)") || "Pasport (sahypa 1)" }, - { url: initialData.passportPage23Url, label: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)" }, - { url: initialData.passportPage89Url, label: t("Passport (page 8-9)") || "Pasport (8-9 sahypa)" }, - { url: initialData.passportPage32Url, label: t("Passport (page 32)") || "Pasport (32-nji sahypa)" }, - ].filter((f): f is { url: string; label: string } => !!f.url) - : []; - +function StepGuarantor2({ form, errors, set, t }: StepContentProps) { return (
- + set("status", v)} - options={statusOptions} - placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} - error={errors.status} + type="text" + label={t("Guarantor name") || "Zamunyň ady"} + value={form.guarantor2Name} + onChange={(v) => set("guarantor2Name", v)} + placeholder={t("Guarantor name") || "Zamunyň ady"} + error={errors.guarantor2Name} /> set("note", v)} - placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."} - rows={3} + type="text" + label={t("Guarantor Surname") || "Zamunyň familiýasy"} + value={form.guarantor2Surname} + onChange={(v) => set("guarantor2Surname", v)} + placeholder={t("Guarantor Surname") || "Zamunyň familiýasy"} + error={errors.guarantor2Surname} + /> + + + set("guarantor2Patronic", v)} + placeholder={t("Guarantor Patronic name") || "Zamunyň atasynyň ady"} /> - {existingFiles.length > 0 && ( - - {existingFiles.map(({ url, label }) => ( - - - {t("loanOrderForm.fileLabels.viewFile") || "Faýly gör"} - - - ))} - - )} - set("passportPage1", f)} - error={errors.passportPage1} + type="searchable-select" + label={t("Passport serie") || "Pasport seriýasy"} + value={form.guarantor2PassportSerie} + onChange={(v) => set("guarantor2PassportSerie", v)} + options={PASSPORT_SERIES_OPTIONS} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + error={errors.guarantor2PassportSerie} /> set("passportPage23", f)} - error={errors.passportPage23} + type="text" + label={t("Passport id") || "Pasport belgisi"} + value={form.guarantor2PassportNumber} + onChange={(v) => set("guarantor2PassportNumber", v)} + placeholder={t("Passport id") || "Pasport belgisi"} + error={errors.guarantor2PassportNumber} /> - + + + + set("passportPage89", f)} + type="text" + label={t("Card number") || "Kart belgisi"} + value={form.guarantor2CardNumber} + onChange={(v) => set("guarantor2CardNumber", v)} + placeholder={t("Card number") || "Kart belgisi"} + error={errors.guarantor2CardNumber} + /> + set("guarantor2CardName", v)} + placeholder={t("Name on card") || "Kartdaky ady"} + error={errors.guarantor2CardName} /> + + + set("guarantor2CardExpMonth", v)} + options={MONTH_OPTIONS} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + error={errors.guarantor2CardExpMonth} + /> + set("guarantor2CardExpYear", v)} + options={YEAR_OPTIONS} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + error={errors.guarantor2CardExpYear} + /> + + + + set("passportPage32", f)} + type="textarea" + label={t("Note") || "Bellik"} + value={form.guarantor2Note} + onChange={(v) => set("guarantor2Note", v)} + placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."} + rows={3} /> @@ -780,18 +1048,19 @@ function StepFiles({ ); } -// ─── Props ──────────────────────────────────────────────────────────────────── +// ─── Main form component ────────────────────────────────────────────────────── interface LoanOrderMobileFormProps { - mode: "create" | "edit"; initialData?: LoanOrderMobile; + mode: "create" | "edit"; } -// ─── Main Component ─────────────────────────────────────────────────────────── - -export function LoanOrderMobileForm({ mode, initialData }: LoanOrderMobileFormProps) { - const { t, i18n } = useTranslation(); +export function LoanOrderMobileForm({ initialData, mode }: LoanOrderMobileFormProps) { + const { t } = useTranslation(); const navigate = useNavigate(); + const [currentStep, setCurrentStep] = useState(0); + const [visited, setVisited] = useState>(() => new Set([0])); + const [submittedSteps, setSubmittedSteps] = useState>(() => new Set()); const createMutation = useCreateLoanOrderMobile(); const updateMutation = useUpdateLoanOrderMobile(); @@ -800,70 +1069,56 @@ export function LoanOrderMobileForm({ mode, initialData }: LoanOrderMobileFormPr const { watch, setValue, - getValues, - formState: { errors: rhfErrors }, - clearErrors, setError, + clearErrors, + formState: { errors: rawErrors }, + getValues, } = useForm({ - defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES, + defaultValues: initialData ? mapInitial(initialData) : DEFAULT_FORM_VALUES, }); const form = watch(); - const [currentStep, setCurrentStep] = useState(0); - const [visited, setVisited] = useState>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set())); - const [submittedSteps, setSubmittedSteps] = useState>(new Set()); - - const stepsWithErrors = useMemo(() => { - const out = new Set(); - visited.forEach((i) => { - if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i); - }); - return out; - }, [form, mode, visited, i18n.language]); + const flatErrors = useMemo(() => flattenErrors(rawErrors as Record), [rawErrors]); const set = useCallback( - (key: K, value: LoanOrderMobileFormData[K]) => { - (setValue as (name: K, val: LoanOrderMobileFormData[K]) => void)(key, value); - clearErrors(key); + (k: K, v: LoanOrderMobileFormData[K]) => { + (setValue as (name: K, val: LoanOrderMobileFormData[K]) => void)(k, v); + clearErrors(k); }, - [setValue, clearErrors], + [setValue, clearErrors, submittedSteps, currentStep], ); - const allSubmittedErrors = useMemo(() => { - const result: FlatErrors = {}; - for (const stepIdx of submittedSteps) { - Object.assign(result, STEPS[stepIdx].validate(form, mode)); - } - return result; - }, [form, mode, submittedSteps, i18n.language]); - const errors = useMemo(() => { - const fromRHF = flattenErrors(rhfErrors as Record); - return { ...fromRHF, ...allSubmittedErrors }; - }, [rhfErrors, allSubmittedErrors]); + const stepProps: StepContentProps = { form, errors: flatErrors, set, t }; - const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t]); + const markVisited = (stepIdx: number) => { + setVisited((prev) => new Set([...prev, stepIdx])); + }; - // ── Navigation ────────────────────────────────────────────────────────────── - - const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i])); - - const markSubmitted = (i: number) => setSubmittedSteps((prev) => new Set([...prev, i])); + const stepsWithErrors = useMemo(() => { + const errorSet = new Set(); + submittedSteps.forEach((s) => { + const stepErrs = STEPS[s].validate(form, mode); + if (Object.keys(stepErrs).length > 0) errorSet.add(s); + }); + return errorSet; + }, [submittedSteps, form, mode]); const handleNext = () => { - markVisited(currentStep); - markSubmitted(currentStep); - const errs = STEPS[currentStep].validate(form, mode); - if (Object.keys(errs).length > 0) { - Object.entries(errs).forEach(([key, msg]) => { + setSubmittedSteps((prev) => new Set([...prev, currentStep])); + const stepErrs = STEPS[currentStep].validate(form, mode); + + if (Object.keys(stepErrs).length > 0) { + Object.entries(stepErrs).forEach(([key, msg]) => { setError(key as keyof LoanOrderMobileFormData, { type: "manual", message: msg }); }); - toast.error(t("common.errors.fillRequiredCorrectly", "Dogry maglumat girizmegiňizi haýyş edýäris.")); + toast.error(t("common.errors.requiredFieldsMissing", "Käbir hökmany meýdanlar doldurylan däldir.")); return; } - if (currentStep < STEPS.length - 1) { - setCurrentStep(currentStep + 1); - window.scrollTo({ top: 0, behavior: "smooth" }); - } + + const next = currentStep + 1; + markVisited(next); + setCurrentStep(next); + window.scrollTo({ top: 0, behavior: "smooth" }); }; const handleBack = () => { @@ -936,14 +1191,12 @@ export function LoanOrderMobileForm({ mode, initialData }: LoanOrderMobileFormPr {/* Page header */}

- {mode === "create" - ? t("loanOrderMobiles.createTitle") || "Karz sargyt döredüň" - : t("loanOrderMobiles.editTitle") || "Karz sargydy üýtget"} + {mode === "create" ? t("loanOrders.create") || "Karz sargyt dörediň" : t("loanOrders.edit") || "Karz sargydy üýtget"}

{mode === "create" - ? t("loanOrderMobiles.createDescription") || "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň." - : t("loanOrderMobiles.editDescription") || "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň."} + ? t("loanOrders.createDescription") || "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň." + : t("loanOrders.editDescription") || "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň."}

@@ -953,11 +1206,16 @@ export function LoanOrderMobileForm({ mode, initialData }: LoanOrderMobileFormPr
{/* Step content */} - {currentStep === 0 && } - {currentStep === 1 && } - {currentStep === 2 && } - {currentStep === 3 && } - {currentStep === 4 && } + {currentStep === 0 && } + {currentStep === 1 && } + {currentStep === 2 && } + {currentStep === 3 && } + {currentStep === 4 && } + {currentStep === 5 && } + {currentStep === 6 && } + {currentStep === 7 && } + {currentStep === 8 && } + {currentStep === 9 && } {/* Actions */}
@@ -984,33 +1238,38 @@ export function LoanOrderMobileForm({ mode, initialData }: LoanOrderMobileFormPr function mapInitial(order: LoanOrderMobile): Partial { return { status: order.status ?? "pending", - loanType: order.loanType ?? "", - region: order.region ?? "Aşgabat", - branch: order.branch ?? "", + loanType: order.loanTypeId != null ? String(order.loanTypeId) : "", + region: order.region ?? "AG", + branch: order.branchId != null ? String(order.branchId) : "", + userId: order.createdById != null ? String(order.createdById) : "", firstName: order.firstName ?? "", lastName: order.lastName ?? "", patronicName: order.patronicName ?? "", education: order.education ?? "", marriageStatus: order.marriageStatus ?? "", - dateOfBirth: order.dateOfBirth ?? "", + dateOfBirth: formatFromApiDate(order.dateOfBirth), residence: order.residence ?? "", currentResidence: order.currentResidence ?? "", passportSerie: order.passportSerie ?? "", passportNumber: order.passportNumber ?? "", - passportDateOfIssue: order.passportDateOfIssue ?? "", + passportDateOfIssue: formatFromApiDate(order.passportDateOfIssue), passportGivenBy: order.passportGivenBy ?? "", + passportOne: order.passportPage1Url ?? "", + passportTwo: order.passportPage23Url ?? "", + passportThree: order.passportPage89Url ?? "", + passportFour: order.passportPage32Url ?? "", bornPlace: order.bornPlace ?? "", email: order.email ?? "", - phone: order.phone ?? "", - phoneAdditional: order.phoneAdditional ?? "", - homePhone: order.homePhone ?? "", + phone: formatFromApiPhone(order.phone), + phoneAdditional: formatFromApiPhone(order.phoneAdditional), + homePhone: formatFromApiPhone(order.homePhone), workCompany: order.workCompany ?? "", - workHrPhone: order.workHrPhone ?? "", - workRegion: order.workRegion ?? "Aşgabat", - workProvince: order.workProvince ?? "", + workHrPhone: formatFromApiPhone(order.workHrPhone), + workRegion: order.workRegion ?? "AG", + workProvince: order.workCityId != null ? String(order.workCityId) : "", position: order.position ?? "", salary: order.salary != null ? String(order.salary) : "", - workStartedAt: order.workStartedAt ?? "", + workStartedAt: formatFromApiDate(order.workStartedAt), note: order.note ?? "", loanAmount: order.loanAmount != null ? String(order.loanAmount) : "", loanHistory: order.loanHistory ?? "", @@ -1028,5 +1287,15 @@ function mapInitial(order: LoanOrderMobile): Partial { guarantor1CardExpMonth: order.guarantor1CardExpMonth ?? "", guarantor1CardExpYear: order.guarantor1CardExpYear ?? "", guarantor1Salary: order.guarantor1Salary != null ? String(order.guarantor1Salary) : "", + guarantor2Name: order.guarantor2Name ?? "", + guarantor2Surname: order.guarantor2Surname ?? "", + guarantor2Patronic: order.guarantor2Patronic ?? "", + guarantor2PassportSerie: order.guarantor2PassportSerie ?? "", + guarantor2PassportNumber: order.guarantor2PassportNumber ?? "", + guarantor2CardNumber: order.guarantor2CardNumber ?? "", + guarantor2CardName: order.guarantor2CardName ?? "", + guarantor2CardExpMonth: order.guarantor2CardExpMonth ?? "", + guarantor2CardExpYear: order.guarantor2CardExpYear ?? "", + guarantor2Note: order.guarantor2Note ?? "", }; } diff --git a/src/features/loanOrderMobiles/hooks/useLoanOrderMobiles.ts b/src/features/loanOrderMobiles/hooks/useLoanOrderMobiles.ts index 9c2cc3e..b5e8aef 100644 --- a/src/features/loanOrderMobiles/hooks/useLoanOrderMobiles.ts +++ b/src/features/loanOrderMobiles/hooks/useLoanOrderMobiles.ts @@ -1,6 +1,6 @@ -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import { toast } from 'sonner' -import { useTranslation } from 'react-i18next' +import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { useTranslation } from "react-i18next"; import { fetchLoanOrderMobiles, @@ -8,40 +8,42 @@ import { getLoanOrderMobileById, createLoanOrderMobile, updateLoanOrderMobile, + patchLoanOrderMobile, type LoanOrderMobileListParams, type LoanOrderMobilePayload, -} from '../api/loanOrderMobilesApi' +} from "../api/loanOrderMobilesApi"; // ─── Query keys ──────────────────────────────────────────────────────────────── export const loanOrderMobileKeys = { - all: ['loanOrderMobiles'] as const, - lists: () => [...loanOrderMobileKeys.all, 'list'] as const, + all: ["loanOrderMobiles"] as const, + lists: () => [...loanOrderMobileKeys.all, "list"] as const, list: (params: LoanOrderMobileListParams) => [...loanOrderMobileKeys.lists(), params] as const, - details: () => [...loanOrderMobileKeys.all, 'detail'] as const, + details: () => [...loanOrderMobileKeys.all, "detail"] as const, detail: (id: string) => [...loanOrderMobileKeys.details(), id] as const, -} +}; // ─── Hooks ───────────────────────────────────────────────────────────────────── export function useLoanOrderMobiles(params: LoanOrderMobileListParams) { return useQuery({ queryKey: loanOrderMobileKeys.list(params), - queryFn: () => fetchLoanOrderMobiles(params), - }) + queryFn: ({ signal }) => fetchLoanOrderMobiles(params, signal), + placeholderData: (prev) => prev, + }); } export function useDeleteLoanOrderMobile() { - const queryClient = useQueryClient() - const { t } = useTranslation() + const queryClient = useQueryClient(); + const { t } = useTranslation(); return useMutation({ mutationFn: (id: string) => deleteLoanOrderMobile(id), onSuccess: () => { - queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() }) - toast.success(t('loanOrderMobiles.deleteSuccess', 'Sargyt üstünlikli pozuldy')) + queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() }); + toast.success(t("loanOrderMobiles.deleteSuccess", "Sargyt üstünlikli pozuldy")); }, - }) + }); } export function useLoanOrderMobileById(id: string) { @@ -49,33 +51,47 @@ export function useLoanOrderMobileById(id: string) { queryKey: loanOrderMobileKeys.detail(id), queryFn: () => getLoanOrderMobileById(id), enabled: !!id, - }) + }); } export function useCreateLoanOrderMobile() { - const queryClient = useQueryClient() - const { t } = useTranslation() + const queryClient = useQueryClient(); + const { t } = useTranslation(); return useMutation({ mutationFn: (payload: LoanOrderMobilePayload) => createLoanOrderMobile(payload), onSuccess: () => { - queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() }) - toast.success(t('loanOrderMobiles.createSuccess', 'Sargyt üstünlikli döredildi')) + queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() }); + toast.success(t("loanOrderMobiles.createSuccess", "Sargyt üstünlikli döredildi")); }, - }) + }); } export function useUpdateLoanOrderMobile() { - const queryClient = useQueryClient() - const { t } = useTranslation() + const queryClient = useQueryClient(); + const { t } = useTranslation(); return useMutation({ - mutationFn: ({ id, payload }: { id: string; payload: Partial }) => - updateLoanOrderMobile(id, payload), + mutationFn: ({ id, payload }: { id: string; payload: Partial }) => updateLoanOrderMobile(id, payload), onSuccess: (_, variables) => { - queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() }) - queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.detail(variables.id) }) - toast.success(t('loanOrderMobiles.updateSuccess', 'Sargyt üstünlikli üýtgedildi')) + queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() }); + queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.detail(variables.id) }); + toast.success(t("loanOrderMobiles.updateSuccess", "Sargyt üstünlikli üýtgedildi")); }, - }) -} \ No newline at end of file + }); +} + +export function usePatchLoanOrderMobile() { + const queryClient = useQueryClient(); + const { t } = useTranslation(); + + return useMutation({ + mutationFn: ({ id, payload }: { id: string; payload: Partial | Record }) => + 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")); + }, + }); +} diff --git a/src/features/loanOrderMobiles/schemas/loanOrderMobile.schema.ts b/src/features/loanOrderMobiles/schemas/loanOrderMobile.schema.ts index e34386a..cd785f7 100644 --- a/src/features/loanOrderMobiles/schemas/loanOrderMobile.schema.ts +++ b/src/features/loanOrderMobiles/schemas/loanOrderMobile.schema.ts @@ -1,293 +1,3 @@ -import { z } from "zod"; -import i18next from "i18next"; - -const fileRequired = z.custom((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().nullable(), - passportPage23: z.custom().nullable(), - passportPage89: z.custom().nullable(), - passportPage32: z.custom().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; - -export const stepSchemas: Record>> = { - 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> { - if (stepIndex === 4 && mode === "edit") return {}; - const schema = stepSchemas[stepIndex]; - const result = schema.safeParse(form); - if (result.success) return {}; - const errors: Partial> = {}; - for (const issue of result.error.issues) { - const key = issue.path[0] as keyof LoanOrderMobileFormData; - if (!errors[key]) { - const msg = issue.message; - errors[key] = msg.startsWith("validation.") ? i18next.t(msg, msg) : msg; - } - } - return errors; -} - -export const DEFAULT_FORM_VALUES: LoanOrderMobileFormData = { - status: "pending", - loanType: "", - region: "Aşgabat", - branch: "", - firstName: "", - lastName: "", - patronicName: "", - education: "", - marriageStatus: "", - dateOfBirth: "", - residence: "", - currentResidence: "", - passportSerie: "", - passportNumber: "", - passportDateOfIssue: "", - passportGivenBy: "", - bornPlace: "", - email: "", - phone: "", - phoneAdditional: "", - homePhone: "", - workCompany: "", - workHrPhone: "", - workRegion: "Aşgabat", - workProvince: "", - position: "", - salary: "", - workStartedAt: "", - passportPage1: null, - passportPage23: null, - passportPage89: null, - passportPage32: null, - note: "", - loanAmount: "", - loanHistory: "", - cardNumber: "", - cardName: "", - cardExpMonth: "", - cardExpYear: "", - guarantor1Name: "", - guarantor1Surname: "", - guarantor1Patronic: "", - guarantor1PassportSerie: "", - guarantor1PassportNumber: "", - guarantor1CardNumber: "", - guarantor1CardName: "", - guarantor1CardExpMonth: "", - guarantor1CardExpYear: "", - guarantor1Salary: "", -}; - -export function buildPayload(data: LoanOrderMobileFormData) { - return { - status: data.status, - loanType: data.loanType, - region: data.region, - branch: data.branch, - firstName: data.firstName, - lastName: data.lastName, - patronicName: data.patronicName || undefined, - education: data.education, - marriageStatus: data.marriageStatus, - dateOfBirth: data.dateOfBirth, - residence: data.residence, - currentResidence: data.currentResidence || undefined, - passportSerie: data.passportSerie, - passportNumber: data.passportNumber, - passportDateOfIssue: data.passportDateOfIssue, - passportGivenBy: data.passportGivenBy, - bornPlace: data.bornPlace || undefined, - email: data.email || undefined, - phone: data.phone, - phoneAdditional: data.phoneAdditional || undefined, - homePhone: data.homePhone || undefined, - workCompany: data.workCompany, - workHrPhone: data.workHrPhone || undefined, - workRegion: data.workRegion || undefined, - workProvince: data.workProvince || undefined, - position: data.position, - salary: Number(data.salary), - workStartedAt: data.workStartedAt, - note: data.note || undefined, - loanAmount: Number(data.loanAmount) || undefined, - loanHistory: data.loanHistory || undefined, - cardNumber: data.cardNumber || undefined, - cardName: data.cardName || undefined, - cardExpMonth: data.cardExpMonth || undefined, - cardExpYear: data.cardExpYear || undefined, - guarantor1Name: data.guarantor1Name || undefined, - guarantor1Surname: data.guarantor1Surname || undefined, - guarantor1Patronic: data.guarantor1Patronic || undefined, - guarantor1PassportSerie: data.guarantor1PassportSerie || undefined, - guarantor1PassportNumber: data.guarantor1PassportNumber || undefined, - guarantor1CardNumber: data.guarantor1CardNumber || undefined, - guarantor1CardName: data.guarantor1CardName || undefined, - guarantor1CardExpMonth: data.guarantor1CardExpMonth || undefined, - guarantor1CardExpYear: data.guarantor1CardExpYear || undefined, - guarantor1Salary: Number(data.guarantor1Salary) || undefined, - }; -} +export * from "@/features/loanOrders/schemas/loanOrder.schema"; +export type { LoanOrderFormData as LoanOrderMobileFormData } from "@/features/loanOrders/schemas/loanOrder.schema"; +export { loanOrderFormSchema as loanOrderMobileFormSchema } from "@/features/loanOrders/schemas/loanOrder.schema"; diff --git a/src/features/loanOrders/api/loanOrdersApi.ts b/src/features/loanOrders/api/loanOrdersApi.ts index e76289b..4a71504 100644 --- a/src/features/loanOrders/api/loanOrdersApi.ts +++ b/src/features/loanOrders/api/loanOrdersApi.ts @@ -8,52 +8,81 @@ import type { LocalizedText } from "@/features/branches/api/branchesApi"; export type LoanOrderStatus = StatusValue; +export interface LoanOrderUser { + id?: number; + name?: string; + username?: string; + phone?: string; + email?: string; +} + export interface LoanOrder { id: string; + uniqueId?: string | null; + source?: string | null; + user?: LoanOrderUser | null; loanType: string; createdAt: string; + updatedAt?: string | null; region: string; branch: string; branchId?: number | string; loanTypeId?: number | string; workCityId?: number | string; + workProvinceId?: number | string; createdById?: number | string; + createdBy?: string | null; firstName: string; lastName: string; + patronicName?: string | null; + fullName?: string | null; phone: string; + homePhone?: string | null; + phoneAdditional?: string | null; status: LoanOrderStatus; note?: string | null; + notes?: string | null; loanAmount?: number | null; loanHistory?: string | null; - patronicName?: string | null; + loanOrderRequiredDoc?: { id: number; name: string } | null; + satisfiable?: string | null; + education?: string | null; marriageStatus?: string | null; + maritalStatus?: string | null; dateOfBirth?: string | null; + birthDate?: string | null; residence?: string | null; + registeredAddress?: string | null; currentResidence?: string | null; + currentAddress?: string | null; passportSerie?: string | null; passportNumber?: string | null; passportDateOfIssue?: string | null; passportGivenBy?: string | null; + passportIssuedBy?: string | null; bornPlace?: string | null; + passportBirthPlace?: string | null; passportPage1Url?: string | null; passportPage23Url?: string | null; passportPage89Url?: string | null; passportPage32Url?: string | null; email?: string | null; - phoneAdditional?: string | null; - homePhone?: string | null; workCompany?: string | null; + employer?: string | null; workHrPhone?: string | null; + deptPhone?: string | null; workRegion?: string | null; workProvince?: string | null; + workCity?: string | null; position?: string | null; salary?: number | null; workStartedAt?: string | null; + employedSince?: string | null; cardNumber?: string | null; cardName?: string | null; @@ -70,6 +99,7 @@ export interface LoanOrder { guarantor1CardExpMonth?: string | null; guarantor1CardExpYear?: string | null; guarantor1Salary?: number | null; + guarantor1Note?: string | null; guarantor2Name?: string | null; guarantor2Surname?: string | null; @@ -82,20 +112,13 @@ export interface LoanOrder { guarantor2CardExpYear?: string | null; guarantor2Note?: string | null; + loanCardNumber?: string | null; + loanCardName?: string | null; + loanCardMonth?: string | null; + loanCardYear?: string | null; + amount?: number | null; - createdBy?: string | null; - fullName?: string | null; - maritalStatus?: string | null; - birthDate?: string | null; - registeredAddress?: string | null; - currentAddress?: string | null; phoneAlt?: string | null; - employer?: string | null; - deptPhone?: string | null; - workCity?: string | null; - employedSince?: string | null; - passportIssuedBy?: string | null; - passportBirthPlace?: string | null; } export interface LoanOrdersParams { @@ -103,9 +126,14 @@ export interface LoanOrdersParams { region?: string; status?: LoanOrderStatus | ""; branch?: string; + branch_id?: string | number; + createdById?: string | number; + userId?: string | number; + user_id?: string | number; archived?: string; page?: number; perPage?: number; + limit?: number; } export interface LoanOrdersResponse { @@ -120,7 +148,7 @@ export interface LoanOrderPayload { loanType: string; region: string; branch: string; - userId: string; + userId?: string | number; firstName: string; lastName: string; patronicName?: string; @@ -181,13 +209,14 @@ export interface LoanOrderPayload { passportTwo?: string; passportThree?: string; passportFour?: string; + source?: string; } // ─── Backend types ───────────────────────────────────────────────────────────── -type NestedLocalized = { id: number; name: LocalizedText | string }; +export type NestedLocalized = { id: number; name: LocalizedText | string }; -interface BackendLoanOrder { +export interface BackendLoanOrder { id?: number | string; uniqueId?: string | null; region?: string | null; @@ -196,6 +225,7 @@ interface BackendLoanOrder { branchName?: LocalizedText | string | null; loanType?: NestedLocalized | number | string | null; loanTypeName?: LocalizedText | string | null; + user?: LoanOrderUser | null; userId?: number | null; userName?: string | null; customerName?: string | null; @@ -236,6 +266,7 @@ interface BackendLoanOrder { workCompanyAccountantNumber?: string | null; workRegion?: string | null; workProvinceId?: number | null; + workProvince?: NestedLocalized | number | string | null; workProvinceName?: LocalizedText | string | null; workSalary?: string | number | null; workPosition?: string | null; @@ -243,6 +274,7 @@ interface BackendLoanOrder { satisfiable?: string | null; source?: string | null; loanOrderRequiredDocId?: number | null; + loanOrderRequiredDoc?: { id: number; name: string } | null; guarantorName?: string | null; guarantorSurname?: string | null; guarantorPatronicName?: string | null; @@ -265,14 +297,14 @@ interface BackendLoanOrder { guarantor2Note?: string | null; } -interface LoanOrdersListResponse { +export interface LoanOrdersListResponse { count: number; loanOrders: BackendLoanOrder[]; } // ─── Mapping helpers ─────────────────────────────────────────────────────────── -function resolveLocalizedName(name: LocalizedText | string | null | undefined): string { +export function resolveLocalizedName(name: LocalizedText | string | null | undefined): string { if (!name) return ""; if (typeof name === "string") return name; const lang = i18next.language || "en"; @@ -281,7 +313,7 @@ function resolveLocalizedName(name: LocalizedText | string | null | undefined): } /** Extract a display name from a nested `{id, name}` object, a `LocalizedText`, or a plain string/number. */ -function resolveNestedName(value: NestedLocalized | LocalizedText | string | number | null | undefined): string { +export function resolveNestedName(value: NestedLocalized | LocalizedText | string | number | null | undefined): string { if (value === null || value === undefined || value === "") return ""; if (typeof value === "string") return value; if (typeof value === "number") return ""; @@ -290,7 +322,7 @@ function resolveNestedName(value: NestedLocalized | LocalizedText | string | num } /** Extract a numeric ID from a nested `{id}` object, a number, or a string. */ -function resolveNestedId(value: NestedLocalized | number | string | null | undefined): number | null { +export function resolveNestedId(value: NestedLocalized | number | string | null | undefined): number | null { if (value === null || value === undefined || value === "") return null; if (typeof value === "number") return value; if (typeof value === "string") { @@ -301,58 +333,78 @@ function resolveNestedId(value: NestedLocalized | number | string | null | undef return null; } -function toNum(value: string | number | null | undefined): number | null { +export function toNum(value: string | number | null | undefined): number | null { if (value === null || value === undefined || value === "") return null; const n = Number(value); return Number.isNaN(n) ? null : n; } -function mapBackendToUI(order: BackendLoanOrder): LoanOrder { +export function mapBackendToUI(order: BackendLoanOrder): LoanOrder { const rawStatus = order.status ?? ""; const status: LoanOrderStatus = isStatusValue(rawStatus) ? rawStatus : "pending"; return { id: String(order.id ?? order.uniqueId ?? ""), + uniqueId: order.uniqueId ?? "", + source: order.source ?? "web", + user: order.user ?? (order.userId ? { id: order.userId, name: order.userName ?? "" } : undefined), loanType: resolveNestedName(order.loanType) || resolveLocalizedName(order.loanTypeName), createdAt: order.createdAt ?? "", + updatedAt: order.updatedAt ?? "", region: order.region ?? "", branch: resolveNestedName(order.branch) || resolveLocalizedName(order.branchName), branchId: resolveNestedId(order.branch) ?? order.branchId ?? undefined, loanTypeId: resolveNestedId(order.loanType) ?? undefined, - workCityId: order.workProvinceId ?? undefined, - createdById: order.userId ?? undefined, + workCityId: resolveNestedId(order.workProvince) ?? order.workProvinceId ?? undefined, + workProvinceId: resolveNestedId(order.workProvince) ?? order.workProvinceId ?? undefined, + createdById: order.user?.id ?? order.userId ?? undefined, + createdBy: order.user?.name ?? order.userName ?? "", firstName: order.customerName ?? "", lastName: order.customerSurname ?? "", patronicName: order.customerPatronicName ?? "", + fullName: [order.customerName, order.customerSurname].filter(Boolean).join(" "), phone: formatFromApiPhone(order.phone ?? order.phoneHome ?? ""), homePhone: formatFromApiPhone(order.phoneHome), phoneAdditional: formatFromApiPhone(order.phoneAdditional), status, note: order.notes ?? "", + notes: order.notes ?? "", loanAmount: toNum(order.loanAmount), + loanHistory: order.loanOrderRequiredDoc?.name || (order.loanOrderRequiredDocId ? String(order.loanOrderRequiredDocId) : ""), + loanOrderRequiredDoc: order.loanOrderRequiredDoc ?? undefined, + satisfiable: order.satisfiable ?? "", dateOfBirth: formatFromApiDate(order.bornAt), + birthDate: formatFromApiDate(order.bornAt), bornPlace: order.bornPlace ?? "", + passportBirthPlace: order.bornPlace ?? "", education: order.education ?? "", marriageStatus: order.marriageStatus ?? "", + maritalStatus: order.marriageStatus ?? "", residence: order.passportAddress ?? "", + registeredAddress: order.passportAddress ?? "", currentResidence: order.realAddress ?? "", + currentAddress: order.realAddress ?? "", email: order.email ?? "", passportSerie: order.passportSerie ?? "", passportNumber: order.passportId ?? "", passportDateOfIssue: formatFromApiDate(order.passportGivenAt), passportGivenBy: order.passportGivenBy ?? "", + passportIssuedBy: order.passportGivenBy ?? "", passportPage1Url: order.passportOne ?? "", passportPage23Url: order.passportTwo ?? "", passportPage89Url: order.passportThree ?? "", passportPage32Url: order.passportFour ?? "", workCompany: order.workCompany ?? "", + employer: order.workCompany ?? "", workHrPhone: formatFromApiPhone(order.workCompanyAccountantNumber), + deptPhone: formatFromApiPhone(order.workCompanyAccountantNumber), workRegion: order.workRegion ?? "", - workProvince: resolveLocalizedName(order.workProvinceName), - workCity: resolveLocalizedName(order.workProvinceName), + workProvince: resolveNestedName(order.workProvince) || resolveLocalizedName(order.workProvinceName), + workCity: resolveNestedName(order.workProvince) || resolveLocalizedName(order.workProvinceName), salary: toNum(order.workSalary), position: order.workPosition ?? "", workStartedAt: formatFromApiDate(order.workStartedAt), + employedSince: formatFromApiDate(order.workStartedAt), cardNumber: order.cardNumber ?? order.loanCardNumber ?? "", cardName: order.cardName ?? order.loanCardName ?? "", cardExpMonth: order.cardMonth ?? order.loanCardMonth ?? "", @@ -367,6 +419,7 @@ function mapBackendToUI(order: BackendLoanOrder): LoanOrder { guarantor1CardExpMonth: order.guarantorCardMonth ?? "", guarantor1CardExpYear: order.guarantorCardYear ?? "", guarantor1Salary: null, + guarantor1Note: order.guarantorNote ?? "", guarantor2Name: order.guarantor2Name ?? "", guarantor2Surname: order.guarantor2Surname ?? "", guarantor2Patronic: order.guarantor2PatronicName ?? "", @@ -377,23 +430,14 @@ function mapBackendToUI(order: BackendLoanOrder): LoanOrder { guarantor2CardExpMonth: order.guarantor2CardMonth ?? "", guarantor2CardExpYear: order.guarantor2CardYear ?? "", guarantor2Note: order.guarantor2Note ?? "", - loanHistory: order.loanOrderRequiredDocId ? String(order.loanOrderRequiredDocId) : "", - createdBy: order.userName ?? "", - fullName: [order.customerName, order.customerSurname].filter(Boolean).join(" "), - registeredAddress: order.passportAddress ?? "", - currentAddress: order.realAddress ?? "", - birthDate: formatFromApiDate(order.bornAt), - maritalStatus: order.marriageStatus ?? "", - phoneAlt: formatFromApiPhone(order.phoneAdditional), - employer: order.workCompany ?? "", - deptPhone: formatFromApiPhone(order.workCompanyAccountantNumber), - employedSince: formatFromApiDate(order.workStartedAt), - passportIssuedBy: order.passportGivenBy ?? "", - passportBirthPlace: order.bornPlace ?? "", + loanCardNumber: order.loanCardNumber ?? "", + loanCardName: order.loanCardName ?? "", + loanCardMonth: order.loanCardMonth ?? "", + loanCardYear: order.loanCardYear ?? "", }; } -function mapPayloadToBackend(payload: LoanOrderPayload | Partial): Record { +export function mapPayloadToBackend(payload: LoanOrderPayload | Partial): Record { return { customerName: payload.firstName ?? "", customerSurname: payload.lastName ?? "", @@ -458,25 +502,28 @@ function mapPayloadToBackend(payload: LoanOrderPayload | Partial { - 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("/loan-orders", { params: { page: page ?? 1, - limit: perPage ?? 25, + limit: perPage ?? limit ?? 25, search: search || undefined, region: region || undefined, status: status || undefined, - branch_id: branch || undefined, + branch_id: branchId || undefined, + user_id: uid || undefined, archived: archived || undefined, }, signal, @@ -486,7 +533,7 @@ export async function fetchLoanOrders(params: LoanOrdersParams = {}, signal?: Ab data: orders, total: data.count ?? orders.length, page: page ?? 1, - perPage: perPage ?? 25, + perPage: perPage ?? limit ?? 25, }; } @@ -505,6 +552,11 @@ export async function updateLoanOrder(id: string, payload: Partial | Record): Promise { + const { data } = await apiClient.patch(`/loan-orders/${id}`, payload); + return mapBackendToUI(data); +} + export async function deleteLoanOrder(id: string): Promise { await apiClient.delete(`/loan-orders/${id}`); } diff --git a/src/features/shared/api/sharedApi.ts b/src/features/shared/api/sharedApi.ts index 3767355..7bdcf29 100644 --- a/src/features/shared/api/sharedApi.ts +++ b/src/features/shared/api/sharedApi.ts @@ -13,11 +13,13 @@ export interface AddRoleUserPayload { userId: number; } -export interface AddPermissionUserPayload { +export interface AddPermissionRolePayload { permissionId: number; - userId: number; + roleId: number; } +export type AddPermissionUserPayload = AddPermissionRolePayload; + // Re-export so shared hooks can import from one place export type { BranchListParams, BranchListResponse }; @@ -67,13 +69,15 @@ export async function postRoleUser(payload: AddRoleUserPayload): Promise { } /** - * POST /permission-users - * Assigns a permission to a user. + * POST /permission-roles + * Assigns a permission to a role. */ -export async function postPermissionUser(payload: AddPermissionUserPayload): Promise { - await apiClient.post("/permission-users", payload); +export async function postPermissionRole(payload: AddPermissionRolePayload): Promise { + await apiClient.post("/permission-roles", payload); } +export const postPermissionUser = postPermissionRole; + /** * Proxy for branch list fetching — kept here so shared hooks * don't import directly from the branches feature. diff --git a/src/features/shared/hooks/useSharedUserAssignments.ts b/src/features/shared/hooks/useSharedUserAssignments.ts index 02e6274..c1736f4 100644 --- a/src/features/shared/hooks/useSharedUserAssignments.ts +++ b/src/features/shared/hooks/useSharedUserAssignments.ts @@ -4,10 +4,10 @@ import { useTranslation } from "react-i18next"; import { postBranchUser, postRoleUser, - postPermissionUser, + postPermissionRole, type AddBranchUserPayload, type AddRoleUserPayload, - type AddPermissionUserPayload, + type AddPermissionRolePayload, } from "../api/sharedApi"; // ─── Query Keys ─────────────────────────────────────────────────────────────── @@ -43,18 +43,17 @@ export function useAssignRoleToUser() { }); } -// ─── useAssignPermissionToUser ──────────────────────────────────────────────── +// ─── useAssignPermissionToRole ──────────────────────────────────────────────── /** - * POST /permission-users — assigns a permission to the given staff user and refreshes the profile cache. - * `userId` is supplied at mutate time (picked from the staff select). + * POST /permission-roles — assigns a permission to the given role and refreshes the profile cache. */ -export function useAssignPermissionToUser() { +export function useAssignPermissionToRole() { const { t } = useTranslation(); const invalidateProfile = useInvalidateProfile(); return useMutation({ - mutationFn: (payload: AddPermissionUserPayload) => postPermissionUser(payload), + mutationFn: (payload: AddPermissionRolePayload) => postPermissionRole(payload), onSuccess: () => { invalidateProfile(); toast.success(t("profile.assign.success", "Üstünlikli birikdirildi")); @@ -62,6 +61,8 @@ export function useAssignPermissionToUser() { }); } +export const useAssignPermissionToUser = useAssignPermissionToRole; + // ─── useAssignBranchToUser ──────────────────────────────────────────────────── /** diff --git a/src/pages/cardDepartment/cardBalance/index.tsx b/src/pages/cardDepartment/cardBalance/index.tsx index 8467c64..9a7d676 100644 --- a/src/pages/cardDepartment/cardBalance/index.tsx +++ b/src/pages/cardDepartment/cardBalance/index.tsx @@ -1,114 +1,232 @@ -import { useState } from "react"; +import { useState, useMemo, useCallback } from "react"; import { useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Download } from "lucide-react"; -import { DeleteDialog } from "@/components/deleteDialog"; -import { DataTable, type ColumnDef } from "@/components/dataTable"; -import { DataTableToolbar, type ColumnMeta } from "@/components/dataTableToolbar"; +import type { ColumnDef, VisibilityState } from "@tanstack/react-table"; + +import { DataTable } from "@/components/dataTable"; +import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar"; import { TableSearchInput } from "@/components/tableSearch"; import { CreateButton } from "@/components/createButton"; import { TableActions } from "@/components/tableActions"; -import type { VisibilityState } from "@tanstack/react-table"; -import { useCardBalances, useDeleteCardBalance, useDownloadCardBalance } from "@/features/cardBalance/hooks/useCardBalance"; -import { type CardBalance } from "@/features/cardBalance/api/cardBalanceApi"; +import { DeleteDialog } from "@/components/deleteDialog"; +import { useCardBalances, useDeleteCardBalance } from "@/features/cardBalance/hooks/useCardBalance"; +import type { CardBalance } from "@/features/cardBalance/api/cardBalanceApi"; +import { CardBalanceStatusBadge } from "@/features/cardBalance/components/cardBalanceStatusBadge"; +import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers"; -const PER_PAGE = 25; +// ─── Column meta for toggle dropdown ───────────────────────────────────────── + +const COLUMN_IDS = ["id", "passportNumber", "cardLast4", "expiry", "balance", "status", "createdBy", "createdAt"] as const; export default function CardBalancesPage() { const { t } = useTranslation(); const navigate = useNavigate(); + const deleteMutation = useDeleteCardBalance(); + const [deleteId, setDeleteId] = useState(null); const [page, setPage] = useState(1); - const [perPage, setPerPage] = useState(PER_PAGE); + const [perPage, setPerPage] = useState(25); const [search, setSearch] = useState(""); - const [deleteId, setDeleteId] = useState(null); const [columnVisibility, setColumnVisibility] = useState({}); - const [columnOrder, setColumnOrder] = useState([]); + const [columnOrder, setColumnOrder] = useState([...COLUMN_IDS]); - const { data, isLoading } = useCardBalances({ page, per_page: perPage, search }); - const deleteMutation = useDeleteCardBalance(); - const downloadMutation = useDownloadCardBalance(); + const [activeFilters, setActiveFilters] = useState([ + { fieldId: "status", value: "" }, + { fieldId: "created_by", value: "" }, + ]); - // ── Columns ─────────────────────────────────────────────────────────────── + // ── Infinite user dropdown for created_by filter ──────────────────────────── - const columns: ColumnDef[] = [ - { - id: "id", - accessorKey: "id", - header: t("ID", "ID"), - cell: ({ row }) => ( - + const [userSearch, setUserSearch] = useState(""); + const { + data: usersInfiniteData, + fetchNextPage: fetchNextUsers, + hasNextPage: hasNextUsers, + isFetchingNextPage: isFetchingNextUsers, + isLoading: isUsersLoading, + } = useInfiniteUsers(userSearch); + + const userOptions = useMemo( + () => + (usersInfiniteData?.pages ?? []).flatMap((page) => + (page?.users ?? []).map((u) => ({ + value: String(u.id), + label: u.name || u.username || String(u.id), + })), ), - }, - { - id: "passport_series", - accessorKey: "passport_series", - header: t("Passport series", "PASPORT SERIYASY"), - cell: ({ row }) => {row.original.passport_series}, - }, - { - id: "passport_number", - accessorKey: "passport_number", - header: t("Passport number", "PASPORT BELGISI"), - cell: ({ row }) => {row.original.passport_number}, - }, - { - id: "card_number", - accessorKey: "card_number", - header: t("Card number", "KART BELGISI"), - cell: ({ row }) => {row.original.card_number}, - }, - { - id: "card_expiry_month", - accessorKey: "card_expiry_month", - header: t("Expiry month", "KART MÖHLETI (AÝ)"), - cell: ({ row }) => {row.original.card_expiry_month}, - }, - { - id: "card_expiry_year", - accessorKey: "card_expiry_year", - header: t("Expiry year", "KART MÖHLETI (ÝYL)"), - cell: ({ row }) => {row.original.card_expiry_year}, - }, - { - id: "actions", - header: "", - enableHiding: false, - cell: ({ row }) => ( - downloadMutation.mutate(row.original.id) }]} - onView={() => navigate(`/card-balances/${row.original.id}`)} - onEdit={() => navigate(`/card-balances/${row.original.id}/edit`)} - onDelete={() => setDeleteId(row.original.id)} - isDeleting={deleteMutation.isPending} - /> - ), - }, - ]; + [usersInfiniteData], + ); - const columnMeta: ColumnMeta[] = columns - .filter((c) => c.id !== "actions") - .map((c) => ({ - id: c.id!, - label: typeof c.header === "string" ? c.header : c.id!, - })); + // ── Query params & data ───────────────────────────────────────────────────── - const total = data?.total ?? 0; - const totalPages = Math.ceil(total / perPage); + const queryParams = useMemo(() => { + const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value])); + return { + page, + limit: perPage, + search: search || undefined, + status: filterMap.status || undefined, + created_by: filterMap.created_by ? Number(filterMap.created_by) : undefined, + }; + }, [search, activeFilters, page, perPage]); - const handleDelete = async () => { + const { data, isLoading } = useCardBalances(queryParams); + const total = data?.count ?? 0; + const totalPages = Math.max(1, Math.ceil(total / perPage)); + + const statusOptions = useMemo( + () => [ + { value: "pending", label: t("cardBalance.status.pending", "Garaşylýar") }, + { value: "approved", label: t("cardBalance.status.approved", "Tassyklanan") }, + { value: "rejected", label: t("cardBalance.status.rejected", "Ret edilen") }, + ], + [t], + ); + + const handleFilterChange = useCallback((fieldId: string, value: string) => { + setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f))); + setPage(1); + }, []); + + const handleFilterReset = useCallback(() => { + setActiveFilters((prev) => prev.map((f) => ({ ...f, value: "" }))); + setPage(1); + }, []); + + const handleDelete = useCallback((id: number) => { + setDeleteId(id); + }, []); + + const confirmDelete = useCallback(() => { if (deleteId === null) return; - await deleteMutation.mutateAsync(deleteId); + deleteMutation.mutate(deleteId); setDeleteId(null); - }; + }, [deleteId, deleteMutation]); + + // ── Columns ───────────────────────────────────────────────────────────────── + + const columns = useMemo[]>( + () => [ + { + id: "id", + accessorKey: "id", + header: t("ID", "ID"), + cell: ({ row }) => ( + + ), + size: 70, + }, + { + id: "passportNumber", + accessorKey: "passportNumber", + header: t("Passport number", "PASPORT BELGISI"), + cell: ({ row }) => {row.original.passportNumber}, + }, + { + id: "cardLast4", + accessorKey: "cardLast4", + header: t("Card last 4", "KART BELGISI (SOŇKY 4)"), + cell: ({ row }) => •••• •••• •••• {row.original.cardLast4}, + }, + { + id: "expiry", + accessorKey: "expiryMonth", + header: t("Expiry", "KART MÖHLETI"), + cell: ({ row }) => ( + + {String(row.original.expiryMonth).padStart(2, "0")}/{row.original.expiryYear} + + ), + }, + { + id: "balance", + accessorKey: "balanceAmount", + header: t("Balance", "GALYNDY"), + cell: ({ row }) => ( + + {row.original.balanceAmount} {row.original.balanceCurrency} + + ), + }, + { + id: "status", + accessorKey: "status", + header: t("Status", "STATUS"), + cell: ({ row }) => , + size: 140, + }, + { + id: "createdBy", + accessorKey: "createdBy", + header: t("Created by", "DÖREDEN"), + cell: ({ row }) => ( + {row.original.createdBy?.name || row.original.createdBy?.username || "—"} + ), + }, + { + id: "createdAt", + accessorKey: "createdAt", + header: t("Created at", "DÖREDILEN WAGTY"), + cell: ({ row }) => ( + {new Date(row.original.createdAt).toLocaleString()} + ), + size: 180, + }, + { + id: "actions", + header: "", + enableHiding: false, + cell: ({ row }) => ( + 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( + () => [ + { + 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 (
+ {/* Header */}
-

{t("Card balances", "Kart galyndylary")}

+

{t("cardBalance.title", "Kart galyndylary")}

+
navigate("/card-balances/create")} />
+
{ setSearch(v); setPage(1); }} - searchPlaceholder={t("common.search", "Gözlemek")} - columns={columnMeta} + searchPlaceholder={t("cardBalance.searchPlaceholder", "Pasport belgisi boýunça gözle")} + columns={toggleableColumns} columnVisibility={columnVisibility} onColumnVisibilityChange={setColumnVisibility} columnOrder={columnOrder} onColumnOrderChange={setColumnOrder} - hideSearch - hideAction + filterFields={filterFields} + activeFilters={activeFilters} + onFilterChange={handleFilterChange} + onFilterReset={handleFilterReset} perPageOptions={[10, 25, 50, 100]} perPage={perPage} onPerPageChange={(v) => { @@ -143,9 +266,10 @@ export default function CardBalancesPage() { }} /> + {/* Table */}
+ {/* Delete dialog */} { if (!o) setDeleteId(null); }} - title={t("Are you sure?", "Eminsiňizmi?")} - description={t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")} - onConfirm={handleDelete} + title={t("cardBalance.deleteConfirm", "Bu ýazgy pozulsynmy?")} + description={t("cardBalance.deleteDescription", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")} + onConfirm={confirmDelete} isLoading={deleteMutation.isPending} />
diff --git a/src/pages/cardDepartment/cardBalanceView/index.tsx b/src/pages/cardDepartment/cardBalanceView/index.tsx index 1ea4737..6bda814 100644 --- a/src/pages/cardDepartment/cardBalanceView/index.tsx +++ b/src/pages/cardDepartment/cardBalanceView/index.tsx @@ -1,7 +1,7 @@ import { useState } from "react"; import { useParams, useNavigate, Link } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Download, Trash2, Pencil } from "lucide-react"; +import { Trash2, Pencil } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; import { @@ -14,25 +14,9 @@ import { AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; -import { - useCardBalance, - useDeleteCardBalance, - useDownloadCardBalance, -} from "@/features/cardBalance/hooks/useCardBalance"; -import { InfoRow, CollapsibleSection, StatusBadge, EmptyState } from "@/components/viewPageComponents"; -import { DataTable, type ColumnDef } from "@/components/dataTable"; -import { DataTableToolbar } from "@/components/dataTableToolbar"; - -// ─── Types for operations table ─────────────────────────────────────────────── - -interface Operation { - id: number; - action_name: string; - performed_by: string; - target: string; - status: "FINISHED" | "PENDING" | "FAILED"; - date: string; -} +import { useCardBalance, useDeleteCardBalance } from "@/features/cardBalance/hooks/useCardBalance"; +import { InfoRow } from "@/components/viewPageComponents"; +import { CardBalanceStatusBadge } from "@/features/cardBalance/components/cardBalanceStatusBadge"; // ─── Page ───────────────────────────────────────────────────────────────────── @@ -42,67 +26,10 @@ export default function CardBalanceViewPage() { const navigate = useNavigate(); const [deleteOpen, setDeleteOpen] = useState(false); - const [opsSearch, setOpsSearch] = useState(""); const numericId = Number(id); const { data, isLoading } = useCardBalance(numericId); const deleteMutation = useDeleteCardBalance(); - const downloadMutation = useDownloadCardBalance(); - - // Placeholder operations — in real app fetch from API using numericId - const operations: Operation[] = []; - - const filteredOperations = operations.filter( - (op) => - op.action_name.toLowerCase().includes(opsSearch.toLowerCase()) || - op.target.toLowerCase().includes(opsSearch.toLowerCase()), - ); - - // ── Operations columns ────────────────────────────────────────────────── - - const operationColumns: ColumnDef[] = [ - { - accessorKey: "id", - header: t("ID", "ID"), - cell: ({ row }) => ( - - {row.original.id} - - ), - size: 80, - }, - { - accessorKey: "action_name", - header: t("Action name", "AMALYŇ ADY"), - cell: ({ row }) => {row.original.action_name}, - }, - { - accessorKey: "performed_by", - header: t("Performed by", "KIM TARAPYNDAN"), - cell: ({ row }) => {row.original.performed_by}, - }, - { - accessorKey: "target", - header: t("Target", "AMALYŇ NYŞANY (TARGEDI)"), - cell: ({ row }) => {row.original.target}, - }, - { - accessorKey: "status", - header: t("Status", "AMALYŇ STATUSY"), - cell: ({ row }) => , - size: 160, - }, - { - accessorKey: "date", - header: t("Date", "SENE"), - cell: ({ row }) => ( - - {row.original.date} - - ), - size: 160, - }, - ]; const handleDelete = async () => { await deleteMutation.mutateAsync(numericId); @@ -114,7 +41,7 @@ export default function CardBalanceViewPage() {
- {Array.from({ length: 5 }).map((_, i) => ( + {Array.from({ length: 6 }).map((_, i) => (
@@ -126,11 +53,7 @@ export default function CardBalanceViewPage() { } if (!data) { - return ( -
- {t("Not found", "Tapylmady")} -
- ); + return
{t("Not found", "Tapylmady")}
; } return ( @@ -138,17 +61,9 @@ export default function CardBalanceViewPage() { {/* Header */}

- {t("Card balance detail", "Kart galyndysy giňişleýin")}: + {t("Card balance detail", "Kart galyndysy giňişleýin")}: #{data.id}

-
- {/* Ammallar (Operations) collapsible section */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - /> - {filteredOperations.length === 0 ? ( - - ) : ( - String(r.id)} - enableRowSelection - /> - )} - - {/* Delete dialog */} - - {t("Are you sure?", "Eminsiňizmi?")} - + {t("Are you sure?", "Eminsiňizmi?")} - {t( - "This action cannot be undone.", - "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.", - )} + {t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")} {t("Cancel", "Ýatyr")} - - {deleteMutation.isPending - ? t("Deleting...", "Öçürilýär...") - : t("Delete", "Öçür")} + + {deleteMutation.isPending ? t("Deleting...", "Öçürilýär...") : t("Delete", "Öçür")} diff --git a/src/pages/cardDepartment/cardRequisites/index.tsx b/src/pages/cardDepartment/cardRequisites/index.tsx index fd5e986..44853a6 100644 --- a/src/pages/cardDepartment/cardRequisites/index.tsx +++ b/src/pages/cardDepartment/cardRequisites/index.tsx @@ -1,155 +1,353 @@ -import { useState } from "react"; +import { useState, useMemo, useCallback } from "react"; import { useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Download, AlertCircle, CheckCircle2, XCircle } from "lucide-react"; -import { DeleteDialog } from "@/components/deleteDialog"; -import { DataTable, type ColumnDef } from "@/components/dataTable"; -import { DataTableToolbar, type ColumnMeta } from "@/components/dataTableToolbar"; +import { AlertCircle, CheckCircle2, XCircle } from "lucide-react"; +import type { ColumnDef, VisibilityState } from "@tanstack/react-table"; + +import { DataTable } from "@/components/dataTable"; +import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar"; import { TableSearchInput } from "@/components/tableSearch"; import { CreateButton } from "@/components/createButton"; import { TableActions } from "@/components/tableActions"; -import type { VisibilityState } from "@tanstack/react-table"; -import { useCardRequisites, useDeleteCardRequisite, useDownloadCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites"; -import type { CardRequisite, CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi"; import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge"; +import { DeleteDialog } from "@/components/deleteDialog"; +import { useCardRequisites, useDeleteCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites"; +import type { CardRequisite, CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi"; +import { resolveLocalizedName } from "@/features/cardRequisites/api/cardRequisitesApi"; +import { useInfiniteBranches } from "@/features/branches/hooks/useBranches"; +import { useInfiniteCardTypes } from "@/features/cardTypes/hooks/useCardTypes"; +import { useInfiniteClients } from "@/features/clients/hooks/useClients"; -// ─── Status badge ───────────────────────────────────────────────────────────── +// ─── Status Badge ───────────────────────────────────────────────────────────── -const STATUS_CONFIG: Record = { - pending: { label: "Garaşylýar", variant: "warning", icon: AlertCircle }, - approved: { label: "Tassyklanan", variant: "success", icon: CheckCircle2 }, - rejected: { label: "Ret edilen", variant: "error", icon: XCircle }, +const STATUS_CONFIG: Record< + CardRequisiteStatus, + { labelKey: string; fallback: string; variant: StatusBadgeVariant; icon: React.ElementType } +> = { + pending: { labelKey: "cardRequisites.status.pending", fallback: "Garaşylýar", variant: "warning", icon: AlertCircle }, + approved: { labelKey: "cardRequisites.status.approved", fallback: "Tassyklanan", variant: "success", icon: CheckCircle2 }, + rejected: { labelKey: "cardRequisites.status.rejected", fallback: "Ret edilen", variant: "error", icon: XCircle }, }; -function CardRequisiteStatusBadge({ status }: { status: CardRequisiteStatus }) { - const cfg = STATUS_CONFIG[status]; +function CardRequisiteStatusBadge({ status }: { status: string }) { + const { t } = useTranslation(); + const cfg = STATUS_CONFIG[status as CardRequisiteStatus]; if (!cfg) return {status}; - return ; + return ; } -// ─── Page ───────────────────────────────────────────────────────────────────── +// ─── Column meta for toggle dropdown ───────────────────────────────────────── -const PER_PAGE = 25; +const COLUMN_IDS = ["id", "uniqueId", "cardType", "customer", "user", "region", "branch", "status"] as const; + +// ─── Filter constants ───────────────────────────────────────────────────────── + +const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const; export default function CardRequisitesPage() { - const { t } = useTranslation(); + const { t, i18n } = useTranslation(); + const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en"; const navigate = useNavigate(); + const deleteMutation = useDeleteCardRequisite(); + const [deleteId, setDeleteId] = useState(null); const [page, setPage] = useState(1); - const [perPage, setPerPage] = useState(PER_PAGE); + const [perPage, setPerPage] = useState(25); const [search, setSearch] = useState(""); - const [deleteId, setDeleteId] = useState(null); const [columnVisibility, setColumnVisibility] = useState({}); - const [columnOrder, setColumnOrder] = useState([]); + const [columnOrder, setColumnOrder] = useState([...COLUMN_IDS]); - const { data, isLoading } = useCardRequisites({ - page, - per_page: perPage, - search, - }); - const deleteMutation = useDeleteCardRequisite(); - const downloadMutation = useDownloadCardRequisite(); + const [activeFilters, setActiveFilters] = useState([ + { fieldId: "status", value: "" }, + { fieldId: "region", value: "" }, + { fieldId: "branch_id", value: "" }, + { fieldId: "card_type_id", value: "" }, + { fieldId: "user_id", value: "" }, + ]); - // ── Columns ────────────────────────────────────────────────────────────────── + // ── Infinite dropdown hooks ───────────────────────────────────────────────── - const columns: ColumnDef[] = [ - { - id: "id", - accessorKey: "id", - header: t("ID", "ID"), - cell: ({ row }) => ( - + const [branchSearch, setBranchSearch] = useState(""); + const { + data: branchesInfiniteData, + fetchNextPage: fetchNextBranches, + hasNextPage: hasNextBranches, + isFetchingNextPage: isFetchingNextBranches, + isLoading: isBranchesLoading, + } = useInfiniteBranches(branchSearch); + + const branchOptions = useMemo( + () => + (branchesInfiniteData?.pages ?? []).flatMap((page) => + (page?.branches ?? []).map((b) => ({ + value: String(b.id), + label: b.name[lang] || b.name.tm || String(b.id), + })), ), - }, - { - id: "card_type", - accessorKey: "card_type", - header: t("Card type", "GÖRNÜŞI"), - cell: ({ row }) => {row.original.card_type}, - }, - { - id: "created_at", - accessorKey: "created_at", - header: t("Created at", "DÖREDILEN WAGTY"), - cell: ({ row }) => {row.original.created_at}, - }, - { - id: "province_name", - accessorKey: "province_name", - header: t("Province", "WELAÝAT"), - cell: ({ row }) => {row.original.province_name ?? "—"}, - }, - { - id: "branch_name", - accessorKey: "branch_name", - header: t("Branch", "ŞAHAMÇA"), - cell: ({ row }) => {row.original.branch_name ?? "—"}, - }, - { - id: "first_name", - accessorKey: "first_name", - header: t("First name", "ADY"), - cell: ({ row }) => {row.original.first_name}, - }, - { - id: "last_name", - accessorKey: "last_name", - header: t("Last name", "FAMILIÝASY"), - cell: ({ row }) => {row.original.last_name}, - }, - { - id: "status", - accessorKey: "status", - header: t("Status", "STATUS"), - cell: ({ row }) => , - }, - { - id: "actions", - header: "", - enableHiding: false, - cell: ({ row }) => ( - downloadMutation.mutate(row.original.id) }]} - onView={() => navigate(`/card-requisites/${row.original.id}`)} - onEdit={() => navigate(`/card-requisites/${row.original.id}/edit`)} - onDelete={() => setDeleteId(row.original.id)} - isDeleting={deleteMutation.isPending} - /> + [branchesInfiniteData, lang], + ); + + const [cardTypeSearch, setCardTypeSearch] = useState(""); + const { + data: cardTypesInfiniteData, + fetchNextPage: fetchNextCardTypes, + hasNextPage: hasNextCardTypes, + isFetchingNextPage: isFetchingNextCardTypes, + isLoading: isCardTypesLoading, + } = useInfiniteCardTypes(cardTypeSearch); + + const cardTypeOptions = useMemo( + () => + (cardTypesInfiniteData?.pages ?? []).flatMap((page) => + (page?.paymentCards ?? []).map((ct) => ({ + value: String(ct.id), + label: ct.title[lang] || ct.title.tm || String(ct.id), + })), ), - }, - ]; + [cardTypesInfiniteData, lang], + ); - // ── Column meta for toolbar ─────────────────────────────────────────────────── + const [userSearch, setUserSearch] = useState(""); + const { + data: clientsInfiniteData, + fetchNextPage: fetchNextClients, + hasNextPage: hasNextClients, + isFetchingNextPage: isFetchingNextClients, + isLoading: isClientsLoading, + } = useInfiniteClients(userSearch); - const columnMeta: ColumnMeta[] = columns - .filter((c) => c.id !== "actions") - .map((c) => ({ - id: c.id!, - label: typeof c.header === "string" ? c.header : c.id!, - })); + const clientOptions = useMemo( + () => + (clientsInfiniteData?.pages ?? []).flatMap((page) => + (page?.users ?? []).map((u) => ({ + value: String(u.id), + label: u.name || u.username || String(u.id), + })), + ), + [clientsInfiniteData], + ); - // ── Pagination ──────────────────────────────────────────────────────────────── + // ── Query params & data ───────────────────────────────────────────────────── - const total = data?.total ?? 0; - const totalPages = Math.ceil(total / perPage); + const queryParams = useMemo(() => { + const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value])); + return { + search: search || undefined, + status: filterMap.status || undefined, + region: filterMap.region || undefined, + branch_id: filterMap.branch_id ? Number(filterMap.branch_id) : undefined, + card_type_id: filterMap.card_type_id ? Number(filterMap.card_type_id) : undefined, + user_id: filterMap.user_id ? Number(filterMap.user_id) : undefined, + page, + limit: perPage, + }; + }, [search, activeFilters, page, perPage]); - const handleDelete = async () => { - if (!deleteId) return; - await deleteMutation.mutateAsync(deleteId); + const { data, isLoading } = useCardRequisites(queryParams); + const total = data?.count ?? 0; + const totalPages = Math.max(1, Math.ceil(total / perPage)); + + const regionOptions = useMemo(() => REGION_CODES.map((code) => ({ value: code, label: t(`loanOrders.regions.${code}`, code) })), [t]); + + const statusOptions = useMemo( + () => [ + { value: "pending", label: t("cardRequisites.status.pending", "Garaşylýar") }, + { value: "approved", label: t("cardRequisites.status.approved", "Tassyklanan") }, + { value: "rejected", label: t("cardRequisites.status.rejected", "Ret edilen") }, + ], + [t], + ); + + const handleFilterChange = useCallback((fieldId: string, value: string) => { + setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f))); + setPage(1); + }, []); + + const handleFilterReset = useCallback(() => { + setActiveFilters((prev) => prev.map((f) => ({ ...f, value: "" }))); + setPage(1); + }, []); + + const handleDelete = useCallback((id: number) => { + setDeleteId(id); + }, []); + + const confirmDelete = useCallback(() => { + if (deleteId === null) return; + deleteMutation.mutate(deleteId); setDeleteId(null); - }; + }, [deleteId, deleteMutation]); + + // ── Columns ───────────────────────────────────────────────────────────────── + + const columns = useMemo[]>( + () => [ + { + id: "id", + accessorKey: "id", + header: t("ID", "ID"), + cell: ({ row }) => ( + + ), + size: 70, + }, + { + id: "uniqueId", + accessorKey: "uniqueId", + header: t("Unique ID", "Unikal ID"), + cell: ({ row }) => {row.original.uniqueId || "—"}, + }, + { + id: "cardType", + accessorKey: "cardType", + header: t("Card type", "GÖRNÜŞI"), + cell: ({ row }) => ( + {resolveLocalizedName(row.original.cardType?.name, lang) || "—"} + ), + }, + { + id: "customer", + accessorKey: "customerName", + header: t("Customer", "MÜŞDERI"), + cell: ({ row }) => ( + + {row.original.customerSurname} {row.original.customerName} + + ), + }, + { + id: "user", + accessorKey: "user", + header: t("User", "ULANYJY"), + cell: ({ row }) => {row.original.user?.name || row.original.user?.username || "—"}, + }, + { + id: "region", + accessorKey: "region", + header: t("Region", "WELAÝAT"), + cell: ({ row }) => ( + + {row.original.region ? t(`loanOrders.regions.${row.original.region}`, row.original.region) : "—"} + + ), + size: 100, + }, + { + id: "branch", + accessorKey: "branch", + header: t("Branch", "ŞAHAMÇA"), + cell: ({ row }) => {resolveLocalizedName(row.original.branch?.name, lang) || "—"}, + }, + { + id: "status", + accessorKey: "status", + header: t("Status", "STATUS"), + cell: ({ row }) => , + size: 140, + }, + { + id: "actions", + header: "", + enableHiding: false, + cell: ({ row }) => ( + 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( + () => [ + { + 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 (
{/* Header */}
-

{t("Card requisites", "Kart rekwizitler")}

+

{t("cardRequisites.title", "Kart rekwizitler")}

+
navigate("/card-requisites/create")} />
+
{ setSearch(v); setPage(1); }} - searchPlaceholder={t("common.search", "Gözlemek")} - columns={columnMeta} + searchPlaceholder={t("cardRequisites.searchPlaceholder", "Gözlemek")} + columns={toggleableColumns} columnVisibility={columnVisibility} onColumnVisibilityChange={setColumnVisibility} columnOrder={columnOrder} onColumnOrderChange={setColumnOrder} - hideSearch - hideAction + filterFields={filterFields} + activeFilters={activeFilters} + onFilterChange={handleFilterChange} + onFilterReset={handleFilterReset} perPageOptions={[10, 25, 50, 100]} perPage={perPage} onPerPageChange={(v) => { @@ -190,29 +393,30 @@ export default function CardRequisitesPage() { {/* Table */} row.id} + getRowId={(row) => String(row.id)} currentPage={page} totalPages={totalPages} totalCount={total} onPageChange={setPage} />
+ {/* Delete dialog */} { if (!o) setDeleteId(null); }} - title={t("Are you sure?", "Eminsiňizmi?")} - description={t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.")} - onConfirm={handleDelete} + title={t("cardRequisites.deleteConfirm", "Bu sargyt pozulsynmy?")} + description={t("cardRequisites.deleteDescription", "Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.")} + onConfirm={confirmDelete} isLoading={deleteMutation.isPending} />
diff --git a/src/pages/cardDepartment/cardRequisitesEdit/index.tsx b/src/pages/cardDepartment/cardRequisitesEdit/index.tsx index 06eff86..2386a06 100644 --- a/src/pages/cardDepartment/cardRequisitesEdit/index.tsx +++ b/src/pages/cardDepartment/cardRequisitesEdit/index.tsx @@ -1,17 +1,18 @@ -import { useParams } from 'react-router-dom' -import { useTranslation } from 'react-i18next' -import { PageSpinner } from '@/components/pageSpinner' -import { PageError } from '@/components/pageError' -import { CardRequisiteForm } from '@/features/cardRequisites/components/cardRequisiteForm' -import { useCardRequisite } from '@/features/cardRequisites/hooks/useCardRequisites' +import { useParams } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { PageSpinner } from "@/components/pageSpinner"; +import { PageError } from "@/components/pageError"; +import { CardRequisiteForm } from "@/features/cardRequisites/components/cardRequisiteForm"; +import { useCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites"; export default function CardRequisiteEditPage() { - const { id } = useParams<{ id: string }>() - const { t } = useTranslation() - const { data, isLoading } = useCardRequisite(id ?? '') + const { id } = useParams<{ id: string }>(); + const { t } = useTranslation(); + const numericId = Number(id); + const { data, isLoading } = useCardRequisite(numericId); - if (isLoading) return - if (!data) return + if (isLoading) return ; + if (!data) return ; - return + return ; } diff --git a/src/pages/cardDepartment/cardRequisitesView/index.tsx b/src/pages/cardDepartment/cardRequisitesView/index.tsx index eb0392e..2f72b1b 100644 --- a/src/pages/cardDepartment/cardRequisitesView/index.tsx +++ b/src/pages/cardDepartment/cardRequisitesView/index.tsx @@ -1,10 +1,9 @@ +import { useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { useCardRequisite, useDeleteCardRequisite, useDownloadCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites"; -import type { CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi"; -import { Skeleton } from "@/components/ui/skeleton"; +import { ArrowLeft, Pencil, Trash2 } from "lucide-react"; import { Button } from "@/components/ui/button"; -import { Pencil, Trash2, Download } from "lucide-react"; +import { Skeleton } from "@/components/ui/skeleton"; import { AlertDialog, AlertDialogAction, @@ -15,6 +14,9 @@ import { AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; +import { useCardRequisite, useDeleteCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites"; +import type { CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi"; +import { resolveLocalizedName } from "@/features/cardRequisites/api/cardRequisitesApi"; import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge"; import { AlertCircle, CheckCircle2, XCircle } from "lucide-react"; import { BentoGrid, BentoCard, InfoRow, PassportImage } from "@/components/viewPageComponents"; @@ -33,12 +35,13 @@ const STATUS_ICON: Record = { rejected: XCircle, }; -function CardRequisiteStatusBadge({ status }: { status: CardRequisiteStatus }) { +function CardRequisiteStatusBadge({ status }: { status: string }) { const { t } = useTranslation(); - const variant = STATUS_VARIANT[status]; - const Icon = STATUS_ICON[status]; + const key = status as CardRequisiteStatus; + const variant = STATUS_VARIANT[key]; + const Icon = STATUS_ICON[key]; if (!variant) return {status}; - return ; + return ; } // ─── Skeleton ───────────────────────────────────────────────────────────────── @@ -61,6 +64,13 @@ function CardRequisiteViewSkeleton() { ); } +function formatDate(value?: string): string { + if (!value) return ""; + const d = new Date(value); + if (isNaN(d.getTime())) return value; + return d.toLocaleDateString(); +} + // ─── Page ───────────────────────────────────────────────────────────────────── export default function CardRequisiteViewPage() { @@ -68,9 +78,10 @@ export default function CardRequisiteViewPage() { const navigate = useNavigate(); const { t } = useTranslation(); - const { data, isLoading, isError } = useCardRequisite(id ?? ""); + const numericId = Number(id); + const { data, isLoading, isError } = useCardRequisite(numericId); const deleteMutation = useDeleteCardRequisite(); - const downloadMutation = useDownloadCardRequisite(); + const [deleteOpen, setDeleteOpen] = useState(false); if (isLoading) { return ; @@ -80,26 +91,29 @@ export default function CardRequisiteViewPage() { return
{t("common.notFound", "Maglumat tapylmady")}
; } + const fullName = [data.customerName, data.customerPatronicName, data.customerSurname].filter(Boolean).join(" "); + return (
{/* ── Page header ──────────────────────────────────────────────────── */}
-

- {t("cardRequisite.viewTitle", "Kart rekwizit giňişleýin")}: {data.id} -

-
- - +

+ {t("cardRequisite.viewTitle", "Kart rekwizit giňişleýin")}: {data.id} +

+
+
+ - @@ -133,60 +147,78 @@ export default function CardRequisiteViewPage() { - + + - - + - - - + + + + - - + + - {/* ── Row 2: Şahsy + Pasport maglumatlary ──────────────────────────── */} + {/* ── Row 2: Şahsy + Ulanyjy + Pasport maglumatlary ─────────────────── */} - - + + - - - + + + + - {/* ── Row 3: Passport images ────────────────────────────────────────── */} + {/* ── Row 3: Pasport maglumatlary ───────────────────────────────────── */} + + + + + + + + {/* ── Row 4: Passport images ────────────────────────────────────────── */} - + - + - + - +
diff --git a/src/pages/loanDepartment/loanOrderMobile/index.tsx b/src/pages/loanDepartment/loanOrderMobile/index.tsx index 26cc9f9..b13dc80 100644 --- a/src/pages/loanDepartment/loanOrderMobile/index.tsx +++ b/src/pages/loanDepartment/loanOrderMobile/index.tsx @@ -1,16 +1,18 @@ import { useState, useMemo, useCallback } from "react"; +import { useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; import { AlertCircle, CheckCircle2, XCircle, CheckCheck } from "lucide-react"; -import { useNavigate } from "react-router-dom"; import type { ColumnDef, VisibilityState } from "@tanstack/react-table"; -import { StatusBadge } from "@/components/ui/statusBadge"; + import { DataTable } from "@/components/dataTable"; import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar"; import { TableSearchInput } from "@/components/tableSearch"; import { CreateButton } from "@/components/createButton"; import { TableActions } from "@/components/tableActions"; +import { StatusBadge } from "@/components/ui/statusBadge"; import { useLoanOrderMobiles, useDeleteLoanOrderMobile } from "@/features/loanOrderMobiles/hooks/useLoanOrderMobiles"; import type { LoanOrderMobile, LoanOrderMobileStatus } from "@/features/loanOrderMobiles/api/loanOrderMobilesApi"; +import { useInfiniteBranches } from "@/features/branches/hooks/useBranches"; import { DeleteDialog } from "@/components/deleteDialog"; import { getStatusLabel, getStatusOptions, STATUS_BADGE_VARIANTS, type StatusValue } from "@/constants"; @@ -30,24 +32,43 @@ function LoanOrderStatusBadge({ status }: { status: LoanOrderMobileStatus }) { ); } -// ─── Column IDs ──────────────────────────────────────────────────────────────── +// ─── Column meta for toggle dropdown ───────────────────────────────────────── const COLUMN_IDS = ["id", "loanType", "createdAt", "region", "branch", "firstName", "lastName", "phone", "status"] as const; -// ─── Filter options ──────────────────────────────────────────────────────────── +// ─── Filter fields ──────────────────────────────────────────────────────────── -// ─── Filter options (Internal keys/values) ─────────────────────────────────── -const REGION_OPTIONS = ["Balkan", "Ahal", "Daşoguz", "Lebap", "Mary", "Aşgabat"]; +const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const; -// ─── Page Component ──────────────────────────────────────────────────────────── +// ─── Page Component ─────────────────────────────────────────────────────────── export default function LoanOrderMobilesPage() { - const { t } = useTranslation(); + const { t, i18n } = useTranslation(); + const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en"; const navigate = useNavigate(); const deleteMutation = useDeleteLoanOrderMobile(); const [deleteId, setDeleteId] = useState(null); - // ── State ────────────────────────────────────────────────────────────────── + const [branchSearch, setBranchSearch] = useState(""); + const { + data: branchesInfiniteData, + fetchNextPage: fetchNextBranches, + hasNextPage: hasNextBranches, + isFetchingNextPage: isFetchingNextBranches, + isLoading: isBranchesLoading, + } = useInfiniteBranches(branchSearch); + + const branchOptions = useMemo( + () => + (branchesInfiniteData?.pages ?? []).flatMap((page) => + (page?.branches ?? []).map((b) => ({ + value: String(b.id), + label: b.name[lang] || b.name.tm, + })), + ), + [branchesInfiniteData, lang], + ); + const [search, setSearch] = useState(""); const [page, setPage] = useState(1); const [perPage, setPerPage] = useState(25); @@ -60,7 +81,6 @@ export default function LoanOrderMobilesPage() { { fieldId: "archived", value: "" }, ]); - // ── Query params ─────────────────────────────────────────────────────────── const queryParams = useMemo(() => { const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value])); return { @@ -77,7 +97,8 @@ export default function LoanOrderMobilesPage() { const { data, isLoading } = useLoanOrderMobiles(queryParams); const totalPages = data ? Math.ceil(data.total / perPage) : 1; - // ── Handlers ─────────────────────────────────────────────────────────────── + const regionOptions = useMemo(() => REGION_CODES.map((code) => ({ value: code, label: t(`loanOrders.regions.${code}`, code) })), [t]); + const handleFilterChange = useCallback((fieldId: string, value: string) => { setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f))); setPage(1); @@ -98,68 +119,69 @@ export default function LoanOrderMobilesPage() { setDeleteId(null); }, [deleteId, deleteMutation]); - // ── Columns ──────────────────────────────────────────────────────────────── const columns = useMemo[]>( () => [ { id: "id", accessorKey: "id", - header: t("loanOrderMobiles.columns.id", "ID"), + header: t("ID", "ID"), cell: ({ row }) => {row.original.id}, size: 130, }, { id: "loanType", accessorKey: "loanType", - header: t("loanOrderMobiles.columns.loanType", "KARZ GÖRNÜŞI"), + header: t("Loan type", "KARZ GÖRNÜŞI"), cell: ({ row }) => {row.original.loanType}, }, { id: "createdAt", accessorKey: "createdAt", - header: t("loanOrderMobiles.columns.createdAt", "DÖREDILEN WAGTY"), + header: t("Created at", "DÖREDILEN WAGTY"), cell: ({ row }) => {row.original.createdAt}, size: 160, }, { id: "region", accessorKey: "region", - header: t("loanOrderMobiles.columns.region", "WELAÝAT"), - cell: ({ row }) => {row.original.region}, + header: t("Region", "WELAÝAT"), + cell: ({ row }) => ( + {t(`loanOrders.regions.${row.original.region}`, row.original.region)} + ), size: 100, }, { id: "branch", accessorKey: "branch", - header: t("loanOrderMobiles.columns.branch", "ŞAHAMÇA"), + header: t("Branch", "ŞAHAMÇA"), cell: ({ row }) => {row.original.branch}, size: 100, }, { id: "firstName", accessorKey: "firstName", - header: t("loanOrderMobiles.columns.firstName", "ADY"), + header: t("Name", "ADY"), cell: ({ row }) => {row.original.firstName}, size: 110, }, { id: "lastName", accessorKey: "lastName", - header: t("loanOrderMobiles.columns.lastName", "FAMILIÝASY"), + header: t("Surname", "FAMILIÝASY"), cell: ({ row }) => {row.original.lastName}, size: 120, }, { id: "phone", accessorKey: "phone", - header: t("loanOrderMobiles.columns.phone", "TELEFON"), + header: t("Phone", "TELEFON"), cell: ({ row }) => {row.original.phone}, size: 110, }, { id: "status", accessorKey: "status", - header: t("loanOrderMobiles.columns.status", "STATUS"), + header: t("Status", "STATUS"), cell: ({ row }) => , size: 180, }, @@ -178,47 +200,51 @@ export default function LoanOrderMobilesPage() { size: 100, }, ], - [t, handleDelete, deleteMutation.isPending, navigate], + [t, navigate, handleDelete, deleteMutation.isPending], ); - // ── Column meta for toolbar ──────────────────────────────────────────────── - const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`loanOrderMobiles.columns.${id}`, id) })), [t]); + const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`loanOrders.columns.${id}`, id) })), [t]); const filterFields = useMemo( () => [ { id: "region", - label: t("loanOrderMobiles.filters.region", "WELAÝAT"), - options: REGION_OPTIONS.map((v) => ({ value: v, label: t(v) })), + label: t("Region", "WELAÝAT"), + options: regionOptions, }, { id: "status", - label: t("loanOrderMobiles.filters.status", "STATUS"), + label: t("Status", "STATUS"), options: getStatusOptions(t, "loanOrderStatus"), }, { id: "branch", - label: t("loanOrderMobiles.filters.branch", "ŞAHAMÇA"), - options: [], + label: t("Branch", "ŞAHAMÇA"), + type: "infinite-select", + options: branchOptions, + loading: isBranchesLoading, + isLoadingMore: isFetchingNextBranches, + hasNextPage: hasNextBranches, + onLoadMore: fetchNextBranches, + searchValue: branchSearch, + onSearchChange: setBranchSearch, }, { id: "archived", - label: t("loanOrderMobiles.filters.archived", "ARHIWLENEN"), + label: t("loanOrders.filters.archived", "ARHIWLENEN"), options: [ { value: "true", label: t("common.yes", "Hawa") }, { value: "false", label: t("common.no", "Ýok") }, ], }, ], - [t], + [t, regionOptions, branchOptions, isBranchesLoading, isFetchingNextBranches, hasNextBranches, branchSearch], ); - // ────────────────────────────────────────────────────────────────────────── return (
- {/* Page Header */}
-

{t("loanOrderMobiles.title", "Karz sargytlary")}

+

{t("loanOrderMobiles.title", "Karz sargytlary (Mobile)")}

@@ -228,23 +254,24 @@ export default function LoanOrderMobilesPage() { setSearch(v); setPage(1); }} - placeholder={t("common.search", "Gözlemek")} + placeholder={t("loanOrderMobiles.searchPlaceholder", "Gözlemek")} /> navigate("/loan-order-mobiles/create")} />
- {/* Table Card */}
{ setSearch(v); setPage(1); }} - searchPlaceholder={t("common.search", "Gözlemek")} + searchPlaceholder={t("loanOrderMobiles.searchPlaceholder", "Gözlemek")} columns={toggleableColumns} columnVisibility={columnVisibility} onColumnVisibilityChange={setColumnVisibility} @@ -260,8 +287,6 @@ export default function LoanOrderMobilesPage() { setPerPage(v); setPage(1); }} - hideSearch - hideAction /> - — + {permissions.length > 0 ? ( +
+ {permissions.map((p) => ( + + + {p.name || p.code || p.id} + + ))} +
+ ) : ( + — + )}
@@ -336,26 +352,31 @@ const ASSIGN_DIALOG_FIELD_LABELS: Record = { }; /** - * Dialog for assigning a role / permission / branch to a staff user. - * Two selects: target user (GET /users/staff) and the resource to assign. + * Dialog for assigning a role / branch to a staff user, or assigning a permission to a role. */ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () => void }) { const { t, i18n } = useTranslation(); const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText; - const [userSearch, setUserSearch] = useState(""); - const [userValue, setUserValue] = useState(""); + const isPermission = kind === "permission"; + + const [targetSearch, setTargetSearch] = useState(""); + const [targetValue, setTargetValue] = useState(""); const [resourceSearch, setResourceSearch] = useState(""); const [resourceValue, setResourceValue] = useState(""); const [error, setError] = useState(); - const staffQuery = useInfiniteStaff(userSearch); + // Target query: Staff users when assigning role/branch to a user; Roles when assigning permission to a role. + const staffQuery = useInfiniteStaff(targetSearch); + const targetRolesQuery = useInfiniteRoles(targetSearch, isPermission); + + // Resource query: const rolesQuery = useInfiniteRoles(resourceSearch, kind === "role"); const permissionsQuery = useInfinitePermissions(resourceSearch, kind === "permission"); const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch"); const roleMutation = useAssignRoleToUser(); - const permissionMutation = useAssignPermissionToUser(); + const permissionMutation = useAssignPermissionToRole(); const branchMutation = useAssignBranchToUser(); const isPending = roleMutation.isPending || permissionMutation.isPending || branchMutation.isPending; @@ -370,6 +391,24 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () = [staffQuery.data], ); + const targetRoleOptions: InfiniteSelectOption[] = useMemo( + () => + (targetRolesQuery.data?.pages ?? []) + .flatMap((p) => p?.roles ?? []) + .map((r) => ({ value: String(r.id), label: r.name || r.code || String(r.id) })), + [targetRolesQuery.data], + ); + + const targetOptions = isPermission ? targetRoleOptions : staffOptions; + const targetLabel = isPermission ? t("users.fields.role", "Rol") : t("profile.assign.userLabel", "Ulanyjy (staff)"); + const targetLoading = isPermission ? targetRolesQuery.isLoading : staffQuery.isLoading; + const targetLoadingMore = isPermission ? targetRolesQuery.isFetchingNextPage : staffQuery.isFetchingNextPage; + const targetHasNextPage = isPermission ? !!targetRolesQuery.hasNextPage : !!staffQuery.hasNextPage; + const loadMoreTargets = () => { + if (isPermission) targetRolesQuery.fetchNextPage(); + else staffQuery.fetchNextPage(); + }; + const resourceOptions: InfiniteSelectOption[] = useMemo(() => { if (kind === "role") { return (rolesQuery.data?.pages ?? []) @@ -406,23 +445,23 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () = }; const handleSubmit = () => { - if (!userValue || !resourceValue) { + if (!targetValue || !resourceValue) { setError(t("common.errors.required", "Meýdança hökmany doldurylmaly")); return; } setError(undefined); - const userId = Number(userValue); - const resourceId = Number(resourceValue); + const firstId = Number(targetValue); + const secondId = Number(resourceValue); const onSuccess = () => { - setUserValue(""); + setTargetValue(""); setResourceValue(""); onClose(); }; - if (kind === "role") roleMutation.mutate({ userId, roleId: resourceId }, { onSuccess }); - else if (kind === "permission") permissionMutation.mutate({ userId, permissionId: resourceId }, { onSuccess }); - else branchMutation.mutate({ userId, branchId: resourceId }, { onSuccess }); + if (kind === "role") roleMutation.mutate({ userId: firstId, roleId: secondId }, { onSuccess }); + else if (kind === "permission") permissionMutation.mutate({ roleId: firstId, permissionId: secondId }, { onSuccess }); + else branchMutation.mutate({ userId: firstId, branchId: secondId }, { onSuccess }); }; return ( @@ -438,20 +477,20 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
{ - setUserValue(v); + setTargetValue(v); if (error) setError(undefined); }} - options={staffOptions} + options={targetOptions} placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} - loading={staffQuery.isLoading} - isLoadingMore={staffQuery.isFetchingNextPage} - hasNextPage={!!staffQuery.hasNextPage} - onLoadMore={() => staffQuery.fetchNextPage()} - searchValue={userSearch} - onSearchChange={setUserSearch} + loading={targetLoading} + isLoadingMore={targetLoadingMore} + hasNextPage={targetHasNextPage} + onLoadMore={loadMoreTargets} + searchValue={targetSearch} + onSearchChange={setTargetSearch} /> {t("common.cancel", "Yza")} -