connected with loan order api

This commit is contained in:
Jelaletdin12
2026-08-19 22:09:39 +05:00
parent 7bb37f9b43
commit 73142c1fcf
19 changed files with 1234 additions and 476 deletions

View File

@@ -1,4 +1,4 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQuery, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
@@ -10,6 +10,7 @@ export const userKeys = {
list: (params: UsersListParams) => [...userKeys.lists(), params] as const,
details: () => [...userKeys.all, "detail"] as const,
detail: (id: number) => [...userKeys.details(), id] as const,
infinite: (search: string) => [...userKeys.all, "infinite", search] as const,
};
export function useUsers(params: UsersListParams = {}) {
@@ -23,6 +24,23 @@ export function useUsers(params: UsersListParams = {}) {
});
}
const USER_PAGE_SIZE = 25;
export function useInfiniteUsers(search = "") {
const debouncedSearch = useDebouncedValue(search);
const effectiveSearch = normalizeSearch(debouncedSearch);
return useInfiniteQuery({
queryKey: userKeys.infinite(effectiveSearch),
initialPageParam: 1,
queryFn: ({ pageParam, signal }) => usersApi.getUsers({ page: pageParam, limit: USER_PAGE_SIZE, search: effectiveSearch }, signal),
getNextPageParam: (lastPage, allPages) => {
const loaded = allPages.reduce((sum, p) => sum + p.users.length, 0);
return loaded < lastPage.count ? allPages.length + 1 : undefined;
},
});
}
export function useUser(id: number) {
return useQuery({
queryKey: userKeys.detail(id),

View File

@@ -1,6 +1,10 @@
import type { StatusValue } from "@/constants";
import apiClient from "@/lib/api/client";
import i18next from "i18next";
import { formatFromApiDate, formatToApiDate, formatFromApiPhone, formatToApiPhone } from "@/lib/utils";
import { isStatusValue, type StatusValue } from "@/constants";
import type { LocalizedText } from "@/features/branches/api/branchesApi";
// ─── Types ────────────────────────────────────────────────────────────────────
// ─── Types (UI-facing) ─────────────────────────────────────────────────────────
export type LoanOrderStatus = StatusValue;
@@ -67,6 +71,17 @@ export interface LoanOrder {
guarantor1CardExpYear?: string | null;
guarantor1Salary?: number | null;
guarantor2Name?: string | null;
guarantor2Surname?: string | null;
guarantor2Patronic?: string | null;
guarantor2PassportSerie?: string | null;
guarantor2PassportNumber?: string | null;
guarantor2CardNumber?: string | null;
guarantor2CardName?: string | null;
guarantor2CardExpMonth?: string | null;
guarantor2CardExpYear?: string | null;
guarantor2Note?: string | null;
amount?: number | null;
createdBy?: string | null;
fullName?: string | null;
@@ -149,218 +164,321 @@ export interface LoanOrderPayload {
guarantor1CardExpMonth?: string;
guarantor1CardExpYear?: string;
guarantor1Salary?: number;
guarantor2Name?: string;
guarantor2Surname?: string;
guarantor2Patronic?: string;
guarantor2PassportSerie?: string;
guarantor2PassportNumber?: string;
guarantor2CardNumber?: string;
guarantor2CardName?: string;
guarantor2CardExpMonth?: string;
guarantor2CardExpYear?: string;
guarantor2Note?: string;
passportOne?: string;
passportTwo?: string;
passportThree?: string;
passportFour?: string;
}
// ─── Mock ─────────────────────────────────────────────────────────────────────
// ─── Backend types ─────────────────────────────────────────────────────────────
const MOCK_DATA: LoanOrder[] = [
{
id: "L-1001",
loanType: "Ipoteka karzy",
createdAt: "2024-03-20 10:30",
region: "Aşgabat",
branch: "Merkezi şahamça",
createdBy: "Nurtuwak",
branchId: 1,
loanTypeId: 1,
workCityId: 1,
createdById: "5970",
firstName: "Aman",
lastName: "Amanow",
phone: "+993 65 112233",
status: "pending",
note: "Müşderi dokumentleri tassyklamady",
loanAmount: 50000,
loanHistory: "positive",
patronicName: "Myradowiç",
education: "high",
marriageStatus: "MARRIED",
dateOfBirth: "1990-05-15",
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: "aman.amanow@email.com",
phoneAdditional: "+993 65 334455",
homePhone: "+993 12 456789",
workCompany: "Türkmennebit",
workHrPhone: "+993 12 987654",
workRegion: "Aşgabat",
workProvince: "Büzmeýin etraby",
position: "Inžener",
salary: 2500,
workStartedAt: "2018-06-01",
cardNumber: "4111111111111111",
cardName: "AMAN AMANOW",
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: "L-1002",
loanType: "Sarp ediş karzy",
createdAt: "2024-03-19 14:15",
region: "Mary",
branch: "Mary-1 şahamçasy",
branchId: 2,
loanTypeId: 2,
workCityId: 5,
createdById: "U-1002",
firstName: "Oguljan",
lastName: "Berdiýewa",
phone: "+993 61 445566",
status: "pending",
note: null,
loanAmount: 10000,
loanHistory: "new",
patronicName: "Myratowna",
education: "masters",
marriageStatus: "SINGLE",
dateOfBirth: "1995-11-20",
residence: "Mary şäher, Gurbansoltan eje köçesi, 10",
currentResidence: "Mary şäher, Gurbansoltan eje köçesi, 10",
passportSerie: "I-MR",
passportNumber: "789012",
passportDateOfIssue: "2018-07-22",
passportGivenBy: "Mary şäheriniň Içeri işler müdirligi",
bornPlace: "Mary şäheri",
email: "oguljan.berdiýewa@email.com",
phoneAdditional: null,
homePhone: null,
workCompany: "Mary ýangyn söndüriş bölümi",
workHrPhone: "+993 55 112233",
workRegion: "Mary",
workProvince: "Mary şäher",
position: "Hasapçy",
salary: 1800,
workStartedAt: "2019-03-15",
cardNumber: "4333333333333333",
cardName: "OGULJAN BERDIÝEWA",
cardExpMonth: "09",
cardExpYear: "2028",
guarantor1Name: "Merdan",
guarantor1Surname: "Merdanow",
guarantor1Patronic: "Amanowiç",
guarantor1PassportSerie: "I-AH",
guarantor1PassportNumber: "345678",
guarantor1CardNumber: "4444444444444444",
guarantor1CardName: "MERDAN MERDANOW",
guarantor1CardExpMonth: "03",
guarantor1CardExpYear: "2025",
guarantor1Salary: 2200,
},
];
interface BackendLoanOrder {
id?: number | string;
uniqueId?: string | null;
region?: string | null;
branchId?: number | null;
branchName?: LocalizedText | string | null;
loanType?: number | string | null;
loanTypeName?: LocalizedText | string | null;
userId?: number | null;
userName?: string | null;
customerName?: string | null;
customerSurname?: string | null;
customerPatronicName?: string | null;
bornAt?: string | null;
bornPlace?: string | null;
education?: string | null;
marriageStatus?: string | null;
email?: string | null;
status?: string | null;
notes?: string | null;
createdAt?: string | null;
updatedAt?: string | null;
loanAmount?: string | number | null;
cardNumber?: string | null;
cardName?: string | null;
cardMonth?: string | null;
cardYear?: string | null;
loanCardNumber?: string | null;
loanCardName?: string | null;
loanCardMonth?: string | null;
loanCardYear?: string | null;
passportSerie?: string | null;
passportId?: string | null;
passportGivenAt?: string | null;
passportGivenBy?: string | null;
passportAddress?: string | null;
realAddress?: string | null;
passportOne?: string | null;
passportTwo?: string | null;
passportThree?: string | null;
passportFour?: string | null;
phone?: string | null;
phoneHome?: string | null;
phoneAdditional?: string | null;
workCompany?: string | null;
workCompanyAccountantNumber?: string | null;
workRegion?: string | null;
workProvinceId?: number | null;
workProvinceName?: LocalizedText | string | null;
workSalary?: string | number | null;
workPosition?: string | null;
workStartedAt?: string | null;
satisfiable?: string | null;
source?: string | null;
loanOrderRequiredDocId?: number | null;
guarantorName?: string | null;
guarantorSurname?: string | null;
guarantorPatronicName?: string | null;
guarantorPassportSerie?: string | null;
guarantorPassportId?: string | null;
guarantorCardNumber?: string | null;
guarantorCardName?: string | null;
guarantorCardMonth?: string | null;
guarantorCardYear?: string | null;
guarantorNote?: string | null;
guarantor2Name?: string | null;
guarantor2Surname?: string | null;
guarantor2PatronicName?: string | null;
guarantor2PassportSerie?: string | null;
guarantor2PassportId?: string | null;
guarantor2CardNumber?: string | null;
guarantor2CardName?: string | null;
guarantor2CardMonth?: string | null;
guarantor2CardYear?: string | null;
guarantor2Note?: string | null;
}
let mockStore = [...MOCK_DATA];
let nextId = 1003;
interface LoanOrdersListResponse {
count: number;
loanOrders: BackendLoanOrder[];
}
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms));
// ─── Mapping helpers ───────────────────────────────────────────────────────────
// ─── API Functions ────────────────────────────────────────────────────────────
function resolveLocalizedName(name: LocalizedText | string | null | undefined): string {
if (!name) return "";
if (typeof name === "string") return name;
const lang = i18next.language || "en";
const key = lang === "tk" ? "tm" : (lang as keyof LocalizedText) in name ? lang : "en";
return name[key as keyof LocalizedText] ?? name.tm ?? name.en ?? name.ru ?? "";
}
export async function fetchLoanOrders(params: LoanOrdersParams): Promise<LoanOrdersResponse> {
await delay(600);
const page = params.page || 1;
const perPage = params.perPage || 25;
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;
}
let filtered = mockStore.filter((item) => {
const matchSearch =
!params.search ||
`${item.firstName} ${item.lastName}`.toLowerCase().includes(params.search.toLowerCase()) ||
item.id.toLowerCase().includes(params.search.toLowerCase()) ||
item.phone.includes(params.search);
const matchStatus = !params.status ? true : item.status === params.status;
const matchRegion = !params.region ? true : item.region === params.region;
const matchBranch = !params.branch ? true : item.branch === params.branch;
return matchSearch && matchStatus && matchRegion && matchBranch;
function mapBackendToUI(order: BackendLoanOrder): LoanOrder {
const rawStatus = order.status ?? "";
const status: LoanOrderStatus = isStatusValue(rawStatus) ? rawStatus : "pending";
return {
id: String(order.id ?? order.uniqueId ?? ""),
loanType: resolveLocalizedName(order.loanTypeName) || (order.loanType != null ? String(order.loanType) : ""),
createdAt: order.createdAt ?? "",
region: order.region ?? "",
branch: resolveLocalizedName(order.branchName),
branchId: order.branchId ?? undefined,
loanTypeId: order.loanType ?? undefined,
workCityId: order.workProvinceId ?? undefined,
createdById: order.userId ?? undefined,
firstName: order.customerName ?? "",
lastName: order.customerSurname ?? "",
patronicName: order.customerPatronicName ?? "",
phone: formatFromApiPhone(order.phone ?? order.phoneHome ?? ""),
homePhone: formatFromApiPhone(order.phoneHome),
phoneAdditional: formatFromApiPhone(order.phoneAdditional),
status,
note: order.notes ?? "",
loanAmount: toNum(order.loanAmount),
dateOfBirth: formatFromApiDate(order.bornAt),
bornPlace: order.bornPlace ?? "",
education: order.education ?? "",
marriageStatus: order.marriageStatus ?? "",
residence: order.passportAddress ?? "",
currentResidence: order.realAddress ?? "",
email: order.email ?? "",
passportSerie: order.passportSerie ?? "",
passportNumber: order.passportId ?? "",
passportDateOfIssue: formatFromApiDate(order.passportGivenAt),
passportGivenBy: order.passportGivenBy ?? "",
passportPage1Url: order.passportOne ?? "",
passportPage23Url: order.passportTwo ?? "",
passportPage89Url: order.passportThree ?? "",
passportPage32Url: order.passportFour ?? "",
workCompany: order.workCompany ?? "",
workHrPhone: formatFromApiPhone(order.workCompanyAccountantNumber),
workRegion: order.workRegion ?? "",
workProvince: resolveLocalizedName(order.workProvinceName),
workCity: resolveLocalizedName(order.workProvinceName),
salary: toNum(order.workSalary),
position: order.workPosition ?? "",
workStartedAt: formatFromApiDate(order.workStartedAt),
cardNumber: order.cardNumber ?? order.loanCardNumber ?? "",
cardName: order.cardName ?? order.loanCardName ?? "",
cardExpMonth: order.cardMonth ?? order.loanCardMonth ?? "",
cardExpYear: order.cardYear ?? order.loanCardYear ?? "",
guarantor1Name: order.guarantorName ?? "",
guarantor1Surname: order.guarantorSurname ?? "",
guarantor1Patronic: order.guarantorPatronicName ?? "",
guarantor1PassportSerie: order.guarantorPassportSerie ?? "",
guarantor1PassportNumber: order.guarantorPassportId ?? "",
guarantor1CardNumber: order.guarantorCardNumber ?? "",
guarantor1CardName: order.guarantorCardName ?? "",
guarantor1CardExpMonth: order.guarantorCardMonth ?? "",
guarantor1CardExpYear: order.guarantorCardYear ?? "",
guarantor1Salary: null,
guarantor2Name: order.guarantor2Name ?? "",
guarantor2Surname: order.guarantor2Surname ?? "",
guarantor2Patronic: order.guarantor2PatronicName ?? "",
guarantor2PassportSerie: order.guarantor2PassportSerie ?? "",
guarantor2PassportNumber: order.guarantor2PassportId ?? "",
guarantor2CardNumber: order.guarantor2CardNumber ?? "",
guarantor2CardName: order.guarantor2CardName ?? "",
guarantor2CardExpMonth: order.guarantor2CardMonth ?? "",
guarantor2CardExpYear: order.guarantor2CardYear ?? "",
guarantor2Note: order.guarantor2Note ?? "",
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 ?? "",
};
}
function mapPayloadToBackend(payload: LoanOrderPayload | Partial<LoanOrderPayload>): Record<string, unknown> {
return {
customerName: payload.firstName ?? "",
customerSurname: payload.lastName ?? "",
customerPatronicName: payload.patronicName || "",
branchId: toNum(payload.branch),
loanType: toNum(payload.loanType),
region: payload.region ?? "",
education: payload.education || "",
marriageStatus: payload.marriageStatus || "",
bornAt: formatToApiDate(payload.dateOfBirth),
bornPlace: payload.bornPlace || "",
passportAddress: payload.residence || "",
realAddress: payload.currentResidence || "",
passportSerie: payload.passportSerie || "",
passportId: payload.passportNumber || "",
passportGivenAt: formatToApiDate(payload.passportDateOfIssue),
passportGivenBy: payload.passportGivenBy || "",
email: payload.email || "",
phone: formatToApiPhone(payload.phone),
phoneAdditional: formatToApiPhone(payload.phoneAdditional),
phoneHome: formatToApiPhone(payload.homePhone),
workCompany: payload.workCompany || "",
workCompanyAccountantNumber: formatToApiPhone(payload.workHrPhone),
workRegion: payload.workRegion || "",
workProvinceId: toNum(payload.workProvince),
workSalary: payload.salary != null ? String(payload.salary) : "",
workPosition: payload.position || "",
workStartedAt: formatToApiDate(payload.workStartedAt),
loanAmount: payload.loanAmount != null ? String(payload.loanAmount) : "",
cardNumber: payload.cardNumber || "",
cardName: payload.cardName || "",
cardMonth: payload.cardExpMonth || "",
cardYear: payload.cardExpYear || "",
loanCardNumber: payload.cardNumber || "",
loanCardName: payload.cardName || "",
loanCardMonth: payload.cardExpMonth || "",
loanCardYear: payload.cardExpYear || "",
guarantorName: payload.guarantor1Name || "",
guarantorSurname: payload.guarantor1Surname || "",
guarantorPatronicName: payload.guarantor1Patronic || "",
guarantorPassportSerie: payload.guarantor1PassportSerie || "",
guarantorPassportId: payload.guarantor1PassportNumber || "",
guarantorCardNumber: payload.guarantor1CardNumber || "",
guarantorCardName: payload.guarantor1CardName || "",
guarantorCardMonth: payload.guarantor1CardExpMonth || "",
guarantorCardYear: payload.guarantor1CardExpYear || "",
guarantorNote: "",
guarantor2Name: payload.guarantor2Name || "",
guarantor2Surname: payload.guarantor2Surname || "",
guarantor2PatronicName: payload.guarantor2Patronic || "",
guarantor2PassportSerie: payload.guarantor2PassportSerie || "",
guarantor2PassportId: payload.guarantor2PassportNumber || "",
guarantor2CardNumber: payload.guarantor2CardNumber || "",
guarantor2CardName: payload.guarantor2CardName || "",
guarantor2CardMonth: payload.guarantor2CardExpMonth || "",
guarantor2CardYear: payload.guarantor2CardExpYear || "",
guarantor2Note: payload.guarantor2Note || "",
notes: payload.note || "",
passportOne: payload.passportOne || "",
passportTwo: payload.passportTwo || "",
passportThree: payload.passportThree || "",
passportFour: payload.passportFour || "",
status: payload.status ?? "pending",
satisfiable: "yes",
source: "web",
loanOrderRequiredDocId: 0,
userId: 0,
uniqueId: "",
};
}
// ─── API Functions ─────────────────────────────────────────────────────────────
export async function fetchLoanOrders(params: LoanOrdersParams = {}, signal?: AbortSignal): Promise<LoanOrdersResponse> {
const { page, perPage, search, region, status, branch, archived } = params;
const { data } = await apiClient.get<LoanOrdersListResponse>("/loan-orders", {
params: {
page: page ?? 1,
limit: perPage ?? 25,
search: search || undefined,
region: region || undefined,
status: status || undefined,
branch_id: branch || undefined,
archived: archived || undefined,
},
signal,
});
filtered = [...filtered].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
const total = filtered.length;
const start = (page - 1) * perPage;
const data = filtered.slice(start, start + perPage);
return { data, total, page, perPage };
const orders = (data.loanOrders ?? []).map(mapBackendToUI);
return {
data: orders,
total: data.count ?? orders.length,
page: page ?? 1,
perPage: perPage ?? 25,
};
}
export async function getLoanOrderById(id: string): Promise<LoanOrder> {
await delay(300);
const item = mockStore.find((o) => o.id === id);
if (!item) throw new Error("Not found");
return { ...item };
const { data } = await apiClient.get<BackendLoanOrder>(`/loan-orders/${id}`);
return mapBackendToUI(data);
}
export async function createLoanOrder(payload: LoanOrderPayload): Promise<LoanOrder> {
await delay(500);
const newItem = {
id: `L-${nextId++}`,
createdAt: new Date().toISOString().slice(0, 16).replace("T", " "),
...payload,
} as LoanOrder;
mockStore = [newItem, ...mockStore];
return newItem;
const { data } = await apiClient.post<BackendLoanOrder>("/loan-orders", mapPayloadToBackend(payload));
return mapBackendToUI(data);
}
export async function updateLoanOrder(id: string, payload: Partial<LoanOrderPayload>): Promise<LoanOrder> {
await delay(500);
const idx = mockStore.findIndex((o) => o.id === id);
if (idx === -1) throw new Error("Not found");
const updated = { ...mockStore[idx], ...payload } as LoanOrder;
mockStore = mockStore.map((o) => (o.id === id ? updated : o));
return updated;
const { data } = await apiClient.put<BackendLoanOrder>(`/loan-orders/${id}`, mapPayloadToBackend(payload));
return mapBackendToUI(data);
}
export async function deleteLoanOrder(id: string): Promise<void> {
await delay(300);
mockStore = mockStore.filter((o) => o.id !== id);
await apiClient.delete(`/loan-orders/${id}`);
}
// ─── Branch options by region ─────────────────────────────────────────────────
export const BRANCHES_BY_REGION: Record<string, { value: string; label: string }[]> = {
Aşgabat: [
{ value: "Merkezi şahamça", label: "Merkezi şahamça" },
{ 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" },
{ value: "Aşgabat-2 şahamçasy", label: "Aşgabat-2 şahamçasy" },
],
Ahal: [
{ value: "Änew şahamçasy", label: "Änew şahamçasy" },
{ value: "Gökdepe şahamçasy", label: "Gökdepe şahamçasy" },
{ value: "Tejen şahamçasy", label: "Tejen şahamçasy" },
],
Balkan: [
{ value: "Balkanabat şahamçasy", label: "Balkanabat şahamçasy" },
{ value: "Türkmenbaşy şahamçasy", label: "Türkmenbaşy şahamçasy" },
{ value: "Bereket şahamçasy", label: "Bereket şahamçasy" },
],
Daşoguz: [
{ value: "Daşoguz şahamçasy", label: "Daşoguz şahamçasy" },
{ value: "Akdepe şahamçasy", label: "Akdepe şahamçasy" },
{ value: "Boldumsaz şahamçasy", label: "Boldumsaz şahamçasy" },
],
Lebap: [
{ value: "Türkmenabat şahamçasy", label: "Türkmenabat şahamçasy" },
{ value: "Seýdi şahamçasy", label: "Seýdi şahamçasy" },
{ value: "Kerki şahamçasy", label: "Kerki şahamçasy" },
],
Mary: [
{ value: "Mary-1 şahamçasy", label: "Mary-1 şahamçasy" },
{ value: "Mary-2 şahamçasy", label: "Mary-2 şahamçasy" },
{ value: "Baýramaly şahamçasy", label: "Baýramaly şahamçasy" },
],
Arkadag: [{ value: "Arkadag şahamçasy", label: "Arkadag şahamçasy" }],
};

View File

@@ -4,31 +4,42 @@ import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { CircleDot, CreditCard, MapPin, User, Wallet, FileText, Phone, Briefcase, FolderOpen, ShieldCheck } from "lucide-react";
import { CircleDot, CreditCard, MapPin, User, Wallet, 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 { FormActions } from "@/components/formActions";
import { DocumentUpload } from "@/components/documentUpload";
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
import { BentoGrid, BentoCard } from "@/components/bento";
import { useCreateLoanOrder, useUpdateLoanOrder } from "@/features/loanOrders/hooks/useLoanOrders";
import type { LoanOrder } from "@/features/loanOrders/api/loanOrdersApi";
import { BRANCHES_BY_REGION } from "@/features/loanOrders/api/loanOrdersApi";
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "@/features/loanOrders/schemas/loanOrder.schema";
import type { LoanOrderFormData } from "@/features/loanOrders/schemas/loanOrder.schema";
import { useInfiniteLoanTypes } from "@/features/loanTypes/hooks/useLoanTypes";
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
import { useInfiniteProvinces } from "@/features/branches/hooks/useBranches";
import type { LocalizedText } from "@/features/branches/api/branchesApi";
import { formatFromApiDate, formatFromApiPhone } from "@/lib/utils";
import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants";
// ─── 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;
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 ?? "";
}
function getRegionOptions(t: TFunction): SelectOption[] {
return REGION_CODES.map((code) => ({
value: code,
label: t(`loanOrders.regions.${code}`, code),
}));
}
const EDUCATION_OPTIONS = [
{ value: "high", label: "Ýokary bilim" },
@@ -48,14 +59,6 @@ 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) => ({
value: String(i + 1).padStart(2, "0"),
label: String(i + 1).padStart(2, "0"),
@@ -142,7 +145,7 @@ const STEPS: StepDef[] = [
titleKey: "Passport",
titleFallback: "Pasport",
subtitleKey: "loanOrderForm.steps.passport.subtitle",
subtitleFallback: "Seriýa, belgisi, senesi",
subtitleFallback: "Seriýa, belgisi, senesi, suratlar",
icon: FileText,
validate: (form, mode) => validateStep(5, form, mode),
},
@@ -164,15 +167,6 @@ const STEPS: StepDef[] = [
icon: Briefcase,
validate: (form, mode) => validateStep(7, form, mode),
},
{
id: "files",
titleKey: "Passport files",
titleFallback: "Pasport faýllar",
subtitleKey: "loanOrderForm.steps.files.subtitle",
subtitleFallback: "Pasport suratlary",
icon: FolderOpen,
validate: (form, mode) => validateStep(8, form, mode),
},
{
id: "guarantor",
titleKey: "1. Guarantor",
@@ -180,6 +174,15 @@ const STEPS: StepDef[] = [
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),
},
];
@@ -227,19 +230,40 @@ function StepStatus({ form, errors, set, t }: StepContentProps) {
);
}
function StepLoan({ form, errors, set, t }: StepContentProps) {
function StepLoan({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrder }) {
const { i18n } = useTranslation();
const [loanTypeSearch, setLoanTypeSearch] = useState("");
const loanTypesQuery = useInfiniteLoanTypes(loanTypeSearch);
const loanTypeOptions: InfiniteSelectOption[] = useMemo(() => {
const lang = i18n.language ?? "en";
const opts: InfiniteSelectOption[] = (loanTypesQuery.data?.pages ?? [])
.flatMap((p) => p.loanTypes)
.map((lt) => ({ value: String(lt.id), label: resolveLocalizedName(lt.title, lang) || 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, i18n.language, initialData]);
return (
<BentoGrid cols={2}>
<BentoCard>
<FormInput
type="searchable-select"
<InfiniteSelect
label={t("Loan type") || "Karz görnüşi"}
required
value={form.loanType}
onChange={(v) => set("loanType", v)}
options={LOAN_TYPE_OPTIONS}
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}
/>
</BentoCard>
@@ -258,8 +282,27 @@ function StepLoan({ form, errors, set, t }: StepContentProps) {
);
}
function StepLocation({ form, errors, set, t }: StepContentProps) {
const branchOptions = BRANCHES_BY_REGION[form.region] ?? [];
function StepLocation({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrder }) {
const { i18n } = useTranslation();
const [branchSearch, setBranchSearch] = useState("");
const branchQuery = useInfiniteBranches(branchSearch);
const regionOptions = useMemo(() => getRegionOptions(t), [t]);
const branchOptions: InfiniteSelectOption[] = useMemo(() => {
const lang = i18n.language ?? "en";
const opts: InfiniteSelectOption[] = (branchQuery.data?.pages ?? [])
.flatMap((p) => p.branches)
.map((b) => ({
value: String(b.id),
label: resolveLocalizedName(b.name, lang) || 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, i18n.language, initialData]);
return (
<BentoGrid cols={2}>
@@ -273,15 +316,14 @@ function StepLocation({ form, errors, set, t }: StepContentProps) {
set("region", v);
set("branch", "");
}}
options={REGION_OPTIONS}
options={regionOptions}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.region}
/>
</BentoCard>
<BentoCard>
<FormInput
type="searchable-select"
<InfiniteSelect
label={t("Branch") || "Şahamça"}
required
value={form.branch}
@@ -290,6 +332,12 @@ function StepLocation({ form, errors, set, t }: StepContentProps) {
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}
/>
</BentoCard>
</BentoGrid>
@@ -369,7 +417,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
/>
</BentoCard>
</BentoGrid>
<BentoGrid cols={2}>
<BentoCard>
<FormInput
@@ -456,7 +503,7 @@ function StepCard({ form, errors, set, t }: StepContentProps) {
);
}
function StepPassport({ form, errors, set, t }: StepContentProps) {
function StepPassport({ form, errors, set, t, mode }: StepContentProps & { mode: "create" | "edit" }) {
return (
<div className="space-y-4">
<BentoGrid cols={3}>
@@ -517,6 +564,56 @@ function StepPassport({ form, errors, set, t }: StepContentProps) {
/>
</BentoCard>
</BentoGrid>
<BentoGrid cols={2}>
<BentoCard>
<DocumentUpload
label={
mode === "edit"
? t("loanOrderForm.fileLabels.replacePage1") || "Pasport (sahypa 1) (çalyşmak)"
: t("Passport (page 1)") || "Pasport (sahypa 1)"
}
value={form.passportOne}
onChange={(v) => set("passportOne", v)}
error={errors.passportOne}
required={mode === "create"}
accept="image/*"
/>
</BentoCard>
<BentoCard>
<DocumentUpload
label={
mode === "edit"
? t("loanOrderForm.fileLabels.replacePage23") || "Pasport (2-3-nji sahypa) (çalyşmak)"
: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)"
}
value={form.passportTwo}
onChange={(v) => set("passportTwo", v)}
error={errors.passportTwo}
required={mode === "create"}
accept="image/*"
/>
</BentoCard>
<BentoCard>
<DocumentUpload
label={t("Passport (page 8-9)") || "Pasport (8-9 sahypa)"}
value={form.passportThree}
onChange={(v) => set("passportThree", v)}
accept="image/*"
/>
</BentoCard>
<BentoCard>
<DocumentUpload
label={t("Passport (page 32)") || "Pasport (32-nji sahypa)"}
value={form.passportFour}
onChange={(v) => set("passportFour", v)}
accept="image/*"
/>
</BentoCard>
</BentoGrid>
</div>
);
}
@@ -565,7 +662,25 @@ function StepContact({ form, errors, set, t }: StepContentProps) {
);
}
function StepJob({ form, errors, set, t }: StepContentProps) {
function StepJob({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrder }) {
const { i18n } = useTranslation();
const [provinceSearch, setProvinceSearch] = useState("");
const provinceQuery = useInfiniteProvinces(provinceSearch);
const regionOptions = useMemo(() => getRegionOptions(t), [t]);
const provinceOptions: InfiniteSelectOption[] = useMemo(() => {
const lang = i18n.language ?? "en";
const opts: InfiniteSelectOption[] = (provinceQuery.data?.pages ?? [])
.flatMap((p) => p.provinces)
.map((prov) => ({ value: String(prov.id), label: resolveLocalizedName(prov.name, lang) || 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, i18n.language, initialData]);
return (
<div className="space-y-4">
<BentoGrid cols={2}>
@@ -595,16 +710,21 @@ function StepJob({ form, errors, set, t }: StepContentProps) {
label={t("Work region") || "Işleýän welaýatyňyz"}
value={form.workRegion}
onChange={(v) => set("workRegion", v)}
options={REGION_OPTIONS}
options={regionOptions}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
/>
<FormInput
type="searchable-select"
<InfiniteSelect
label={t("Work province") || "Işleýän etrabyňyz"}
value={form.workProvince}
onChange={(v) => 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}
/>
</BentoCard>
</BentoGrid>
@@ -647,88 +767,6 @@ function StepJob({ form, errors, set, t }: StepContentProps) {
);
}
function StepFiles({ form, errors, set, t, mode, initialData }: StepContentProps & { mode: "create" | "edit"; initialData?: LoanOrder }) {
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)
: [];
return (
<div className="space-y-4">
{existingFiles.length > 0 && (
<BentoGrid cols={4}>
{existingFiles.map(({ url, label }) => (
<BentoCard key={label} title={label}>
<a href={url} target="_blank" rel="noopener noreferrer" className="text-xs text-primary underline truncate block">
{t("loanOrderForm.fileLabels.viewFile") || "Faýly gör"}
</a>
</BentoCard>
))}
</BentoGrid>
)}
<BentoGrid cols={2}>
<BentoCard>
<FormInput
type="file"
label={
mode === "edit"
? t("loanOrderForm.fileLabels.replacePage1") || "Pasport (sahypa 1) (çalyşmak)"
: t("Passport (page 1)") || "Pasport (sahypa 1)"
}
required={mode === "create"}
accept="image/*"
fileValue={form.passportPage1}
onFileChange={(f) => set("passportPage1", f)}
error={errors.passportPage1}
/>
</BentoCard>
<BentoCard>
<FormInput
type="file"
label={
mode === "edit"
? t("loanOrderForm.fileLabels.replacePage23") || "Pasport (2-3-nji sahypa) (çalyşmak)"
: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)"
}
required={mode === "create"}
accept="image/*"
fileValue={form.passportPage23}
onFileChange={(f) => set("passportPage23", f)}
error={errors.passportPage23}
/>
</BentoCard>
<BentoCard>
<FormInput
type="file"
label={t("Passport (page 8-9)") || "Pasport (8-9 sahypa)"}
accept="image/*"
fileValue={form.passportPage89}
onFileChange={(f) => set("passportPage89", f)}
/>
</BentoCard>
<BentoCard>
<FormInput
type="file"
label={t("Passport (page 32)") || "Pasport (32-nji sahypa)"}
accept="image/*"
fileValue={form.passportPage32}
onFileChange={(f) => set("passportPage32", f)}
/>
</BentoCard>
</BentoGrid>
</div>
);
}
function StepGuarantor({ form, errors, set, t }: StepContentProps) {
return (
<div className="space-y-4">
@@ -850,6 +888,118 @@ function StepGuarantor({ form, errors, set, t }: StepContentProps) {
);
}
function StepGuarantor2({ form, errors, set, t }: StepContentProps) {
return (
<div className="space-y-4">
<BentoGrid cols={3}>
<BentoCard>
<FormInput
type="text"
label={t("Guarantor 2 name") || "2. Zamunyň ady"}
value={form.guarantor2Name}
onChange={(v) => set("guarantor2Name", v)}
placeholder={t("Guarantor 2 name") || "2. Zamunyň ady"}
error={errors.guarantor2Name}
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("Guarantor 2 Surname") || "2. Zamunyň familiýasy"}
value={form.guarantor2Surname}
onChange={(v) => set("guarantor2Surname", v)}
placeholder={t("Guarantor 2 Surname") || "2. Zamunyň familiýasy"}
error={errors.guarantor2Surname}
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("Guarantor 2 Patronic name") || "2. Zamunyň atasynyň ady"}
value={form.guarantor2Patronic}
onChange={(v) => set("guarantor2Patronic", v)}
placeholder={t("Guarantor 2 Patronic name") || "2. Zamunyň atasynyň ady"}
/>
</BentoCard>
</BentoGrid>
<BentoGrid cols={2}>
<BentoCard>
<FormInput
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}
/>
</BentoCard>
<BentoCard>
<FormInput
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}
/>
</BentoCard>
</BentoGrid>
<BentoGrid cols={2}>
<BentoCard>
<FormInput
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}
/>
<FormInput
type="text"
label={t("Name on card") || "Kartdaky ady"}
value={form.guarantor2CardName}
onChange={(v) => set("guarantor2CardName", v)}
placeholder={t("Name on card") || "Kartdaky ady"}
error={errors.guarantor2CardName}
/>
</BentoCard>
<BentoCard>
<FormInput
type="searchable-select"
label={t("Expiration month") || "Möhleti (aý)"}
value={form.guarantor2CardExpMonth}
onChange={(v) => set("guarantor2CardExpMonth", v)}
options={MONTH_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.guarantor2CardExpMonth}
/>
<FormInput
type="searchable-select"
label={t("Expiration year") || "Möhleti (ýyl)"}
value={form.guarantor2CardExpYear}
onChange={(v) => set("guarantor2CardExpYear", v)}
options={YEAR_OPTIONS}
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
error={errors.guarantor2CardExpYear}
/>
<FormInput
type="textarea"
label={t("Guarantor Note") || "Zamun belligi"}
value={form.guarantor2Note}
onChange={(v) => set("guarantor2Note", v)}
placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."}
rows={2}
/>
</BentoCard>
</BentoGrid>
</div>
);
}
// ─── Props ────────────────────────────────────────────────────────────────────
interface LoanOrderFormProps {
@@ -1006,7 +1156,7 @@ export function LoanOrderForm({ mode, initialData }: LoanOrderFormProps) {
{/* Page header */}
<div>
<h1 className="text-xl font-semibold text-foreground">
{mode === "create" ? t("loanOrders.create") || "Karz sargyt döredüň" : t("loanOrders.edit") || "Karz sargydy üýtget"}
{mode === "create" ? t("loanOrders.create") || "Karz sargyt dörediň" : t("loanOrders.edit") || "Karz sargydy üýtget"}
</h1>
<p className="text-sm text-muted-foreground mt-1">
{mode === "create"
@@ -1022,15 +1172,15 @@ export function LoanOrderForm({ mode, initialData }: LoanOrderFormProps) {
{/* Step content */}
{currentStep === 0 && <StepStatus {...stepProps} />}
{currentStep === 1 && <StepLoan {...stepProps} />}
{currentStep === 2 && <StepLocation {...stepProps} />}
{currentStep === 1 && <StepLoan {...stepProps} initialData={initialData} />}
{currentStep === 2 && <StepLocation {...stepProps} initialData={initialData} />}
{currentStep === 3 && <StepPersonal {...stepProps} />}
{currentStep === 4 && <StepCard {...stepProps} />}
{currentStep === 5 && <StepPassport {...stepProps} />}
{currentStep === 5 && <StepPassport {...stepProps} mode={mode} />}
{currentStep === 6 && <StepContact {...stepProps} />}
{currentStep === 7 && <StepJob {...stepProps} />}
{currentStep === 8 && <StepFiles {...stepProps} mode={mode} initialData={initialData} />}
{currentStep === 9 && <StepGuarantor {...stepProps} />}
{currentStep === 7 && <StepJob {...stepProps} initialData={initialData} />}
{currentStep === 8 && <StepGuarantor {...stepProps} />}
{currentStep === 9 && <StepGuarantor2 {...stepProps} />}
{/* Actions */}
<FormActions
@@ -1040,7 +1190,7 @@ export function LoanOrderForm({ mode, initialData }: LoanOrderFormProps) {
onNext={!isLastStep ? handleNext : undefined}
showSubmit={isLastStep}
onSubmit={isLastStep ? doSubmit : undefined}
submitLabel={mode === "create" ? t("loanOrders.createButton") || "Karz sargyt döredüň" : t("common.save") || "Ýatda sakla"}
submitLabel={mode === "create" ? t("loanOrders.create") || "Karz sargyt döredüň" : t("common.save") || "Ýatda sakla"}
loadingLabel={t("common.loading") || "Ýüklenilýär..."}
cancelLabel={t("common.cancel") || "Ýatyr"}
prevLabel={t("common.back") || "Yza"}
@@ -1053,33 +1203,37 @@ export function LoanOrderForm({ mode, initialData }: LoanOrderFormProps) {
function mapInitial(order: LoanOrder): Partial<LoanOrderFormData> {
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) : "",
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 ?? "",
@@ -1097,5 +1251,15 @@ function mapInitial(order: LoanOrder): Partial<LoanOrderFormData> {
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 ?? "",
};
}

View File

@@ -1,7 +1,6 @@
import { z } from "zod";
import i18next from "i18next";
const fileRequired = z.custom<File>((val) => val instanceof File, "validation.requiredFile");
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
export const loanOrderFormSchema = z.object({
status: z.string().min(1, "validation.required"),
@@ -100,10 +99,10 @@ export const loanOrderFormSchema = z.object({
position: z.string().min(1, "validation.required"),
salary: z.string().min(1, "validation.required"),
workStartedAt: z.string().min(1, "validation.required"),
passportPage1: z.custom<File | null>().nullable(),
passportPage23: z.custom<File | null>().nullable(),
passportPage89: z.custom<File | null>().nullable(),
passportPage32: z.custom<File | null>().nullable(),
passportOne: z.string().optional(),
passportTwo: z.string().optional(),
passportThree: z.string().optional(),
passportFour: z.string().optional(),
note: z.string().optional(),
loanAmount: z.string().min(1, "validation.required"),
loanHistory: z.string().optional(),
@@ -121,6 +120,16 @@ export const loanOrderFormSchema = z.object({
guarantor1CardExpMonth: z.string().min(1, "validation.required"),
guarantor1CardExpYear: z.string().min(1, "validation.required"),
guarantor1Salary: z.string().min(1, "validation.required"),
guarantor2Name: z.string().optional(),
guarantor2Surname: z.string().optional(),
guarantor2Patronic: z.string().optional(),
guarantor2PassportSerie: z.string().optional(),
guarantor2PassportNumber: z.string().optional(),
guarantor2CardNumber: z.string().optional(),
guarantor2CardName: z.string().optional(),
guarantor2CardExpMonth: z.string().optional(),
guarantor2CardExpYear: z.string().optional(),
guarantor2Note: z.string().optional(),
});
export type LoanOrderFormData = z.infer<typeof loanOrderFormSchema>;
@@ -148,6 +157,8 @@ export const stepSchemas: Record<number, z.ZodType<Partial<LoanOrderFormData>>>
passportNumber: true,
passportDateOfIssue: true,
passportGivenBy: true,
passportOne: true,
passportTwo: true,
}),
6: loanOrderFormSchema.pick({ phone: true, phoneAdditional: true, homePhone: true }),
7: loanOrderFormSchema.pick({
@@ -157,11 +168,7 @@ export const stepSchemas: Record<number, z.ZodType<Partial<LoanOrderFormData>>>
workStartedAt: true,
workHrPhone: true,
}),
8: z.object({
passportPage1: fileRequired,
passportPage23: fileRequired,
}),
9: loanOrderFormSchema.pick({
8: loanOrderFormSchema.pick({
guarantor1Name: true,
guarantor1Surname: true,
guarantor1PassportSerie: true,
@@ -172,6 +179,18 @@ export const stepSchemas: Record<number, z.ZodType<Partial<LoanOrderFormData>>>
guarantor1CardExpYear: true,
guarantor1Salary: true,
}),
9: loanOrderFormSchema.pick({
guarantor2Name: true,
guarantor2Surname: true,
guarantor2Patronic: true,
guarantor2PassportSerie: true,
guarantor2PassportNumber: true,
guarantor2CardNumber: true,
guarantor2CardName: true,
guarantor2CardExpMonth: true,
guarantor2CardExpYear: true,
guarantor2Note: true,
}),
};
export function validateStep(
@@ -179,8 +198,18 @@ export function validateStep(
form: LoanOrderFormData,
mode: "create" | "edit",
): Partial<Record<keyof LoanOrderFormData, string>> {
if (stepIndex === 8 && mode === "edit") return {};
const schema = stepSchemas[stepIndex];
// In edit mode the passport files are already uploaded, so only the text
// fields of the passport step stay required.
const schema =
stepIndex === 5 && mode === "edit"
? loanOrderFormSchema.pick({
passportSerie: true,
passportNumber: true,
passportDateOfIssue: true,
passportGivenBy: true,
})
: stepSchemas[stepIndex];
if (!schema) return {};
const result = schema.safeParse(form);
if (result.success) return {};
const errors: Partial<Record<keyof LoanOrderFormData, string>> = {};
@@ -197,7 +226,7 @@ export function validateStep(
export const DEFAULT_FORM_VALUES: LoanOrderFormData = {
status: "pending",
loanType: "",
region: "Aşgabat",
region: "AG",
branch: "",
firstName: "",
lastName: "",
@@ -218,15 +247,15 @@ export const DEFAULT_FORM_VALUES: LoanOrderFormData = {
homePhone: "",
workCompany: "",
workHrPhone: "",
workRegion: "Aşgabat",
workRegion: "AG",
workProvince: "",
position: "",
salary: "",
workStartedAt: "",
passportPage1: null,
passportPage23: null,
passportPage89: null,
passportPage32: null,
passportOne: "",
passportTwo: "",
passportThree: "",
passportFour: "",
note: "",
loanAmount: "",
loanHistory: "",
@@ -244,6 +273,16 @@ export const DEFAULT_FORM_VALUES: LoanOrderFormData = {
guarantor1CardExpMonth: "",
guarantor1CardExpYear: "",
guarantor1Salary: "",
guarantor2Name: "",
guarantor2Surname: "",
guarantor2Patronic: "",
guarantor2PassportSerie: "",
guarantor2PassportNumber: "",
guarantor2CardNumber: "",
guarantor2CardName: "",
guarantor2CardExpMonth: "",
guarantor2CardExpYear: "",
guarantor2Note: "",
};
export function buildPayload(data: LoanOrderFormData) {
@@ -293,5 +332,19 @@ export function buildPayload(data: LoanOrderFormData) {
guarantor1CardExpMonth: data.guarantor1CardExpMonth || undefined,
guarantor1CardExpYear: data.guarantor1CardExpYear || undefined,
guarantor1Salary: Number(data.guarantor1Salary) || undefined,
guarantor2Name: data.guarantor2Name || undefined,
guarantor2Surname: data.guarantor2Surname || undefined,
guarantor2Patronic: data.guarantor2Patronic || undefined,
guarantor2PassportSerie: data.guarantor2PassportSerie || undefined,
guarantor2PassportNumber: data.guarantor2PassportNumber || undefined,
guarantor2CardNumber: data.guarantor2CardNumber || undefined,
guarantor2CardName: data.guarantor2CardName || undefined,
guarantor2CardExpMonth: data.guarantor2CardExpMonth || undefined,
guarantor2CardExpYear: data.guarantor2CardExpYear || undefined,
guarantor2Note: data.guarantor2Note || undefined,
passportOne: data.passportOne || undefined,
passportTwo: data.passportTwo || undefined,
passportThree: data.passportThree || undefined,
passportFour: data.passportFour || undefined,
};
}

View File

@@ -1,4 +1,5 @@
import apiClient from "@/lib/api/client";
import type { LocalizedText } from "@/features/branches/api/branchesApi";
// ─── Types ─────────────────────────────────────────────────────────────────────
@@ -9,7 +10,9 @@ export interface LoanPaidOffLetter {
uniqueId: string;
region: string;
branchId: number | null;
branchName?: LocalizedText | string | null;
userId: number | null;
userName?: string | null;
customerName: string;
customerSurname: string;
customerPatronicName: string;

View File

@@ -9,9 +9,14 @@ import type { LucideIcon } from "lucide-react";
import { FormInput, type SelectOption } from "@/components/formInput";
import { FormActions } from "@/components/formActions";
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
import { DocumentUpload } from "@/components/documentUpload";
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
import { BentoGrid, BentoCard } from "@/components/bento";
import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants";
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
import type { LocalizedText } from "@/features/branches/api/branchesApi";
import { useCreateLoanPaidOffLetter, useUpdateLoanPaidOffLetter } from "../hooks/useLoanPaidOffLetters";
import type { LoanPaidOffLetter } from "../api/loanPaidOffLettersApi";
@@ -43,6 +48,12 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
return result;
}
function resolveLocalizedName(name: LocalizedText | string | undefined | null, lang = "en"): string {
if (!name) return "";
if (typeof name === "string") return name;
return name[lang as keyof LocalizedText] ?? name.tm ?? name.en ?? name.ru ?? "";
}
// ─── Static options ───────────────────────────────────────────────────────────
const REGION_CODES = ["AG", "AH", "BA", "DA", "LE", "MA"] as const;
@@ -234,7 +245,14 @@ function StepLocation({
t,
regionOptions,
statusOptions,
}: StepContentProps & { regionOptions: SelectOption[]; statusOptions: SelectOption[] }) {
branchSelectProps,
userSelectProps,
}: StepContentProps & {
regionOptions: SelectOption[];
statusOptions: SelectOption[];
branchSelectProps: Omit<InfiniteSelectProps, "label" | "required" | "placeholder">;
userSelectProps: Omit<InfiniteSelectProps, "label" | "required" | "placeholder">;
}) {
return (
<BentoGrid cols={2}>
<BentoCard>
@@ -248,19 +266,22 @@ function StepLocation({
error={errors.region}
required
/>
<FormInput
type="number"
label={t("loanPaidOffLetters.fields.branchId", "Şahamça ID")}
<InfiniteSelect
label={t("loanPaidOffLetters.fields.branchId", "Şahamça")}
value={form.branchId}
onChange={set("branchId")}
error={errors.branchId}
required
placeholder={t("loanPaidOffLetters.placeholders.branch", "Şahamça saýlaň")}
{...branchSelectProps}
/>
<FormInput
type="number"
label={t("loanPaidOffLetters.fields.userId", "Ulanyjy ID")}
<InfiniteSelect
label={t("loanPaidOffLetters.fields.userId", "Ulanyjy")}
value={form.userId ?? ""}
onChange={set("userId")}
error={errors.userId}
placeholder={t("loanPaidOffLetters.placeholders.user", "Ulanyjy saýlaň")}
{...userSelectProps}
/>
<FormInput
type="select"
@@ -283,12 +304,12 @@ function StepLocation({
onChange={set("uniqueId")}
placeholder="LPL-2026-0001"
/>
<FormInput
type="text"
<DocumentUpload
label={t("loanPaidOffLetters.fields.loanFile", "Faýl")}
value={form.loanFile ?? ""}
onChange={set("loanFile")}
placeholder="letter1.pdf"
error={errors.loanFile}
accept=".pdf,.doc,.docx,image/*"
/>
<FormInput
type="textarea"
@@ -306,7 +327,7 @@ function StepLocation({
// ─── LoanPaidOffLetterForm ────────────────────────────────────────────────────
export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFormProps) {
const { t } = useTranslation();
const { t, i18n } = useTranslation();
const navigate = useNavigate();
const createMutation = useCreateLoanPaidOffLetter();
@@ -317,6 +338,72 @@ export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFo
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>([0])));
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(() => new Set());
// ── Branch infinite-scroll select ──
const [branchSearch, setBranchSearch] = useState("");
const branchQuery = useInfiniteBranches(branchSearch);
const branchSelectProps: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
const lang = i18n.language ?? "en";
const opts: InfiniteSelectOption[] = (branchQuery.data?.pages ?? [])
.flatMap((p) => p.branches)
.map((b) => ({
value: String(b.id),
label: resolveLocalizedName(b.name, lang) || b.uniqueCode || String(b.id),
}));
if (initialData?.branchId) {
const bId = String(initialData.branchId);
if (!opts.some((o) => o.value === bId)) {
const initialBranchName = resolveLocalizedName(initialData.branchName, lang) || bId;
opts.unshift({ value: bId, label: initialBranchName });
}
}
return {
options: opts,
loading: branchQuery.isLoading,
isLoadingMore: branchQuery.isFetchingNextPage,
hasNextPage: !!branchQuery.hasNextPage,
onLoadMore: () => branchQuery.fetchNextPage(),
searchValue: branchSearch,
onSearchChange: setBranchSearch,
};
}, [branchQuery, branchSearch, i18n.language, initialData]);
// ── User infinite-scroll select ──
const [userSearch, setUserSearch] = useState("");
const usersQuery = useInfiniteUsers(userSearch);
const userSelectProps: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
const opts: InfiniteSelectOption[] = (usersQuery.data?.pages ?? [])
.flatMap((p) => p.users)
.map((u) => {
const displayName = [u.firstName, u.lastName].filter(Boolean).join(" ") || u.name || u.username;
return {
value: String(u.id),
label: `${displayName}${u.phone ? ` (${u.phone})` : ""}`,
};
});
if (initialData?.userId) {
const uId = String(initialData.userId);
if (!opts.some((o) => o.value === uId)) {
const initialUserName = initialData.userName || uId;
opts.unshift({ value: uId, label: initialUserName });
}
}
return {
options: opts,
loading: usersQuery.isLoading,
isLoadingMore: usersQuery.isFetchingNextPage,
hasNextPage: !!usersQuery.hasNextPage,
onLoadMore: () => usersQuery.fetchNextPage(),
searchValue: userSearch,
onSearchChange: setUserSearch,
};
}, [usersQuery, userSearch, initialData]);
const {
watch,
setValue,
@@ -477,7 +564,15 @@ export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFo
{currentStep === 0 && <StepCustomer {...stepProps} />}
{currentStep === 1 && <StepPassport {...stepProps} />}
{currentStep === 2 && <StepLoan {...stepProps} />}
{currentStep === 3 && <StepLocation {...stepProps} regionOptions={regionOptions} statusOptions={statusOptions} />}
{currentStep === 3 && (
<StepLocation
{...stepProps}
regionOptions={regionOptions}
statusOptions={statusOptions}
branchSelectProps={branchSelectProps}
userSelectProps={userSelectProps}
/>
)}
{/* Form Actions */}
<FormActions

View File

@@ -5,6 +5,7 @@ import apiClient from "@/lib/api/client";
export interface LoanRemaining {
id: number;
userId: number;
userName: string;
passportSerie: string;
passportId: string;
accountNumber: string;

View File

@@ -1,4 +1,4 @@
import { useEffect } from "react";
import { useEffect, useState, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
@@ -7,7 +7,10 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { FormInput } from "@/components/formInput";
import { FormActions } from "@/components/formActions";
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
import { BentoGrid, BentoCard } from "@/components/bento";
import { PASSPORT_SERIES_OPTIONS } from "@/constants/passportSeries";
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
import { useCreateLoanRemaining, useUpdateLoanRemaining } from "../hooks/useLoanRemaining";
import type { LoanRemaining } from "../api/loanRemainingApi";
@@ -27,6 +30,42 @@ export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps)
const isPending = createMutation.isPending || updateMutation.isPending;
// ── Infinite Users Searchable Select ──
const [userSearch, setUserSearch] = useState("");
const usersQuery = useInfiniteUsers(userSearch);
const userSelectProps: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
const opts: InfiniteSelectOption[] = (usersQuery.data?.pages ?? [])
.flatMap((p) => p.users)
.map((u) => {
const displayName = [u.firstName, u.lastName].filter(Boolean).join(" ") || u.name || u.username;
return {
value: String(u.id),
label: `${displayName}${u.phone ? ` (${u.phone})` : ""}`,
};
});
if (initialData?.userId) {
const currentVal = String(initialData.userId);
if (!opts.some((o) => o.value === currentVal)) {
opts.unshift({
value: currentVal,
label: initialData.userName || currentVal,
});
}
}
return {
options: opts,
loading: usersQuery.isLoading,
isLoadingMore: usersQuery.isFetchingNextPage,
hasNextPage: !!usersQuery.hasNextPage,
onLoadMore: () => usersQuery.fetchNextPage(),
searchValue: userSearch,
onSearchChange: setUserSearch,
};
}, [usersQuery, userSearch, initialData]);
const {
handleSubmit,
watch,
@@ -86,39 +125,46 @@ export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps)
<BentoCard>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormInput
type="select"
options={PASSPORT_SERIES_OPTIONS}
label={t("loanRemaining.columns.passportSerie", "Pasport seriýasy")}
required
value={watch("passportSerie")}
onChange={(v) => setValue("passportSerie", v)}
placeholder={t("loanRemaining.placeholders.passportSerie", "TM")}
onChange={(v) => setValue("passportSerie", v, { shouldValidate: true })}
placeholder={t("loanRemaining.placeholders.passportSerie", "Pasport seriýasy saýlaň")}
error={errMsg(errors.passportSerie?.message)}
disabled={isPending}
/>
<FormInput
label={t("loanRemaining.columns.passportId", "Pasport belgisi")}
required
value={watch("passportId")}
onChange={(v) => setValue("passportId", v)}
onChange={(v) => setValue("passportId", v, { shouldValidate: true })}
placeholder="A123456"
error={errMsg(errors.passportId?.message)}
disabled={isPending}
/>
<FormInput
label={t("loanRemaining.columns.accountNumber", "Karz hasaby")}
required
value={watch("accountNumber")}
onChange={(v) => setValue("accountNumber", v)}
onChange={(v) => setValue("accountNumber", v, { shouldValidate: true })}
placeholder="ACC-LOAN-..."
error={errMsg(errors.accountNumber?.message)}
disabled={isPending}
/>
<FormInput
label={t("loanRemaining.columns.userId", "Ulanyjy ID")}
<InfiniteSelect
label={t("loanRemaining.columns.userId", "Ulanyjy")}
required
value={watch("userId")}
onChange={(v) => setValue("userId", v)}
placeholder="2"
onChange={(v) => setValue("userId", v, { shouldValidate: true })}
placeholder={t("loanRemaining.placeholders.userId", "Ulanyjy saýlaň")}
error={errMsg(errors.userId?.message)}
disabled={isPending}
{...userSelectProps}
/>
</div>
</BentoCard>

View File

@@ -1,6 +1,6 @@
// features/loanTypes/hooks/useLoanTypes.ts
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
@@ -36,6 +36,28 @@ export function useGetLoanTypes(params: LoanTypeListParams = {}) {
});
}
const LOAN_TYPE_PAGE_SIZE = 25;
/**
* Paginated loan types for infinite-scroll searchable selects.
* `search` is debounced server-side search; each keystroke resets to page 1.
*/
export function useInfiniteLoanTypes(search = "") {
const debouncedSearch = useDebouncedValue(search);
const effectiveSearch = normalizeSearch(debouncedSearch);
return useInfiniteQuery({
queryKey: [...loanTypeKeys.all(), "infinite", effectiveSearch] as const,
initialPageParam: 1,
queryFn: ({ pageParam, signal }) => fetchLoanTypes({ page: pageParam, limit: LOAN_TYPE_PAGE_SIZE, search: effectiveSearch }, signal),
getNextPageParam: (lastPage, allPages) => {
const loaded = allPages.reduce((sum, p) => sum + p.loanTypes.length, 0);
return loaded < lastPage.count ? allPages.length + 1 : undefined;
},
staleTime: 5 * 60 * 1000, // 5 minutes
});
}
// ─── useGetLoanTypeById ───────────────────────────────────────────────────────
export function useGetLoanTypeById(id: number | undefined) {