started connect with api

This commit is contained in:
Jelaletdin12
2026-08-11 22:48:25 +05:00
parent 0ca218505d
commit 6da59f42d9
112 changed files with 7091 additions and 6989 deletions

View File

@@ -1,163 +1,70 @@
import apiClient from "@/lib/api/client";
// ─── Types ────────────────────────────────────────────────────────────────────
export interface LoanDocumentTranslation {
tk: string
ru: string
en: string
export interface LoanDocument {
id: number;
name: string;
value: string;
active: boolean;
createdAt: string;
updatedAt: string;
}
export interface LoanDocument {
id: number
name: LoanDocumentTranslation
description: LoanDocumentTranslation
createdAt: string
updatedAt: string
export interface LoanDocumentListParams {
page?: number;
limit?: number;
search?: string;
active?: string;
}
export interface LoanDocumentListResponse {
count: number;
loansDocuments: LoanDocument[];
}
export interface LoanDocumentPayload {
name: LoanDocumentTranslation
description: LoanDocumentTranslation
active: boolean;
name: string;
value: string;
}
export interface PaginatedResponse<T> {
data: T[]
total: number
page: number
perPage: number
totalPages: number
}
export interface ListParams {
page?: number
perPage?: number
search?: string
}
// ─── Mock Data ────────────────────────────────────────────────────────────────
const MOCK_LOAN_DOCUMENTS: LoanDocument[] = [
{
id: 1,
name: {
tk: 'Hormatly müşderi! Siziň ýüztutmaňyz kanagatlandyryldy!',
ru: 'Уважаемый клиент! Ваше обращение удовлетворено!',
en: 'Dear customer! Your request has been approved!',
},
description: {
tk: 'Siziň karz sargydyňyz üstünlikli kabul edildi we tassyklandy.',
ru: 'Ваша заявка на кредит успешно принята и подтверждена.',
en: 'Your loan application has been successfully received and confirmed.',
},
createdAt: '2026-01-15T10:30:00Z',
updatedAt: '2026-01-15T10:30:00Z',
},
{
id: 2,
name: {
tk: 'Hormatly müşderi! Siziň ýüztutmaňyz kanagatlandyrylmady!',
ru: 'Уважаемый клиент! Ваше обращение не удовлетворено!',
en: 'Dear customer! Your request has been rejected!',
},
description: {
tk: 'Siziň bank kart maglumatlaryňyz tapylmandygy sebäpli Siziň ýüztutmaňyz kanagatlandyrylmady! Bank kartyňyz boýunça hyzmat ediji bankyňyza ýüz tutmagyňyzy Sizden haýyş edýäris.',
ru: 'Ваше обращение не удовлетворено в связи с тем, что данные вашей банковской карты не найдены! Просим вас обратиться в банк, обслуживающий вашу банковскую карту.',
en: 'Your request has been rejected because your bank card information was not found! We kindly ask you to contact the bank that services your card.',
},
createdAt: '2026-02-20T14:15:00Z',
updatedAt: '2026-03-10T09:00:00Z',
},
{
id: 3,
name: {
tk: 'Karz resminama talap edilýär',
ru: 'Требуется документ для кредита',
en: 'Loan document required',
},
description: {
tk: 'Karz almak üçin zerur resminamalary tabşyrmagyňyzy haýyş edýäris.',
ru: 'Просим вас предоставить необходимые документы для получения кредита.',
en: 'Please submit the required documents to obtain the loan.',
},
createdAt: '2026-03-05T08:00:00Z',
updatedAt: '2026-03-05T08:00:00Z',
},
]
let mockStore = [...MOCK_LOAN_DOCUMENTS]
let nextId = mockStore.length + 1
// ─── Simulated delay ──────────────────────────────────────────────────────────
const delay = (ms = 400) => new Promise((r) => setTimeout(r, ms))
// ─── API Functions ────────────────────────────────────────────────────────────
export async function fetchLoanDocuments(
params: ListParams = {}
): Promise<PaginatedResponse<LoanDocument>> {
await delay()
const { page = 1, perPage = 10, search = '' } = params
let filtered = mockStore
if (search.trim()) {
const q = search.toLowerCase()
filtered = mockStore.filter(
(d) =>
d.name.tk.toLowerCase().includes(q) ||
d.name.ru.toLowerCase().includes(q) ||
d.name.en.toLowerCase().includes(q)
)
}
const total = filtered.length
const totalPages = Math.ceil(total / perPage)
const start = (page - 1) * perPage
const data = filtered.slice(start, start + perPage)
return { data, total, page, perPage, totalPages }
export async function fetchLoanDocuments(params: LoanDocumentListParams = {}, signal?: AbortSignal): Promise<LoanDocumentListResponse> {
const { page, limit, search, active } = params;
const { data } = await apiClient.get<LoanDocumentListResponse>("/loans-documents", {
params: {
page,
limit,
document_name: search || undefined,
active: active || undefined,
},
signal,
});
return data;
}
export async function fetchLoanDocumentById(id: number): Promise<LoanDocument> {
await delay()
const doc = mockStore.find((d) => d.id === id)
if (!doc) throw new Error(`LoanDocument with id ${id} not found`)
return { ...doc }
const { data } = await apiClient.get<LoanDocument>(`/loans-documents/${id}`);
return data;
}
export async function createLoanDocument(
payload: LoanDocumentPayload
): Promise<LoanDocument> {
await delay(600)
const now = new Date().toISOString()
const newDoc: LoanDocument = {
id: nextId++,
...payload,
createdAt: now,
updatedAt: now,
}
mockStore = [newDoc, ...mockStore]
return { ...newDoc }
export async function createLoanDocument(payload: LoanDocumentPayload): Promise<LoanDocument> {
const { data } = await apiClient.post<LoanDocument>("/loans-documents", payload);
return data;
}
export async function updateLoanDocument(
id: number,
payload: LoanDocumentPayload
): Promise<LoanDocument> {
await delay(600)
const index = mockStore.findIndex((d) => d.id === id)
if (index === -1) throw new Error(`LoanDocument with id ${id} not found`)
const updated: LoanDocument = {
...mockStore[index],
...payload,
updatedAt: new Date().toISOString(),
}
mockStore = mockStore.map((d) => (d.id === id ? updated : d))
return { ...updated }
export async function updateLoanDocument(id: number, payload: LoanDocumentPayload): Promise<LoanDocument> {
const { data } = await apiClient.put<LoanDocument>(`/loans-documents/${id}`, payload);
return data;
}
export async function deleteLoanDocument(id: number): Promise<void> {
await delay(400)
const exists = mockStore.some((d) => d.id === id)
if (!exists) throw new Error(`LoanDocument with id ${id} not found`)
mockStore = mockStore.filter((d) => d.id !== id)
}
await apiClient.delete(`/loans-documents/${id}`);
}
export async function updateLoanDocumentActive(id: number, active: boolean): Promise<LoanDocument> {
const { data } = await apiClient.put<LoanDocument>(`/loans-documents/${id}/active`, { active });
return data;
}

View File

@@ -1,381 +1,34 @@
import { useState, useEffect, useMemo, useCallback, useRef } from "react";
import { useCallback, useMemo, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Link from "@tiptap/extension-link";
import Underline from "@tiptap/extension-underline";
import {
Bold,
Italic,
Strikethrough,
Link2,
Heading2,
Quote,
Code,
List,
ListOrdered,
Minus,
WrapText,
Paperclip,
Type,
X,
FileText,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { FormInput } from "@/components/formInput";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { FormActions } from "@/components/formActions";
import { BentoGrid, BentoCard } from "@/components/bento";
import { useCreateRequiredDocument, useUpdateRequiredDocument } from "../hooks/useRequiredDocuments";
import type { LoanDocument } from "../api/requiredDocumentsApi";
import { createRequiredDocumentFormSchema, DEFAULT_FORM_VALUES, buildPayload, mapInitial } from "../schemas/requiredDocument.schema";
import type { RequiredDocumentFormData } from "../schemas/requiredDocument.schema";
import type { LoanDocument, LoanDocumentTranslation } from "../api/requiredDocumentsApi";
// ─── Types ────────────────────────────────────────────────────────────────────
type Locale = "tk" | "ru" | "en";
type FormMode = "create" | "edit";
interface RequiredDocumentFormProps {
mode: "create" | "edit";
mode: FormMode;
initialData?: LoanDocument;
}
// ─── Lang tabs ────────────────────────────────────────────────────────────────
type FlatErrors = Partial<Record<keyof RequiredDocumentFormData, string>>;
const LOCALES: Locale[] = ["tk", "ru", "en"];
// ─── Tiptap Toolbar ───────────────────────────────────────────────────────────
interface RichTextToolbarProps {
editor: ReturnType<typeof useEditor>;
onFileAttach?: (file: File) => void;
}
// ─── RichTextToolbar ─────────────────────────────────────────────────────────
function RichTextToolbar({ editor, onFileAttach }: RichTextToolbarProps) {
const [showLinkModal, setShowLinkModal] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
if (!editor) return null;
const handleLinkConfirm = (url: string) => {
if (url) {
const href = url.startsWith("http") ? url : `https://${url}`;
editor.chain().focus().setLink({ href }).run();
}
setShowLinkModal(false);
};
const handleAttachmentClick = () => fileInputRef.current?.click();
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
onFileAttach?.(file);
editor.chain().focus().insertContent(`<span>📎 ${file.name}</span> `).run();
e.target.value = "";
};
const tools = [
{
icon: Bold,
action: () => editor.chain().focus().toggleBold().run(),
active: editor.isActive("bold"),
title: "Bold",
},
{
icon: Italic,
action: () => editor.chain().focus().toggleItalic().run(),
active: editor.isActive("italic"),
title: "Italic",
},
{
icon: Strikethrough,
action: () => editor.chain().focus().toggleStrike().run(),
active: editor.isActive("strike"),
title: "Strike",
},
{
icon: Link2,
action: () => setShowLinkModal(true),
active: editor.isActive("link"),
title: "Link",
},
{
icon: Heading2,
action: () => editor.chain().focus().toggleHeading({ level: 2 }).run(),
active: editor.isActive("heading", { level: 2 }),
title: "H2",
},
{
icon: Quote,
action: () => editor.chain().focus().toggleBlockquote().run(),
active: editor.isActive("blockquote"),
title: "Quote",
},
{
icon: Code,
action: () => editor.chain().focus().toggleCodeBlock().run(),
active: editor.isActive("codeBlock"),
title: "Code Block",
},
{
icon: List,
action: () => editor.chain().focus().toggleBulletList().run(),
active: editor.isActive("bulletList"),
title: "Bullet List",
},
{
icon: ListOrdered,
action: () => editor.chain().focus().toggleOrderedList().run(),
active: editor.isActive("orderedList"),
title: "Ordered List",
},
{
icon: Minus,
action: () => editor.chain().focus().setHorizontalRule().run(),
active: false,
title: "Divider",
},
{
icon: WrapText,
action: () => editor.chain().focus().setHardBreak().run(),
active: false,
title: "Hard Break",
},
{
icon: Paperclip,
action: handleAttachmentClick,
active: false,
title: "Attachment",
},
{
icon: Type,
action: () => editor.chain().focus().selectAll().clearNodes().unsetAllMarks().run(),
active: false,
title: "Clear format",
},
];
return (
<>
<div className="flex flex-wrap items-center gap-0.5 p-1.5 border-b border-border bg-muted/30">
{
// eslint-disable-next-line react-hooks/refs
tools.map(({ icon: Icon, action, active, title }) => (
<button
key={title}
type="button"
title={title}
onMouseDown={(e) => {
e.preventDefault();
action();
}}
className={cn(
"flex items-center justify-center w-7 h-7 rounded text-muted-foreground",
"hover:bg-muted hover:text-foreground transition-colors",
active && "bg-primary/10 text-primary",
)}
>
<Icon size={14} />
</button>
))
}
<input ref={fileInputRef} type="file" className="hidden" onChange={handleFileChange} />
</div>
{/* Link modal */}
{showLinkModal && <LinkModal onConfirm={handleLinkConfirm} onClose={() => setShowLinkModal(false)} />}
</>
);
}
// ─── Link Modal ───────────────────────────────────────────────────────────────
function LinkModal({ onConfirm, onClose }: { onConfirm: (url: string) => void; onClose: () => void }) {
const [url, setUrl] = useState("");
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40"
onMouseDown={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<div className="bg-background border border-border rounded-lg shadow-lg p-4 w-80 flex flex-col gap-3">
<p className="text-sm font-medium">URL giriziň</p>
<input
autoFocus
type="url"
value={url}
onChange={(e) => setUrl(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") onConfirm(url);
if (e.key === "Escape") onClose();
}}
placeholder="https://..."
className="border border-input rounded px-2 py-1.5 text-sm w-full focus:outline-none focus:ring-1 focus:ring-ring"
/>
<div className="flex justify-end gap-2">
<button type="button" onClick={onClose} className="text-sm px-3 py-1 rounded hover:bg-muted text-muted-foreground">
Ýatyr
</button>
<button
type="button"
onClick={() => onConfirm(url)}
className="text-sm px-3 py-1 rounded bg-primary text-primary-foreground hover:bg-primary/90"
>
Goş
</button>
</div>
</div>
</div>
);
}
// ─── RichTextEditor ───────────────────────────────────────────────────────────
interface RichTextEditorProps {
value: string;
onChange: (html: string) => void;
error?: string;
onFileAttach?: (file: File) => void;
}
function RichTextEditor({ value, onChange, error, onFileAttach }: RichTextEditorProps) {
const editor = useEditor({
extensions: [
StarterKit.configure({
heading: { levels: [1, 2, 3] },
code: {},
blockquote: {},
bulletList: {},
orderedList: {},
horizontalRule: {},
hardBreak: {},
}),
Underline,
Link.configure({
openOnClick: false,
autolink: true,
HTMLAttributes: {
rel: "noopener noreferrer",
target: "_blank",
},
}),
],
content: value,
onUpdate: ({ editor }) => onChange(editor.getHTML()),
});
// Sync external value changes (e.g. tab switch)
useEffect(() => {
if (editor && editor.getHTML() !== value) {
editor.commands.setContent(value, { emitUpdate: false });
}
}, [value, editor]);
return (
<div
className={cn(
"rounded-md border bg-background overflow-hidden",
error ? "border-destructive" : "border-input",
"focus-within:ring-1 focus-within:ring-ring",
)}
>
<RichTextToolbar editor={editor} onFileAttach={onFileAttach} />
<EditorContent
editor={editor}
className="min-h-[120px] px-3 py-2 text-sm text-foreground prose prose-sm dark:prose-invert max-w-none focus:outline-none [&_.ProseMirror]:focus:outline-none [&_.ProseMirror_a]:text-primary [&_.ProseMirror_a]:underline [&_.ProseMirror_a]:cursor-pointer"
/>
{error && (
<p className="px-3 pb-2 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>
)}
</div>
);
}
// ─── AttachedFilesList ────────────────────────────────────────────────────────
interface AttachedFilesListProps {
files: File[];
onRemove: (index: number) => void;
}
function AttachedFilesList({ files, onRemove }: AttachedFilesListProps) {
if (files.length === 0) return null;
return (
<div className="mt-2 flex flex-col gap-1">
{files.map((file, i) => (
<div key={`${file.name}-${i}`} className="flex items-center gap-2 text-xs text-muted-foreground bg-muted/40 rounded px-2 py-1.5">
<FileText size={12} className="shrink-0 text-primary" />
<span className="flex-1 truncate">{file.name}</span>
<span className="shrink-0 text-muted-foreground/60">{(file.size / 1024).toFixed(1)} KB</span>
<button type="button" onClick={() => onRemove(i)} className="shrink-0 hover:text-destructive transition-colors ml-1">
<X size={12} />
</button>
</div>
))}
</div>
);
}
// ─── LangTabs ────────────────────────────────────────────────────────────────
interface LangTabsProps {
active: Locale;
onChange: (locale: Locale) => void;
}
function LangTabs({ active, onChange }: LangTabsProps) {
const { t } = useTranslation();
return (
<div className="flex items-center justify-end gap-3 mb-2">
{LOCALES.map((code) => (
<button
key={code}
type="button"
onClick={() => onChange(code)}
className={cn(
"text-sm transition-colors",
active === code ? "text-primary font-semibold underline underline-offset-4" : "text-muted-foreground hover:text-foreground",
)}
>
{t("languages." + code, code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English")}
</button>
))}
</div>
);
}
// ─── Error helpers ──────────────────────────────────────────────────────────
type LegacyErrorKey = `name_${Locale}` | `desc_${Locale}`;
const RHF_TO_LEGACY_KEY: Record<string, LegacyErrorKey> = {
nameTk: "name_tk",
nameRu: "name_ru",
nameEn: "name_en",
descTk: "desc_tk",
descRu: "desc_ru",
descEn: "desc_en",
};
function flattenErrors(errors: Record<string, { message?: string } | undefined>): Partial<Record<LegacyErrorKey, string>> {
const result: Partial<Record<LegacyErrorKey, string>> = {};
for (const [key, err] of Object.entries(errors)) {
const legacyKey = RHF_TO_LEGACY_KEY[key];
if (legacyKey && err?.message) {
result[legacyKey] = err.message;
}
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
const result: FlatErrors = {};
for (const key of Object.keys(errors)) {
const msg = errors[key]?.message;
if (msg) result[key as keyof RequiredDocumentFormData] = msg;
}
return result;
}
@@ -390,21 +43,6 @@ export function RequiredDocumentForm({ mode, initialData }: RequiredDocumentForm
);
const navigate = useNavigate();
// Per-field locale tabs (UI only, not form state)
const [nameLang, setNameLang] = useState<Locale>("tk");
const [descLang, setDescLang] = useState<Locale>("tk");
// ── Attached files — stored as File[] for FormData submission ──────────────
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const handleFileAttach = useCallback((file: File) => {
setAttachedFiles((prev) => [...prev, file]);
}, []);
const handleFileRemove = useCallback((index: number) => {
setAttachedFiles((prev) => prev.filter((_, i) => i !== index));
}, []);
const createMutation = useCreateRequiredDocument();
const updateMutation = useUpdateRequiredDocument(initialData?.id ?? 0);
@@ -415,9 +53,10 @@ export function RequiredDocumentForm({ mode, initialData }: RequiredDocumentForm
const {
watch,
setValue,
getValues,
formState: { errors: rhfErrors },
clearErrors,
trigger,
getValues,
} = useForm<RequiredDocumentFormData>({
resolver: zodResolver(schema),
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
@@ -428,84 +67,37 @@ export function RequiredDocumentForm({ mode, initialData }: RequiredDocumentForm
useEffect(() => {
if (Object.keys(rhfErrors).length > 0) trigger();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [i18n.language]);
const name: LoanDocumentTranslation = useMemo(
() => ({ tk: form.nameTk, ru: form.nameRu, en: form.nameEn }),
[form.nameTk, form.nameRu, form.nameEn],
);
const description: LoanDocumentTranslation = useMemo(
() => ({ tk: form.descTk, ru: form.descRu, en: form.descEn }),
[form.descTk, form.descRu, form.descEn],
);
const setName = useCallback(
(updater: (prev: LoanDocumentTranslation) => LoanDocumentTranslation) => {
const current = getValues();
const prev: LoanDocumentTranslation = {
tk: current.nameTk,
ru: current.nameRu,
en: current.nameEn,
};
const next = updater(prev);
setValue("nameTk", next.tk);
setValue("nameRu", next.ru);
setValue("nameEn", next.en);
const set = useCallback(
(key: keyof RequiredDocumentFormData) => (value: string | boolean) => {
(setValue as (k: keyof RequiredDocumentFormData, v: string | boolean) => void)(key, value);
clearErrors(key);
},
[setValue, getValues],
);
const setDescription = useCallback(
(updater: (prev: LoanDocumentTranslation) => LoanDocumentTranslation) => {
const current = getValues();
const prev: LoanDocumentTranslation = {
tk: current.descTk,
ru: current.descRu,
en: current.descEn,
};
const next = updater(prev);
setValue("descTk", next.tk);
setValue("descRu", next.ru);
setValue("descEn", next.en);
},
[setValue, getValues],
[setValue, clearErrors],
);
// ── Submit ──────────────────────────────────────────────────────────────────
const handleSubmit = async (e?: React.FormEvent) => {
e?.preventDefault();
const handleSubmit = async () => {
const isValid = await trigger();
if (!isValid) return;
const payload = buildPayload(getValues());
// Build FormData — JSON fields + all attached File objects
const formData = new FormData();
formData.append("name[tk]", payload.name.tk);
formData.append("name[ru]", payload.name.ru);
formData.append("name[en]", payload.name.en);
formData.append("description[tk]", payload.description.tk);
formData.append("description[ru]", payload.description.ru);
formData.append("description[en]", payload.description.en);
attachedFiles.forEach((file) => {
formData.append("files", file, file.name);
});
if (mode === "create") {
await createMutation.mutateAsync(payload);
navigate("/settings/loan/loan-documents");
const result = await createMutation.mutateAsync(payload);
navigate(`/settings/loan/required-documents/${result.id}`);
} else {
await updateMutation.mutateAsync(payload);
navigate("/settings/loan/loan-documents");
navigate(`/settings/loan/required-documents/${initialData!.id}`);
}
};
const submitLabel =
mode === "create"
? t("loanDocuments.form.create", "Karz gerekli resminamalary döretiň")
: t("loanDocuments.form.update", "Karz gerekli resminamalary täzele");
const handleCancel = () => navigate("/settings/loan/required-documents");
// ── Render ──────────────────────────────────────────────────────────────────
return (
<div className="flex flex-col gap-5">
@@ -514,58 +106,49 @@ export function RequiredDocumentForm({ mode, initialData }: RequiredDocumentForm
? t("loanDocuments.createTitle", "Karz gerekli resminama dörediň")
: t("loanDocuments.editTitle", "Karz gerekli resminama üýtgetmek")}
</h1>
<form onSubmit={handleSubmit} noValidate>
<BentoGrid cols={2}>
<BentoCard span="full">
<p className="text-sm font-semibold text-muted-foreground mb-1">
{t("loanDocuments.fields.name", "Ady")}
<span className="text-destructive ml-0.5">*</span>
</p>
<LangTabs active={nameLang} onChange={setNameLang} />
<FormInput
type="text"
value={name[nameLang]}
onChange={(val) => setName((prev) => ({ ...prev, [nameLang]: val }))}
placeholder={t("loanDocuments.fields.namePlaceholder", "Ady")}
error={errors[`name_${nameLang}`]}
/>
{LOCALES.filter((l) => l !== nameLang && errors[`name_${l}`]).map((code) => (
<p key={code} className="text-xs text-destructive/70">
{t("languages." + code, code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English")}: {errors[`name_${code}`]}
</p>
))}
</BentoCard>
<BentoCard span="full">
<p className="text-sm font-semibold text-muted-foreground mb-1">
{t("loanDocuments.fields.description", "Yazgy")}
<span className="text-destructive ml-0.5">*</span>
</p>
<LangTabs active={descLang} onChange={setDescLang} />
<RichTextEditor
value={description[descLang]}
onChange={(val) => setDescription((prev) => ({ ...prev, [descLang]: val }))}
error={errors[`desc_${descLang}`]}
onFileAttach={handleFileAttach}
/>
<AttachedFilesList files={attachedFiles} onRemove={handleFileRemove} />
{LOCALES.filter((l) => l !== descLang && errors[`desc_${l}`]).map((code) => (
<p key={code} className="text-xs text-destructive/70">
{t("languages." + code, code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English")}: {errors[`desc_${code}`]}
</p>
))}
</BentoCard>
</BentoGrid>
<FormActions
isPending={isPending}
onSubmit={handleSubmit}
onCancel={() => navigate("/settings/loan/loan-documents")}
cancelVariant="ghost"
loadingLabel={t("common.saving", "Saklanylýar...")}
submitLabel={submitLabel}
className="mt-4"
/>
</form>
<BentoGrid cols={2}>
<BentoCard>
<FormInput
type="text"
label={t("loanDocuments.fields.name", "Ady")}
value={form.name}
onChange={set("name")}
placeholder={t("loanDocuments.fields.namePlaceholder", "Ady")}
error={errors.name}
required
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("loanDocuments.fields.value", "Baha")}
value={form.value}
onChange={set("value")}
placeholder={t("loanDocuments.fields.valuePlaceholder", "Baha")}
error={errors.value}
required
/>
</BentoCard>
<BentoCard>
<div className="flex items-center gap-2 pt-1">
<span className="text-sm font-semibold text-muted-foreground">{t("loanDocuments.fields.isActive", "Işjeň")}</span>
<Checkbox id="isActive" checked={form.active} onCheckedChange={(checked) => set("active")(!!checked)} />
<Label htmlFor="isActive" className="text-sm text-foreground cursor-pointer">
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
</Label>
</div>
</BentoCard>
</BentoGrid>
<FormActions
isPending={isPending}
onSubmit={handleSubmit}
onCancel={handleCancel}
submitLabel={
mode === "create"
? t("loanDocuments.form.create", "Karz gerekli resminamalary döretiň")
: t("loanDocuments.form.update", "Karz gerekli resminamalary täzele")
}
/>
</div>
);
}

View File

@@ -1,87 +1,108 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
import {
fetchLoanDocuments,
fetchLoanDocumentById,
createLoanDocument,
updateLoanDocument,
updateLoanDocumentActive,
deleteLoanDocument,
type ListParams,
type LoanDocumentListParams,
type LoanDocumentPayload,
} from '../api/requiredDocumentsApi'
} from "../api/requiredDocumentsApi";
// ─── Query Keys ───────────────────────────────────────────────────────────────
export const requiredDocumentsKeys = {
all: ['requiredDocuments'] as const,
lists: () => [...requiredDocumentsKeys.all, 'list'] as const,
list: (params: ListParams) => [...requiredDocumentsKeys.lists(), params] as const,
details: () => [...requiredDocumentsKeys.all, 'detail'] as const,
all: ["requiredDocuments"] as const,
lists: () => [...requiredDocumentsKeys.all, "list"] as const,
list: (params: LoanDocumentListParams) => [...requiredDocumentsKeys.lists(), params] as const,
details: () => [...requiredDocumentsKeys.all, "detail"] as const,
detail: (id: number) => [...requiredDocumentsKeys.details(), id] as const,
};
// ─── useGetRequiredDocuments ──────────────────────────────────────────────────
export function useGetRequiredDocuments(params: LoanDocumentListParams = {}) {
const debouncedSearch = useDebouncedValue(params.search ?? "");
const queryParams: LoanDocumentListParams = { ...params, search: normalizeSearch(debouncedSearch) };
return useQuery({
queryKey: requiredDocumentsKeys.list(queryParams),
queryFn: ({ signal }) => fetchLoanDocuments(queryParams, signal),
placeholderData: (prev) => prev,
});
}
// ─── useGetLoanDocuments ──────────────────────────────────────────────────────
// ─── useGetRequiredDocumentById ───────────────────────────────────────────────
export function useGetRequiredDocuments(params: ListParams) {
export function useGetRequiredDocumentById(id: number | undefined) {
return useQuery({
queryKey: requiredDocumentsKeys.list(params),
queryFn: () => fetchLoanDocuments(params),
})
}
// ─── useGetLoanDocumentById ───────────────────────────────────────────────────
export function useGetRequiredDocumentById(id: number) {
return useQuery({
queryKey: requiredDocumentsKeys.detail(id),
queryFn: () => fetchLoanDocumentById(id),
queryKey: requiredDocumentsKeys.detail(id!),
queryFn: () => fetchLoanDocumentById(id!),
enabled: !!id,
})
});
}
// ─── useCreateLoanDocument ────────────────────────────────────────────────────
// ─── useCreateRequiredDocument ────────────────────────────────────────────────
export function useCreateRequiredDocument() {
const queryClient = useQueryClient()
const { t } = useTranslation()
const queryClient = useQueryClient();
const { t } = useTranslation();
return useMutation({
mutationFn: (payload: LoanDocumentPayload) => createLoanDocument(payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() })
toast.success(t('loanDocuments.toast.created', 'Resminama üstünlikli döredildi!'))
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() });
toast.success(t("loanDocuments.toast.created", "Resminama üstünlikli döredildi!"));
},
})
});
}
// ─── useUpdateLoanDocument ────────────────────────────────────────────────────
// ─── useUpdateRequiredDocument ────────────────────────────────────────────────
export function useUpdateRequiredDocument(id: number) {
const queryClient = useQueryClient()
const { t } = useTranslation()
const queryClient = useQueryClient();
const { t } = useTranslation();
return useMutation({
mutationFn: (payload: LoanDocumentPayload) => updateLoanDocument(id, payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() })
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.detail(id) })
toast.success(t('loanDocuments.toast.updated', 'Resminama üstünlikli täzelendi!'))
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() });
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.detail(id) });
toast.success(t("loanDocuments.toast.updated", "Resminama üstünlikli täzelendi!"));
},
})
});
}
// ─── useDeleteLoanDocument ────────────────────────────────────────────────────
// ─── useUpdateRequiredDocumentActive ──────────────────────────────────────────
export function useUpdateRequiredDocumentActive() {
const queryClient = useQueryClient();
const { t } = useTranslation();
return useMutation({
mutationFn: ({ id, active }: { id: number; active: boolean }) => updateLoanDocumentActive(id, active),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() });
toast.success(t("loanDocuments.toast.statusUpdated", "Resminama statusy üstünlikli täzelendi!"));
},
});
}
// ─── useDeleteRequiredDocument ────────────────────────────────────────────────
export function useDeleteRequiredDocument() {
const queryClient = useQueryClient()
const { t } = useTranslation()
const queryClient = useQueryClient();
const { t } = useTranslation();
return useMutation({
mutationFn: (id: number) => deleteLoanDocument(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() })
toast.success(t('loanDocuments.toast.deleted', 'Resminama üstünlikli öçürildi!'))
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() });
toast.success(t("loanDocuments.toast.deleted", "Resminama üstünlikli öçürildi!"));
},
})
}
});
}

View File

@@ -1,42 +1,34 @@
import { z } from 'zod'
import type { LoanDocument, LoanDocumentPayload } from '../api/requiredDocumentsApi'
import { z } from "zod";
import type { LoanDocument, LoanDocumentPayload } from "../api/requiredDocumentsApi";
export function createRequiredDocumentFormSchema(t: (key: string, fallback?: string) => string) {
return z.object({
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
descTk: z.string().min(1, t('validation.required', 'validation.required')),
descRu: z.string().min(1, t('validation.required', 'validation.required')),
descEn: z.string().min(1, t('validation.required', 'validation.required')),
})
name: z.string().min(1, t("validation.required", "validation.required")),
value: z.string().min(1, t("validation.required", "validation.required")),
active: z.boolean(),
});
}
export type RequiredDocumentFormData = z.infer<ReturnType<typeof createRequiredDocumentFormSchema>>
export type RequiredDocumentFormData = z.infer<ReturnType<typeof createRequiredDocumentFormSchema>>;
export const DEFAULT_FORM_VALUES: RequiredDocumentFormData = {
nameTk: '',
nameRu: '',
nameEn: '',
descTk: '',
descRu: '',
descEn: '',
}
name: "",
value: "",
active: true,
};
export function buildPayload(data: RequiredDocumentFormData): LoanDocumentPayload {
return {
name: { tk: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
description: { tk: data.descTk.trim(), ru: data.descRu.trim(), en: data.descEn.trim() },
}
name: data.name.trim(),
value: data.value.trim(),
active: data.active,
};
}
export function mapInitial(data: LoanDocument): RequiredDocumentFormData {
return {
nameTk: data.name.tk,
nameRu: data.name.ru,
nameEn: data.name.en,
descTk: data.description.tk,
descRu: data.description.ru,
descEn: data.description.en,
}
name: data.name,
value: data.value,
active: data.active,
};
}