added some settings page

This commit is contained in:
Jelaletdin12
2026-05-12 23:16:27 +05:00
parent f415acd649
commit a1d059a838
19 changed files with 2612 additions and 11 deletions

View File

@@ -0,0 +1,169 @@
// features/loanTypes/api/loanTypesApi.ts
export interface LoanTypeTranslation {
tk: string
ru: string
en: string
}
export interface LoanType {
id: number
name: LoanTypeTranslation
tax: number
loanTerm: number
notes: LoanTypeTranslation | null
isActive: boolean
createdAt: string
updatedAt: string
}
export interface LoanTypeListParams {
page?: number
perPage?: number
search?: string
}
export interface LoanTypeListResponse {
data: LoanType[]
total: number
page: number
perPage: number
totalPages: number
}
export interface CreateLoanTypePayload {
name: LoanTypeTranslation
tax: number
loanTerm: number
notes: LoanTypeTranslation | null
isActive: boolean
}
export type UpdateLoanTypePayload = CreateLoanTypePayload
// ─── Mock Data ────────────────────────────────────────────────────────────────
const MOCK_LOAN_TYPES: LoanType[] = [
{
id: 5,
name: { tk: 'Talyp karzy', ru: 'Студенческий кредит', en: 'Student Loan' },
tax: 1,
loanTerm: 30,
notes: { tk: 'Bellik', ru: 'Примечание', en: 'Note' },
isActive: true,
createdAt: '2026-01-10T08:00:00Z',
updatedAt: '2026-03-15T10:30:00Z',
},
{
id: 4,
name: {
tk: 'Üpjünçiligine girew emlägi bolan sarp ediş karzy',
ru: 'Потребительский кредит под залог имущества',
en: 'Consumer Loan Secured by Property',
},
tax: 1,
loanTerm: 30,
notes: null,
isActive: true,
createdAt: '2026-01-08T09:00:00Z',
updatedAt: '2026-02-20T11:00:00Z',
},
{
id: 3,
name: { tk: 'Kiçi göwrümli karzlar', ru: 'Микрокредиты', en: 'Micro Loans' },
tax: 1,
loanTerm: 30,
notes: null,
isActive: true,
createdAt: '2026-01-05T07:00:00Z',
updatedAt: '2026-01-05T07:00:00Z',
},
{
id: 2,
name: {
tk: 'Üpjünçiligine zamunlyk bolan sarp ediş karzy',
ru: 'Потребительский кредит под поручительство',
en: 'Consumer Loan with Guarantor',
},
tax: 1,
loanTerm: 30,
notes: null,
isActive: true,
createdAt: '2026-01-03T06:00:00Z',
updatedAt: '2026-01-03T06:00:00Z',
},
{
id: 1,
name: { tk: 'Ýaş çatynjalara', ru: 'Молодожёнам', en: 'Newlyweds Loan' },
tax: 1,
loanTerm: 30,
notes: null,
isActive: true,
createdAt: '2026-01-01T00:00:00Z',
updatedAt: '2026-01-01T00:00:00Z',
},
]
let _mockStore: LoanType[] = [...MOCK_LOAN_TYPES]
let _nextId = 6
const delay = (ms = 400) => new Promise<void>((res) => setTimeout(res, ms))
// ─── API Functions ────────────────────────────────────────────────────────────
export async function fetchLoanTypes(params: LoanTypeListParams = {}): Promise<LoanTypeListResponse> {
await delay()
const { page = 1, perPage = 25, search = '' } = params
const filtered = search.trim()
? _mockStore.filter((lt) =>
lt.name.tk.toLowerCase().includes(search.toLowerCase()) ||
lt.name.ru.toLowerCase().includes(search.toLowerCase()) ||
lt.name.en.toLowerCase().includes(search.toLowerCase())
)
: _mockStore
const sorted = [...filtered].sort((a, b) => b.id - a.id)
const start = (page - 1) * perPage
const data = sorted.slice(start, start + perPage)
return {
data,
total: filtered.length,
page,
perPage,
totalPages: Math.max(1, Math.ceil(filtered.length / perPage)),
}
}
export async function fetchLoanTypeById(id: number): Promise<LoanType> {
await delay()
const found = _mockStore.find((lt) => lt.id === id)
if (!found) throw new Error(`LoanType with id=${id} not found`)
return { ...found }
}
export async function createLoanType(payload: CreateLoanTypePayload): Promise<LoanType> {
await delay()
const newItem: LoanType = {
id: _nextId++,
...payload,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
}
_mockStore = [newItem, ..._mockStore]
return { ...newItem }
}
export async function updateLoanType(id: number, payload: UpdateLoanTypePayload): Promise<LoanType> {
await delay()
const idx = _mockStore.findIndex((lt) => lt.id === id)
if (idx === -1) throw new Error(`LoanType with id=${id} not found`)
_mockStore[idx] = { ..._mockStore[idx], ...payload, updatedAt: new Date().toISOString() }
return { ..._mockStore[idx] }
}
export async function deleteLoanType(id: number): Promise<void> {
await delay()
_mockStore = _mockStore.filter((lt) => lt.id !== id)
}

View File

@@ -0,0 +1,268 @@
// features/loanTypes/components/LoanTypeForm.tsx
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { FormInput } from '@/components/formInput'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import { useCreateLoanType, useUpdateLoanType } from '../hooks/useLoanTypes'
import type { LoanType, CreateLoanTypePayload } from '../api/loanTypesApi'
// ─── Types ────────────────────────────────────────────────────────────────────
type FormMode = 'create' | 'edit'
interface LoanTypeFormProps {
mode: FormMode
initialData?: LoanType
loanTypeId?: number
}
interface FormErrors {
nameTk?: string
nameRu?: string
nameEn?: string
tax?: string
loanTerm?: string
}
// ─── Language Tab ─────────────────────────────────────────────────────────────
type Lang = 'tk' | 'ru' | 'en'
const LANG_TABS: { key: Lang; label: string }[] = [
{ key: 'tk', label: 'Türkmen' },
{ key: 'ru', label: 'Русский' },
{ key: 'en', label: 'English' },
]
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(
nameTk: string,
nameRu: string,
nameEn: string,
tax: string,
loanTerm: string,
t: (key: string, fallback: string) => string
): FormErrors {
const errors: FormErrors = {}
if (!nameTk.trim()) errors.nameTk = t('validation.required', 'Hökmany meýdan')
if (!nameRu.trim()) errors.nameRu = t('validation.required', 'Hökmany meýdan')
if (!nameEn.trim()) errors.nameEn = t('validation.required', 'Hökmany meýdan')
if (!tax || Number(tax) <= 0) errors.tax = t('validation.positiveNumber', 'Oňyn san gerek')
if (!loanTerm || Number(loanTerm) <= 0) errors.loanTerm = t('validation.positiveNumber', 'Oňyn san gerek')
return errors
}
// ─── LoanTypeForm ─────────────────────────────────────────────────────────────
export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const createMutation = useCreateLoanType()
const updateMutation = useUpdateLoanType(loanTypeId ?? 0)
const isPending = createMutation.isPending || updateMutation.isPending
// ── State ──────────────────────────────────────────────────────────────────
const [activeLang, setActiveLang] = useState<Lang>('tk')
const [nameTk, setNameTk] = useState('')
const [nameRu, setNameRu] = useState('')
const [nameEn, setNameEn] = useState('')
const [notesTk, setNotesTk] = useState('')
const [notesRu, setNotesRu] = useState('')
const [notesEn, setNotesEn] = useState('')
const [tax, setTax] = useState('')
const [loanTerm, setLoanTerm] = useState('')
const [isActive, setIsActive] = useState(true)
const [errors, setErrors] = useState<FormErrors>({})
// ── Populate on edit ───────────────────────────────────────────────────────
useEffect(() => {
if (mode === 'edit' && initialData) {
setNameTk(initialData.name.tk)
setNameRu(initialData.name.ru)
setNameEn(initialData.name.en)
setNotesTk(initialData.notes?.tk ?? '')
setNotesRu(initialData.notes?.ru ?? '')
setNotesEn(initialData.notes?.en ?? '')
setTax(String(initialData.tax))
setLoanTerm(String(initialData.loanTerm))
setIsActive(initialData.isActive)
}
}, [mode, initialData])
// ── Submit ─────────────────────────────────────────────────────────────────
const handleSubmit = async () => {
const validationErrors = validate(nameTk, nameRu, nameEn, tax, loanTerm, t)
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors)
return
}
setErrors({})
const payload: CreateLoanTypePayload = {
name: { tk: nameTk.trim(), ru: nameRu.trim(), en: nameEn.trim() },
tax: Number(tax),
loanTerm: Number(loanTerm),
notes:
notesTk.trim() || notesRu.trim() || notesEn.trim()
? { tk: notesTk.trim(), ru: notesRu.trim(), en: notesEn.trim() }
: null,
isActive,
}
if (mode === 'create') {
const result = await createMutation.mutateAsync(payload)
navigate(`/resources/loan-types/${result.id}`)
} else {
await updateMutation.mutateAsync(payload)
navigate(`/resources/loan-types/${loanTypeId}`)
}
}
const handleCancel = () => navigate('/resources/loan-types')
// ── Name fields per lang ───────────────────────────────────────────────────
const nameFields: Record<Lang, { value: string; onChange: (v: string) => void; error?: string }> = {
tk: { value: nameTk, onChange: setNameTk, error: errors.nameTk },
ru: { value: nameRu, onChange: setNameRu, error: errors.nameRu },
en: { value: nameEn, onChange: setNameEn, error: errors.nameEn },
}
const notesFields: Record<Lang, { value: string; onChange: (v: string) => void }> = {
tk: { value: notesTk, onChange: setNotesTk },
ru: { value: notesRu, onChange: setNotesRu },
en: { value: notesEn, onChange: setNotesEn },
}
// ─────────────────────────────────────────────────────────────────────────
return (
<div className="space-y-0">
{/* Language tabs row */}
<div className="flex items-center justify-end gap-1 mb-0 pb-0">
{LANG_TABS.map((tab) => (
<button
key={tab.key}
type="button"
onClick={() => setActiveLang(tab.key)}
className={`px-3 py-1 text-sm rounded-md transition-colors ${
activeLang === tab.key
? 'text-primary font-semibold'
: 'text-muted-foreground hover:text-foreground'
}`}
>
{tab.label}
</button>
))}
</div>
{/* Form card */}
<div className="bg-card border border-border rounded-xl overflow-hidden divide-y divide-border">
{/* Ady */}
<div className="grid grid-cols-[220px_1fr] items-center px-4 py-3">
<span className="text-sm text-muted-foreground">
{t('loanTypes.fields.name', 'Ady')}
<span className="text-destructive ml-0.5">*</span>
</span>
<FormInput
type="text"
value={nameFields[activeLang].value}
onChange={nameFields[activeLang].onChange}
placeholder={t('loanTypes.fields.name', 'Ady')}
error={nameFields[activeLang].error}
/>
</div>
{/* Salgyt */}
<div className="grid grid-cols-[220px_1fr] items-center px-4 py-3">
<span className="text-sm text-muted-foreground">
{t('loanTypes.fields.tax', 'Salgyt')}
<span className="text-destructive ml-0.5">*</span>
</span>
<FormInput
type="number"
value={tax}
onChange={setTax}
placeholder={t('loanTypes.fields.tax', 'Salgyt')}
error={errors.tax}
/>
</div>
{/* Karz möhleti */}
<div className="grid grid-cols-[220px_1fr] items-center px-4 py-3">
<span className="text-sm text-muted-foreground">
{t('loanTypes.fields.loanTerm', 'Karz möhleti')}
<span className="text-destructive ml-0.5">*</span>
</span>
<FormInput
type="number"
value={loanTerm}
onChange={setLoanTerm}
placeholder={t('loanTypes.fields.loanTerm', 'Karz möhleti')}
error={errors.loanTerm}
/>
</div>
{/* Bellikler */}
<div className="grid grid-cols-[220px_1fr] items-center px-4 py-3">
<span className="text-sm text-muted-foreground">
{t('loanTypes.fields.notes', 'Bellikler')}
</span>
<FormInput
type="text"
value={notesFields[activeLang].value}
onChange={notesFields[activeLang].onChange}
placeholder={t('loanTypes.fields.notes', 'Bellikler')}
/>
</div>
{/* Işjeň */}
<div className="grid grid-cols-[220px_1fr] items-center px-4 py-3">
<span className="text-sm text-muted-foreground">
{t('loanTypes.fields.isActive', 'Işjeň')}
</span>
<div className="flex items-center gap-2">
<Checkbox
id="isActive"
checked={isActive}
/>
<Label htmlFor="isActive" className="text-sm text-foreground cursor-pointer">
{isActive
? t('common.active', 'Işjeň')
: t('common.inactive', 'Işjeň däl')}
</Label>
</div>
</div>
</div>
{/* Actions */}
<div className="flex items-center justify-end gap-3 pt-4">
<Button
type="button"
variant="ghost"
onClick={handleCancel}
disabled={isPending}
>
{t('common.cancel', 'Ýatyr')}
</Button>
<Button
type="button"
onClick={handleSubmit}
disabled={isPending}
>
{isPending
? t('common.saving', 'Saklanýar...')
: mode === 'create'
? t('loanTypes.actions.create', 'Karz görnüşi dörediň')
: t('loanTypes.actions.save', 'Ýatda sakla')}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,97 @@
// features/loanTypes/hooks/useLoanTypes.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import {
fetchLoanTypes,
fetchLoanTypeById,
createLoanType,
updateLoanType,
deleteLoanType,
type LoanTypeListParams,
type CreateLoanTypePayload,
type UpdateLoanTypePayload,
} from '../api/loanTypesApi'
// ─── Query Keys ───────────────────────────────────────────────────────────────
export const loanTypeKeys = {
all: () => ['loanTypes'] as const,
list: (params: LoanTypeListParams) => ['loanTypes', 'list', params] as const,
detail: (id: number) => ['loanTypes', 'detail', id] as const,
}
// ─── useGetLoanTypes ──────────────────────────────────────────────────────────
export function useGetLoanTypes(params: LoanTypeListParams = {}) {
return useQuery({
queryKey: loanTypeKeys.list(params),
queryFn: () => fetchLoanTypes(params),
placeholderData: (prev) => prev,
})
}
// ─── useGetLoanTypeById ───────────────────────────────────────────────────────
export function useGetLoanTypeById(id: number | undefined) {
return useQuery({
queryKey: loanTypeKeys.detail(id!),
queryFn: () => fetchLoanTypeById(id!),
enabled: !!id,
})
}
// ─── useCreateLoanType ────────────────────────────────────────────────────────
export function useCreateLoanType() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: CreateLoanTypePayload) => createLoanType(payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: loanTypeKeys.all() })
toast.success(t('loanTypes.toast.created', 'Karz görnüşi üstünlikli döredildi'))
},
onError: (error: Error) => {
toast.error(error.message || t('loanTypes.toast.createError', 'Döretmek başartmady'))
},
})
}
// ─── useUpdateLoanType ────────────────────────────────────────────────────────
export function useUpdateLoanType(id: number) {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: UpdateLoanTypePayload) => updateLoanType(id, payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: loanTypeKeys.all() })
toast.success(t('loanTypes.toast.updated', 'Karz görnüşi üstünlikli täzelendi'))
},
onError: (error: Error) => {
toast.error(error.message || t('loanTypes.toast.updateError', 'Täzelemek başartmady'))
},
})
}
// ─── useDeleteLoanType ────────────────────────────────────────────────────────
export function useDeleteLoanType() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (id: number) => deleteLoanType(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: loanTypeKeys.all() })
toast.success(t('loanTypes.toast.deleted', 'Karz görnüşi üstünlikli pozuldy'))
},
onError: (error: Error) => {
toast.error(error.message || t('loanTypes.toast.deleteError', 'Pozmak başartmady'))
},
})
}

View File

@@ -0,0 +1,163 @@
// ─── Types ────────────────────────────────────────────────────────────────────
export interface LoanDocumentTranslation {
tk: string
ru: string
en: string
}
export interface LoanDocument {
id: number
name: LoanDocumentTranslation
description: LoanDocumentTranslation
createdAt: string
updatedAt: string
}
export interface LoanDocumentPayload {
name: LoanDocumentTranslation
description: LoanDocumentTranslation
}
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 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 }
}
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 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 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)
}

View File

@@ -0,0 +1,311 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useEditor, EditorContent } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import Link from '@tiptap/extension-link'
import {
Bold,
Italic,
Strikethrough,
Link2,
Heading2,
Quote,
Code,
List,
ListOrdered,
Minus,
WrapText,
Paperclip,
Type,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { FormInput } from '@/components/formInput'
import { Button } from '@/components/ui/button'
import { useCreateRequiredDocument, useUpdateRequiredDocument } from '../hooks/useRequiredDocuments'
import type { LoanDocument, LoanDocumentPayload, LoanDocumentTranslation } from '../api/requiredDocumentsApi'
// ─── Types ────────────────────────────────────────────────────────────────────
type Locale = 'tk' | 'ru' | 'en'
interface RequiredDocumentFormProps {
mode: 'create' | 'edit'
initialData?: LoanDocument
requiredDocumentId?: number
}
// ─── Lang tabs ────────────────────────────────────────────────────────────────
const LOCALES: { code: Locale; label: string }[] = [
{ code: 'tk', label: 'Türkmen' },
{ code: 'ru', label: 'Русский' },
{ code: 'en', label: 'English' },
]
// ─── Tiptap Toolbar ───────────────────────────────────────────────────────────
interface RichTextToolbarProps {
editor: ReturnType<typeof useEditor>
}
function RichTextToolbar({ editor }: RichTextToolbarProps) {
if (!editor) return null
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: () => {
const url = prompt('URL giriziň:')
if (url) editor.chain().focus().setLink({ href: url }).run()
}, 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().toggleCode().run(), active: editor.isActive('code'), title: 'Code' },
{ 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: () => {}, active: false, title: 'Attachment' },
{ icon: Type, action: () => editor.chain().focus().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">
{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>
))}
</div>
)
}
// ─── RichTextEditor ───────────────────────────────────────────────────────────
interface RichTextEditorProps {
value: string
onChange: (html: string) => void
error?: string
}
function RichTextEditor({ value, onChange, error }: RichTextEditorProps) {
const editor = useEditor({
extensions: [StarterKit, Link.configure({ openOnClick: false })],
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} />
<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"
/>
{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>
)
}
// ─── LangTabs ────────────────────────────────────────────────────────────────
interface LangTabsProps {
active: Locale
onChange: (locale: Locale) => void
}
function LangTabs({ active, onChange }: LangTabsProps) {
return (
<div className="flex items-center justify-end gap-3 mb-2">
{LOCALES.map(({ code, label }) => (
<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'
)}
>
{label}
</button>
))}
</div>
)
}
// ─── Empty translation ────────────────────────────────────────────────────────
const emptyTranslation = (): LoanDocumentTranslation => ({ tk: '', ru: '', en: '' })
// ─── RequiredDocumentForm ─────────────────────────────────────────────────────────
export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }: RequiredDocumentFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
// Per-field locale tabs
const [nameLang, setNameLang] = useState<Locale>('tk')
const [descLang, setDescLang] = useState<Locale>('tk')
// Form state
const [name, setName] = useState<LoanDocumentTranslation>(
initialData?.name ?? emptyTranslation()
)
const [description, setDescription] = useState<LoanDocumentTranslation>(
initialData?.description ?? emptyTranslation()
)
// Errors
const [errors, setErrors] = useState<Partial<Record<`name_${Locale}` | `desc_${Locale}`, string>>>({})
// Sync initial data on edit mode load
useEffect(() => {
if (initialData) {
setName(initialData.name)
setDescription(initialData.description)
}
}, [initialData])
const createMutation = useCreateRequiredDocument()
const updateMutation = useUpdateRequiredDocument(requiredDocumentId ?? 0)
const isPending = createMutation.isPending || updateMutation.isPending
// ── Validation ──────────────────────────────────────────────────────────────
const validate = (): boolean => {
const errs: typeof errors = {}
LOCALES.forEach(({ code }) => {
if (!name[code].trim()) {
errs[`name_${code}`] = t('validation.required', 'Bu meýdan hökmany')
}
if (!description[code].replace(/<[^>]*>/g, '').trim()) {
errs[`desc_${code}`] = t('validation.required', 'Bu meýdan hökmany')
}
})
setErrors(errs)
return Object.keys(errs).length === 0
}
// ── Submit ──────────────────────────────────────────────────────────────────
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!validate()) return
const payload: LoanDocumentPayload = { name, description }
if (mode === 'create') {
await createMutation.mutateAsync(payload)
navigate('/settings/loan/loan-documents')
} else {
await updateMutation.mutateAsync(payload)
navigate('/settings/loan/loan-documents')
}
}
const submitLabel =
mode === 'create'
? t('loanDocuments.form.create', 'Karz gerekli resminamalary döretiň')
: t('loanDocuments.form.update', 'Karz gerekli resminamalary täzele')
return (
<form onSubmit={handleSubmit} noValidate>
<div className="bg-card border border-border rounded-xl overflow-hidden divide-y divide-border">
{/* ── Name field ──────────────────────────────────────────────────── */}
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-4">
<label className="text-sm text-muted-foreground pt-1">
{t('loanDocuments.fields.name', 'Ady')}
<span className="text-destructive ml-0.5">*</span>
</label>
<div>
<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}`]}
/>
{/* Show errors for other locales as hints */}
{LOCALES.filter((l) => l.code !== nameLang && errors[`name_${l.code}`]).map(({ code, label }) => (
<p key={code} className="mt-1 text-xs text-destructive/70">
{label}: {errors[`name_${code}`]}
</p>
))}
</div>
</div>
{/* ── Description field ────────────────────────────────────────────── */}
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-4">
<label className="text-sm text-muted-foreground pt-1">
{t('loanDocuments.fields.description', 'Yazgy')}
<span className="text-destructive ml-0.5">*</span>
</label>
<div>
<LangTabs active={descLang} onChange={setDescLang} />
<RichTextEditor
value={description[descLang]}
onChange={(val) => setDescription((prev) => ({ ...prev, [descLang]: val }))}
error={errors[`desc_${descLang}`]}
/>
{LOCALES.filter((l) => l.code !== descLang && errors[`desc_${l.code}`]).map(({ code, label }) => (
<p key={code} className="mt-1 text-xs text-destructive/70">
{label}: {errors[`desc_${code}`]}
</p>
))}
</div>
</div>
</div>
{/* ── Actions ──────────────────────────────────────────────────────────── */}
<div className="flex items-center justify-end gap-3 mt-4">
<Button
type="button"
variant="ghost"
onClick={() => navigate('/settings/loan/loan-documents')}
disabled={isPending}
>
{t('common.cancel', 'Ýatyr')}
</Button>
<Button type="submit" disabled={isPending} className="bg-primary text-primary-foreground hover:bg-primary/90">
{isPending ? t('common.saving', 'Saklanylýar...') : submitLabel}
</Button>
</div>
</form>
)
}

View File

@@ -0,0 +1,96 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import {
fetchLoanDocuments,
fetchLoanDocumentById,
createLoanDocument,
updateLoanDocument,
deleteLoanDocument,
type ListParams,
type LoanDocumentPayload,
} 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,
detail: (id: number) => [...requiredDocumentsKeys.details(), id] as const,
}
// ─── useGetLoanDocuments ──────────────────────────────────────────────────────
export function useGetRequiredDocuments(params: ListParams) {
return useQuery({
queryKey: requiredDocumentsKeys.list(params),
queryFn: () => fetchLoanDocuments(params),
})
}
// ─── useGetLoanDocumentById ───────────────────────────────────────────────────
export function useGetRequiredDocumentById(id: number) {
return useQuery({
queryKey: requiredDocumentsKeys.detail(id),
queryFn: () => fetchLoanDocumentById(id),
enabled: !!id,
})
}
// ─── useCreateLoanDocument ────────────────────────────────────────────────────
export function useCreateRequiredDocument() {
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!'))
},
onError: () => {
toast.error(t('loanDocuments.toast.createError', 'Resminama döredilende ýalňyşlyk ýüze çykdy!'))
},
})
}
// ─── useUpdateLoanDocument ────────────────────────────────────────────────────
export function useUpdateRequiredDocument(id: number) {
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!'))
},
onError: () => {
toast.error(t('loanDocuments.toast.updateError', 'Resminama täzelenende ýalňyşlyk ýüze çykdy!'))
},
})
}
// ─── useDeleteLoanDocument ────────────────────────────────────────────────────
export function useDeleteRequiredDocument() {
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!'))
},
onError: () => {
toast.error(t('loanDocuments.toast.deleteError', 'Resminama öçürilende ýalňyşlyk ýüze çykdy!'))
},
})
}