added some settings page
This commit is contained in:
169
src/features/loanTypes/api/loanTypesApi.ts
Normal file
169
src/features/loanTypes/api/loanTypesApi.ts
Normal 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)
|
||||
}
|
||||
268
src/features/loanTypes/components/loanTypesForm.tsx
Normal file
268
src/features/loanTypes/components/loanTypesForm.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
97
src/features/loanTypes/hooks/useLoanTypes.ts
Normal file
97
src/features/loanTypes/hooks/useLoanTypes.ts
Normal 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'))
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user