connected with loan order api
This commit is contained in:
213
src/components/documentUpload.tsx
Normal file
213
src/components/documentUpload.tsx
Normal file
@@ -0,0 +1,213 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Upload, X, Loader2, FileText, ExternalLink } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { postFile, buildFileUrl } from "@/features/shared/api/sharedApi";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface DocumentUploadProps {
|
||||
label?: string;
|
||||
value?: string;
|
||||
onChange?: (url: string) => void;
|
||||
error?: string;
|
||||
required?: boolean;
|
||||
disabled?: boolean;
|
||||
accept?: string;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
// ─── FieldLabel ───────────────────────────────────────────────────────────────
|
||||
|
||||
function FieldLabel({ label, required }: { label?: string; required?: boolean }) {
|
||||
if (!label) return null;
|
||||
return (
|
||||
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1.5 select-none">
|
||||
{label}
|
||||
{required && <span className="text-destructive ml-0.5">*</span>}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── ErrorMsg ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function ErrorMsg({ error }: { error?: string }) {
|
||||
if (!error) return null;
|
||||
return (
|
||||
<p className="mt-1.5 text-xs text-destructive font-medium flex items-center gap-1.5">
|
||||
<span className="inline-block w-1 h-1 rounded-full bg-destructive shrink-0" />
|
||||
{error}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Helper: Extract Filename ────────────────────────────────────────────────
|
||||
|
||||
function getDisplayFilename(urlOrName: string): string {
|
||||
if (!urlOrName) return "";
|
||||
try {
|
||||
const parts = urlOrName.split("/");
|
||||
return decodeURIComponent(parts[parts.length - 1]);
|
||||
} catch {
|
||||
return urlOrName;
|
||||
}
|
||||
}
|
||||
|
||||
const IMAGE_EXT_REGEX = /\.(png|jpe?g|gif|webp|bmp|svg|avif|heic|heif)$/i;
|
||||
|
||||
function isImageFileName(urlOrName: string): boolean {
|
||||
const clean = urlOrName.split("?")[0].split("#")[0];
|
||||
return IMAGE_EXT_REGEX.test(clean);
|
||||
}
|
||||
|
||||
// ─── DocumentUpload ───────────────────────────────────────────────────────────
|
||||
|
||||
export function DocumentUpload({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
required,
|
||||
disabled,
|
||||
accept = ".pdf,.doc,.docx,image/*",
|
||||
placeholder,
|
||||
}: DocumentUploadProps) {
|
||||
const { t } = useTranslation();
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadError, setUploadError] = useState("");
|
||||
|
||||
const defaultPlaceholder = placeholder ?? t("common.fileUploadPlaceholder", "Faýl saýlaň ýa-da süýräp getiriň (PDF, DOCX, Surat)");
|
||||
|
||||
const handleFile = async (file: File | null) => {
|
||||
if (!file || disabled) return;
|
||||
|
||||
setUploading(true);
|
||||
setUploadError("");
|
||||
try {
|
||||
const filename = await postFile(file);
|
||||
const fileUrl = buildFileUrl(filename);
|
||||
onChange?.(fileUrl);
|
||||
} catch {
|
||||
setUploadError(t("common.fileUploadError", "Faýl ýüklenip bilinmedi"));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
const handleDrop = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setDragOver(false);
|
||||
handleFile(e.dataTransfer.files[0] ?? null);
|
||||
};
|
||||
|
||||
const effectiveError = error || uploadError;
|
||||
const fileName = value ? getDisplayFilename(value) : "";
|
||||
|
||||
return (
|
||||
<div>
|
||||
<FieldLabel label={label} required={required} />
|
||||
|
||||
{value ? (
|
||||
<div className="p-3 rounded-md border border-border bg-muted/30 space-y-2">
|
||||
{isImageFileName(value) ? (
|
||||
<a
|
||||
href={value.startsWith("http") ? value : buildFileUrl(value)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block overflow-hidden rounded-md border border-border bg-background"
|
||||
>
|
||||
<img
|
||||
src={value.startsWith("http") ? value : buildFileUrl(value)}
|
||||
alt={fileName}
|
||||
loading="lazy"
|
||||
className="w-full h-36 object-cover"
|
||||
/>
|
||||
</a>
|
||||
) : (
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
<div className="w-8 h-8 rounded-md bg-primary/10 flex items-center justify-center shrink-0">
|
||||
<FileText size={16} className="text-primary" />
|
||||
</div>
|
||||
<p className="text-sm font-medium text-foreground truncate">{fileName}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<a
|
||||
href={value.startsWith("http") ? value : buildFileUrl(value)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-primary hover:underline inline-flex items-center gap-1 shrink-0"
|
||||
>
|
||||
<ExternalLink size={11} />
|
||||
{t("common.viewFile", "Faýla seret")}
|
||||
</a>
|
||||
|
||||
{!disabled && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange?.("")}
|
||||
className="p-1.5 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors shrink-0"
|
||||
title={t("common.remove", "Aýyr")}
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
onClick={() => !disabled && !uploading && inputRef.current?.click()}
|
||||
onKeyDown={(e) => e.key === "Enter" && !disabled && !uploading && inputRef.current?.click()}
|
||||
onDragOver={(e) => {
|
||||
if (disabled) return;
|
||||
e.preventDefault();
|
||||
setDragOver(true);
|
||||
}}
|
||||
onDragLeave={() => setDragOver(false)}
|
||||
onDrop={handleDrop}
|
||||
className={cn(
|
||||
"flex flex-col items-center justify-center gap-2 px-4 py-5",
|
||||
"rounded-md border-2 border-dashed cursor-pointer select-none text-center",
|
||||
"transition-all duration-200 text-sm",
|
||||
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||
dragOver && "border-primary bg-primary/5 scale-[1.01]",
|
||||
effectiveError ? "border-destructive/60" : "border-border",
|
||||
!dragOver && !effectiveError && "hover:border-primary/50 hover:bg-muted/20",
|
||||
(disabled || uploading) && "opacity-60 cursor-not-allowed pointer-events-none",
|
||||
)}
|
||||
>
|
||||
{uploading ? (
|
||||
<div className="flex items-center gap-2 py-1">
|
||||
<Loader2 size={18} className="animate-spin text-primary" />
|
||||
<span className="text-sm text-muted-foreground">{t("common.uploading", "Ýüklenýär...")}</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="w-9 h-9 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
<Upload size={18} className="text-primary" />
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground max-w-xs">{defaultPlaceholder}</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept={accept}
|
||||
disabled={disabled || uploading}
|
||||
onChange={(e) => handleFile(e.target.files?.[0] ?? null)}
|
||||
className="hidden"
|
||||
/>
|
||||
|
||||
<ErrorMsg error={effectiveError} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,66 +1,35 @@
|
||||
import * as React from "react"
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="table-container"
|
||||
className="relative w-full overflow-x-auto"
|
||||
>
|
||||
<table
|
||||
data-slot="table"
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
<div data-slot="table-container" className="relative w-full overflow-x-auto scrollbar-thin">
|
||||
<table data-slot="table" className={cn("w-full caption-bottom text-sm", className)} {...props} />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||
return (
|
||||
<thead
|
||||
data-slot="table-header"
|
||||
className={cn("[&_tr]:border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return <thead data-slot="table-header" className={cn("[&_tr]:border-b", className)} {...props} />;
|
||||
}
|
||||
|
||||
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||
return (
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
className={cn("[&_tr:last-child]:border-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return <tbody data-slot="table-body" className={cn("[&_tr:last-child]:border-0", className)} {...props} />;
|
||||
}
|
||||
|
||||
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||
return (
|
||||
<tfoot
|
||||
data-slot="table-footer"
|
||||
className={cn(
|
||||
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return <tfoot data-slot="table-footer" className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)} {...props} />;
|
||||
}
|
||||
|
||||
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||
return (
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
|
||||
className
|
||||
)}
|
||||
className={cn("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||
@@ -69,46 +38,21 @@ function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||
return (
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn(
|
||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
<td data-slot="table-cell" className={cn("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0", className)} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function TableCaption({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"caption">) {
|
||||
return (
|
||||
<caption
|
||||
data-slot="table-caption"
|
||||
className={cn("mt-4 text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function TableCaption({ className, ...props }: React.ComponentProps<"caption">) {
|
||||
return <caption data-slot="table-caption" className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} />;
|
||||
}
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableCaption,
|
||||
}
|
||||
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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" }],
|
||||
};
|
||||
|
||||
@@ -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 ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -243,6 +243,7 @@
|
||||
/* ── Custom Scrollbar Styles ── */
|
||||
.scrollbar-thin,
|
||||
[data-slot="select-content"],
|
||||
[data-slot="table-container"],
|
||||
select,
|
||||
.rdp-dropdown,
|
||||
.rdp-dropdowns select {
|
||||
@@ -252,10 +253,12 @@ select,
|
||||
|
||||
.scrollbar-thin::-webkit-scrollbar,
|
||||
[data-slot="select-content"]::-webkit-scrollbar,
|
||||
[data-slot="table-container"]::-webkit-scrollbar,
|
||||
select::-webkit-scrollbar,
|
||||
.rdp-dropdown::-webkit-scrollbar,
|
||||
.rdp-dropdowns select::-webkit-scrollbar,
|
||||
.overflow-y-auto::-webkit-scrollbar,
|
||||
.overflow-x-auto::-webkit-scrollbar,
|
||||
.overflow-auto::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
@@ -263,20 +266,24 @@ select::-webkit-scrollbar,
|
||||
|
||||
.scrollbar-thin::-webkit-scrollbar-track,
|
||||
[data-slot="select-content"]::-webkit-scrollbar-track,
|
||||
[data-slot="table-container"]::-webkit-scrollbar-track,
|
||||
select::-webkit-scrollbar-track,
|
||||
.rdp-dropdown::-webkit-scrollbar-track,
|
||||
.rdp-dropdowns select::-webkit-scrollbar-track,
|
||||
.overflow-y-auto::-webkit-scrollbar-track,
|
||||
.overflow-x-auto::-webkit-scrollbar-track,
|
||||
.overflow-auto::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.scrollbar-thin::-webkit-scrollbar-thumb,
|
||||
[data-slot="select-content"]::-webkit-scrollbar-thumb,
|
||||
[data-slot="table-container"]::-webkit-scrollbar-thumb,
|
||||
select::-webkit-scrollbar-thumb,
|
||||
.rdp-dropdown::-webkit-scrollbar-thumb,
|
||||
.rdp-dropdowns select::-webkit-scrollbar-thumb,
|
||||
.overflow-y-auto::-webkit-scrollbar-thumb,
|
||||
.overflow-x-auto::-webkit-scrollbar-thumb,
|
||||
.overflow-auto::-webkit-scrollbar-thumb {
|
||||
background-color: var(--border);
|
||||
border-radius: 9999px;
|
||||
@@ -284,10 +291,12 @@ select::-webkit-scrollbar-thumb,
|
||||
|
||||
.scrollbar-thin::-webkit-scrollbar-thumb:hover,
|
||||
[data-slot="select-content"]::-webkit-scrollbar-thumb:hover,
|
||||
[data-slot="table-container"]::-webkit-scrollbar-thumb:hover,
|
||||
select::-webkit-scrollbar-thumb:hover,
|
||||
.rdp-dropdown::-webkit-scrollbar-thumb:hover,
|
||||
.rdp-dropdowns select::-webkit-scrollbar-thumb:hover,
|
||||
.overflow-y-auto::-webkit-scrollbar-thumb:hover,
|
||||
.overflow-x-auto::-webkit-scrollbar-thumb:hover,
|
||||
.overflow-auto::-webkit-scrollbar-thumb:hover {
|
||||
background-color: var(--muted-foreground);
|
||||
}
|
||||
|
||||
@@ -433,6 +433,12 @@
|
||||
"loanPaidOffLetters.regions.DA": "Dashoguz",
|
||||
"loanPaidOffLetters.regions.LE": "Lebap",
|
||||
"loanPaidOffLetters.regions.MA": "Mary",
|
||||
"loanOrders.regions.AG": "Ashgabat",
|
||||
"loanOrders.regions.AH": "Ahal",
|
||||
"loanOrders.regions.BN": "Balkan",
|
||||
"loanOrders.regions.DZ": "Dashoguz",
|
||||
"loanOrders.regions.LB": "Lebap",
|
||||
"loanOrders.regions.MR": "Mary",
|
||||
"loanPaidOffLetters.sections.info": "Main info",
|
||||
"loanPaidOffLetters.sections.customer": "Customer info",
|
||||
"loanPaidOffLetters.sections.passport": "Passport",
|
||||
@@ -460,6 +466,8 @@
|
||||
"loanPaidOffLetters.deleteSuccess": "Certificate deleted successfully",
|
||||
"loanPaidOffLetters.createSuccess": "Created successfully",
|
||||
"loanPaidOffLetters.updateSuccess": "Updated successfully",
|
||||
"loanPaidOffLetters.fields.branchName": "Branch name",
|
||||
"loanPaidOffLetters.fields.userName": "User name",
|
||||
"loanRemaining.title": "Loan Remaining Balance",
|
||||
"loanRemaining.createButton": "Create Loan Remaining Record",
|
||||
"loanRemaining.deleteConfirm": "Are you sure you want to delete this record?",
|
||||
@@ -468,6 +476,7 @@
|
||||
"loanRemaining.columns.passportId": "Passport number",
|
||||
"loanRemaining.columns.passportSerie": "Passport series",
|
||||
"loanRemaining.columns.userId": "User ID",
|
||||
"loanRemaining.columns.userName": "User Name",
|
||||
"loanOrderStatus.GARAŞYLÝAR": "PENDING",
|
||||
"loanOrderStatus.KANAGATLANDYRYLAN": "APPROVED",
|
||||
"loanOrderStatus.RED_EDILDI": "REJECTED",
|
||||
@@ -532,6 +541,11 @@
|
||||
"Status": "Status",
|
||||
"Card (Salary)": "Card (Salary)",
|
||||
"1. Guarantor": "1. Guarantor",
|
||||
"2. Guarantor": "2. Guarantor",
|
||||
"Guarantor 2 name": "2nd Guarantor name",
|
||||
"Guarantor 2 Surname": "2nd Guarantor surname",
|
||||
"Guarantor 2 Patronic name": "2nd Guarantor patronymic name",
|
||||
"Guarantor Note": "Guarantor note",
|
||||
"Loan history": "Loan history",
|
||||
"loanOrderForm.labels.status": "Status",
|
||||
"loanOrderForm.labels.loanAmount": "Loan amount",
|
||||
@@ -548,6 +562,7 @@
|
||||
"loanOrderForm.steps.job.subtitle": "Company & Position",
|
||||
"loanOrderForm.steps.files.subtitle": "Passport Photos",
|
||||
"loanOrderForm.steps.guarantor.subtitle": "Guarantor Info",
|
||||
"loanOrderForm.steps.guarantor2.subtitle": "2nd Guarantor Info",
|
||||
"loanOrderForm.placeholders.select": "Select",
|
||||
"loanOrderForm.placeholders.searchableSelect": "Click to select",
|
||||
"loanOrderForm.placeholders.note": "Note...",
|
||||
|
||||
@@ -433,6 +433,12 @@
|
||||
"loanPaidOffLetters.regions.DA": "Дашогуз",
|
||||
"loanPaidOffLetters.regions.LE": "Лебап",
|
||||
"loanPaidOffLetters.regions.MA": "Мары",
|
||||
"loanOrders.regions.AG": "Ашхабад",
|
||||
"loanOrders.regions.AH": "Ахал",
|
||||
"loanOrders.regions.BN": "Балкан",
|
||||
"loanOrders.regions.DZ": "Дашогуз",
|
||||
"loanOrders.regions.LB": "Лебап",
|
||||
"loanOrders.regions.MR": "Мары",
|
||||
"loanPaidOffLetters.sections.info": "Основная информация",
|
||||
"loanPaidOffLetters.sections.customer": "Информация о клиенте",
|
||||
"loanPaidOffLetters.sections.passport": "Паспорт",
|
||||
@@ -452,7 +458,9 @@
|
||||
"loanPaidOffLetters.fields.loanFile": "Файл",
|
||||
"loanPaidOffLetters.fields.region": "Регион",
|
||||
"loanPaidOffLetters.fields.branchId": "ID филиала",
|
||||
"loanPaidOffLetters.fields.branchName": "Название филиала",
|
||||
"loanPaidOffLetters.fields.userId": "ID пользователя",
|
||||
"loanPaidOffLetters.fields.userName": "Имя пользователя",
|
||||
"loanPaidOffLetters.fields.status": "Статус",
|
||||
"loanPaidOffLetters.fields.uniqueId": "Уникальный ID",
|
||||
"loanPaidOffLetters.fields.notes": "Заметки",
|
||||
@@ -468,6 +476,7 @@
|
||||
"loanRemaining.columns.passportId": "Номер паспорта",
|
||||
"loanRemaining.columns.passportSerie": "Серия паспорта",
|
||||
"loanRemaining.columns.userId": "ID пользователя",
|
||||
"loanRemaining.columns.userName": "Имя пользователя",
|
||||
"loanOrderStatus.GARAŞYLÝAR": "В ОЖИДАНИИ",
|
||||
"loanOrderStatus.KANAGATLANDYRYLAN": "ОДОБРЕНО",
|
||||
"loanOrderStatus.RED_EDILDI": "ОТКЛОНЕНО",
|
||||
@@ -532,6 +541,11 @@
|
||||
"Status": "Статус",
|
||||
"Card (Salary)": "Карта (Зарплата)",
|
||||
"1. Guarantor": "1. Поручитель",
|
||||
"2. Guarantor": "2. Поручитель",
|
||||
"Guarantor 2 name": "Имя 2-го поручителя",
|
||||
"Guarantor 2 Surname": "Фамилия 2-го поручителя",
|
||||
"Guarantor 2 Patronic name": "Отчество 2-го поручителя",
|
||||
"Guarantor Note": "Заметка поручителя",
|
||||
"Loan history": "Кредитная история",
|
||||
"loanOrderForm.labels.status": "Статус",
|
||||
"loanOrderForm.labels.loanAmount": "Сумма кредита",
|
||||
@@ -548,6 +562,7 @@
|
||||
"loanOrderForm.steps.job.subtitle": "Компания и должность",
|
||||
"loanOrderForm.steps.files.subtitle": "Фото паспорта",
|
||||
"loanOrderForm.steps.guarantor.subtitle": "Информация о поручителе",
|
||||
"loanOrderForm.steps.guarantor2.subtitle": "Информация о 2-м поручителе",
|
||||
"loanOrderForm.placeholders.select": "Выберите",
|
||||
"loanOrderForm.placeholders.searchableSelect": "Нажмите для выбора",
|
||||
"loanOrderForm.placeholders.note": "Примечание...",
|
||||
|
||||
@@ -433,6 +433,12 @@
|
||||
"loanPaidOffLetters.regions.DA": "Daşoguz",
|
||||
"loanPaidOffLetters.regions.LE": "Lebap",
|
||||
"loanPaidOffLetters.regions.MA": "Mary",
|
||||
"loanOrders.regions.AG": "Aşgabat",
|
||||
"loanOrders.regions.AH": "Ahal",
|
||||
"loanOrders.regions.BN": "Balkan",
|
||||
"loanOrders.regions.DZ": "Daşoguz",
|
||||
"loanOrders.regions.LB": "Lebap",
|
||||
"loanOrders.regions.MR": "Mary",
|
||||
"loanPaidOffLetters.sections.info": "Esasy maglumatlar",
|
||||
"loanPaidOffLetters.sections.customer": "Müşderi maglumatlary",
|
||||
"loanPaidOffLetters.sections.passport": "Pasport",
|
||||
@@ -452,7 +458,9 @@
|
||||
"loanPaidOffLetters.fields.loanFile": "Faýl",
|
||||
"loanPaidOffLetters.fields.region": "Sebit",
|
||||
"loanPaidOffLetters.fields.branchId": "Şahamça ID",
|
||||
"loanPaidOffLetters.fields.branchName": "Şahamça ady",
|
||||
"loanPaidOffLetters.fields.userId": "Ulanyjy ID",
|
||||
"loanPaidOffLetters.fields.userName": "Ulanyjy ady",
|
||||
"loanPaidOffLetters.fields.status": "Status",
|
||||
"loanPaidOffLetters.fields.uniqueId": "Unikal ID",
|
||||
"loanPaidOffLetters.fields.notes": "Bellikler",
|
||||
@@ -532,6 +540,11 @@
|
||||
"Status": "Ýagdaý",
|
||||
"Card (Salary)": "Kart (Zähmet haky)",
|
||||
"1. Guarantor": "1. Zamun",
|
||||
"2. Guarantor": "2. Zamun",
|
||||
"Guarantor 2 name": "2. Zamunyň ady",
|
||||
"Guarantor 2 Surname": "2. Zamunyň familiýasy",
|
||||
"Guarantor 2 Patronic name": "2. Zamunyň atasynyň ady",
|
||||
"Guarantor Note": "Zamun belligi",
|
||||
"Loan history": "Karz taryhy",
|
||||
"loanOrderForm.labels.status": "Status",
|
||||
"loanOrderForm.labels.loanAmount": "Karz möçberi",
|
||||
@@ -548,6 +561,7 @@
|
||||
"loanOrderForm.steps.job.subtitle": "Kärhana we wezipe",
|
||||
"loanOrderForm.steps.files.subtitle": "Pasport suratlary",
|
||||
"loanOrderForm.steps.guarantor.subtitle": "Zamun maglumatlary",
|
||||
"loanOrderForm.steps.guarantor2.subtitle": "2. Zamun maglumatlary",
|
||||
"loanOrderForm.placeholders.select": "Saýlaň",
|
||||
"loanOrderForm.placeholders.searchableSelect": "Saýlamak üçin basyň",
|
||||
"loanOrderForm.placeholders.note": "Bellik...",
|
||||
@@ -1088,6 +1102,7 @@
|
||||
"loanRemaining.columns.passportSeries": "Pasport seriýasy",
|
||||
"loanRemaining.columns.passportNumber": "Pasport belgisi",
|
||||
"loanRemaining.columns.loanAccount": "Karz hasaby",
|
||||
"loanRemaining.columns.userName": "Ulanyjy ady",
|
||||
"common.print": "Çap etmek",
|
||||
"common.export": "Eksport",
|
||||
"common.deleting": "Pozulýar...",
|
||||
|
||||
@@ -145,7 +145,7 @@ export default function LoanOrderViewPage() {
|
||||
|
||||
{/* Location */}
|
||||
<BentoCard title={t("loanOrders.sections.location", "Lokasiýa")}>
|
||||
<InfoRow label={t("loanOrders.columns.region", "Welaýat")} value={order.region} />
|
||||
<InfoRow label={t("loanOrders.columns.region", "Welaýat")} value={t(`loanOrders.regions.${order.region}`, order.region)} />
|
||||
<InfoRow
|
||||
label={t("loanOrders.columns.branch", "Şahamça")}
|
||||
value={order.branch}
|
||||
|
||||
@@ -37,14 +37,7 @@ const COLUMN_IDS = ["id", "loanType", "createdAt", "region", "branch", "firstNam
|
||||
|
||||
// ─── Filter fields ────────────────────────────────────────────────────────────
|
||||
|
||||
const REGION_OPTIONS = [
|
||||
{ value: "Balkan", label: "Balkan" },
|
||||
{ value: "Ahal", label: "Ahal" },
|
||||
{ value: "Daşoguz", label: "Daşoguz" },
|
||||
{ value: "Lebap", label: "Lebap" },
|
||||
{ value: "Mary", label: "Mary" },
|
||||
{ value: "Aşgabat", label: "Aşgabat" },
|
||||
];
|
||||
const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const;
|
||||
|
||||
// ─── Page Component ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -82,6 +75,8 @@ export default function LoanOrdersPage() {
|
||||
const { data, isLoading } = useLoanOrders(queryParams);
|
||||
const totalPages = data ? Math.ceil(data.total / perPage) : 1;
|
||||
|
||||
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);
|
||||
@@ -128,7 +123,9 @@ export default function LoanOrdersPage() {
|
||||
id: "region",
|
||||
accessorKey: "region",
|
||||
header: t("Region", "WELAÝAT"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.region}</span>,
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground">{t(`loanOrders.regions.${row.original.region}`, row.original.region)}</span>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
@@ -191,7 +188,7 @@ export default function LoanOrdersPage() {
|
||||
{
|
||||
id: "region",
|
||||
label: t("Region", "WELAÝAT"),
|
||||
options: REGION_OPTIONS,
|
||||
options: regionOptions,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
@@ -212,7 +209,7 @@ export default function LoanOrdersPage() {
|
||||
],
|
||||
},
|
||||
],
|
||||
[t],
|
||||
[t, regionOptions],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,19 +1,28 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Trash2, Pencil } from "lucide-react";
|
||||
import { Trash2, Pencil, FileText, ExternalLink } from "lucide-react";
|
||||
import { useLoanPaidOffLetterById, useDeleteLoanPaidOffLetter } from "@/features/loanPaidOffLetters/hooks/useLoanPaidOffLetters";
|
||||
import { StatusBadge } from "@/components/ui/statusBadge";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents";
|
||||
import { ConfirmDialog } from "@/components/confirmDialog";
|
||||
import { STATUS_BADGE_VARIANTS } from "@/constants";
|
||||
import { buildFileUrl } from "@/features/shared/api/sharedApi";
|
||||
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
|
||||
function formatDate(value: string | null | undefined): string {
|
||||
if (!value) return "—";
|
||||
return value.slice(0, 10);
|
||||
}
|
||||
|
||||
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 ?? "";
|
||||
}
|
||||
|
||||
function LoanPaidOffLetterViewSkeleton() {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
@@ -33,7 +42,7 @@ function LoanPaidOffLetterViewSkeleton() {
|
||||
}
|
||||
|
||||
export default function LoanPaidOffLettersViewPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const deleteMutation = useDeleteLoanPaidOffLetter();
|
||||
@@ -117,20 +126,35 @@ export default function LoanPaidOffLettersViewPage() {
|
||||
/>
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.loanAmount", "Karz möçberi")} value={record.loanAmount || "—"} />
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.loanReason", "Karz sebäbi")} value={record.loanReason || "—"} />
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.loanFile", "Faýl")} value={record.loanFile || "—"} />
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.loanFile", "Faýl")}>
|
||||
{record.loanFile ? (
|
||||
<a
|
||||
href={record.loanFile.startsWith("http") ? record.loanFile : buildFileUrl(record.loanFile)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-primary/10 text-primary text-xs font-medium hover:bg-primary/20 transition-colors"
|
||||
>
|
||||
<FileText size={14} />
|
||||
<span className="truncate max-w-[220px]">{decodeURIComponent(record.loanFile.split("/").pop() || record.loanFile)}</span>
|
||||
<ExternalLink size={12} className="ml-1 opacity-70 shrink-0" />
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
)}
|
||||
</InfoRow>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("loanPaidOffLetters.sections.additional", "Goşmaça")}>
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.region", "Sebit")} value={record.region || "—"} />
|
||||
<InfoRow
|
||||
label={t("loanPaidOffLetters.fields.branchId", "Şahamça ID")}
|
||||
value={record.branchId != null ? String(record.branchId) : "—"}
|
||||
label={t("loanPaidOffLetters.fields.branchName", "Şahamça")}
|
||||
value={resolveLocalizedName(record.branchName, i18n.language) || (record.branchId != null ? String(record.branchId) : "—")}
|
||||
isLink={Boolean(record.branchId)}
|
||||
href={record.branchId ? `/settings/location/branches/${record.branchId}` : undefined}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("loanPaidOffLetters.fields.userId", "Ulanyjy ID")}
|
||||
value={record.userId != null ? String(record.userId) : "—"}
|
||||
label={t("loanPaidOffLetters.fields.userName", "Ulanyjy ady")}
|
||||
value={record.userName || (record.userId != null ? String(record.userId) : "—")}
|
||||
isLink={Boolean(record.userId)}
|
||||
href={record.userId ? `/all-users/${record.userId}` : undefined}
|
||||
/>
|
||||
|
||||
@@ -79,6 +79,12 @@ export default function LoanRemainingViewPage() {
|
||||
<Section title={t("loanRemaining.sections.info", "Esasy maglumatlar")}>
|
||||
<InfoRow label={t("common.id", "ID")} value={String(record.id)} />
|
||||
<InfoRow label={t("loanRemaining.columns.userId", "Ulanyjy ID")} value={String(record.userId)} />
|
||||
<InfoRow
|
||||
label={t("loanRemaining.columns.userName", "Ulanyjy ady")}
|
||||
isLink
|
||||
href={`/all-users/${record.userId}`}
|
||||
value={String(record.userName)}
|
||||
/>
|
||||
<InfoRow label={t("loanRemaining.columns.passportSerie", "Pasport seriýasy")} value={record.passportSerie} />
|
||||
<InfoRow label={t("loanRemaining.columns.passportId", "Pasport belgisi")} value={record.passportId} />
|
||||
<InfoRow label={t("loanRemaining.columns.accountNumber", "Karz hasaby")} value={record.accountNumber} />
|
||||
|
||||
Reference in New Issue
Block a user