added setting card pages
This commit is contained in:
108
src/features/cardReasons/api/cardReasonsApi.ts
Normal file
108
src/features/cardReasons/api/cardReasonsApi.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CardReason {
|
||||
id: number
|
||||
name: Record<'tk' | 'ru' | 'en', string>
|
||||
value: number
|
||||
description: string | null
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
export interface CardReasonListResponse {
|
||||
data: CardReason[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
}
|
||||
|
||||
export interface CreateCardReasonPayload {
|
||||
name: Record<'tk' | 'ru' | 'en', string>
|
||||
value: number
|
||||
description: string | null
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
export interface UpdateCardReasonPayload extends CreateCardReasonPayload {
|
||||
id: number
|
||||
}
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_CARD_STATES: CardReason[] = [
|
||||
{ id: 1, name: { tk: 'Täze', ru: 'Новый', en: 'New' }, value: 32, description: null, isActive: true },
|
||||
{ id: 2, name: { tk: 'Döwülen/Zaýalanan', ru: 'Сломанный/Поврежденный', en: 'Broken/Damaged' }, value: 32, description: null, isActive: true },
|
||||
{ id: 3, name: { tk: 'Ulanylyş möhleti geçen', ru: 'Срок истёк', en: 'Expired' }, value: 32, description: null, isActive: true },
|
||||
{ id: 4, name: { tk: 'Maşgalasy üýtgeýär', ru: 'Смена фамилии', en: 'Name change' }, value: 32, description: null, isActive: true },
|
||||
{ id: 5, name: { tk: 'Ýiten', ru: 'Потерян', en: 'Lost' }, value: 37.75, description: null, isActive: true },
|
||||
{ id: 6, name: { tk: 'Pin bukja (bloklanan)', ru: 'Пин конверт (заблокирован)', en: 'Pin envelope (blocked)' }, value: 3.02, description: null, isActive: false },
|
||||
{ id: 7, name: { tk: 'Rekwizit', ru: 'Реквизит', en: 'Requisite' }, value: 2.30, description: null, isActive: false },
|
||||
]
|
||||
|
||||
let mockStore = [...MOCK_CARD_STATES]
|
||||
let nextId = 8
|
||||
|
||||
// Simulated async delay
|
||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchCardReasons(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
}): Promise<CardReasonListResponse> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 25, search = '', isActive } = params
|
||||
|
||||
let filtered = mockStore.filter((item) => {
|
||||
const matchSearch =
|
||||
!search ||
|
||||
Object.values(item.name).some((n) =>
|
||||
n.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
const matchActive =
|
||||
isActive === '' || isActive === undefined
|
||||
? true
|
||||
: isActive === 'true'
|
||||
? item.isActive
|
||||
: !item.isActive
|
||||
return matchSearch && matchActive
|
||||
})
|
||||
|
||||
filtered = [...filtered].sort((a, b) => b.id - a.id)
|
||||
|
||||
const total = filtered.length
|
||||
const start = (page - 1) * perPage
|
||||
const data = filtered.slice(start, start + perPage)
|
||||
|
||||
return { data, total, page, perPage }
|
||||
}
|
||||
|
||||
export async function fetchCardReasonById(id: number): Promise<CardReason> {
|
||||
await delay()
|
||||
const item = mockStore.find((c) => c.id === id)
|
||||
if (!item) throw new Error('Not found')
|
||||
return { ...item }
|
||||
}
|
||||
|
||||
export async function createCardReason(payload: CreateCardReasonPayload): Promise<CardReason> {
|
||||
await delay(400)
|
||||
const newItem: CardReason = { id: nextId++, ...payload }
|
||||
mockStore = [newItem, ...mockStore]
|
||||
return newItem
|
||||
}
|
||||
|
||||
export async function updateCardReason(payload: UpdateCardReasonPayload): Promise<CardReason> {
|
||||
await delay(400)
|
||||
const idx = mockStore.findIndex((c) => c.id === payload.id)
|
||||
if (idx === -1) throw new Error('Not found')
|
||||
const updated = { ...mockStore[idx], ...payload }
|
||||
mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c))
|
||||
return updated
|
||||
}
|
||||
|
||||
export async function deleteCardReason(id: number): Promise<void> {
|
||||
await delay(300)
|
||||
mockStore = mockStore.filter((c) => c.id !== id)
|
||||
}
|
||||
231
src/features/cardReasons/components/reasonForm.tsx
Normal file
231
src/features/cardReasons/components/reasonForm.tsx
Normal file
@@ -0,0 +1,231 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import type { CardReason, CreateCardReasonPayload } from '../api/cardReasonsApi'
|
||||
import { useCreateCardReason, useUpdateCardReason } from '../hooks/useCardReasons'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface FormErrors {
|
||||
nameTk?: string
|
||||
nameRu?: string
|
||||
nameEn?: string
|
||||
value?: string
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
nameTk: string
|
||||
nameRu: string
|
||||
nameEn: string
|
||||
value: string
|
||||
description: string
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
interface CardReasonFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardReason
|
||||
CardReasonId?: number
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function buildInitialState(data?: CardReason): FormState {
|
||||
if (!data) {
|
||||
return { nameTk: '', nameRu: '', nameEn: '', value: '', description: '', isActive: true }
|
||||
}
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
value: String(data.value),
|
||||
description: data.description ?? '',
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
|
||||
function validate(form: FormState, t: (k: string, fb: string) => string): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
if (!form.nameTk.trim())
|
||||
errors.nameTk = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.nameRu.trim())
|
||||
errors.nameRu = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.nameEn.trim())
|
||||
errors.nameEn = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.value.trim() || isNaN(Number(form.value)) || Number(form.value) < 0)
|
||||
errors.value = t('validation.invalidNumber', 'Dogry san giriziň')
|
||||
return errors
|
||||
}
|
||||
|
||||
// ─── Lang Tab ─────────────────────────────────────────────────────────────────
|
||||
|
||||
type LangKey = 'tk' | 'ru' | 'en'
|
||||
|
||||
const LANG_TABS: { key: LangKey; label: string }[] = [
|
||||
{ key: 'tk', label: 'Türkmen' },
|
||||
{ key: 'ru', label: 'Русский' },
|
||||
{ key: 'en', label: 'English' },
|
||||
]
|
||||
|
||||
// ─── CardReasonForm ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createMutation = useCreateCardReason()
|
||||
const updateMutation = useUpdateCardReason()
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||
const [form, setForm] = useState<FormState>(() => buildInitialState(initialData))
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
// Sync form when initialData arrives (edit mode data fetch)
|
||||
useEffect(() => {
|
||||
if (initialData) setForm(buildInitialState(initialData))
|
||||
}, [initialData])
|
||||
|
||||
const set = (key: keyof FormState) => (value: string | boolean) =>
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
|
||||
const handleSubmit = () => {
|
||||
const errs = validate(form, t)
|
||||
if (Object.keys(errs).length > 0) {
|
||||
setErrors(errs)
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
|
||||
const payload: CreateCardReasonPayload = {
|
||||
name: { tk: form.nameTk, ru: form.nameRu, en: form.nameEn },
|
||||
value: Number(form.value),
|
||||
description: form.description.trim() || null,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => navigate('/resources/card-states'),
|
||||
})
|
||||
} else if (CardReasonId !== undefined) {
|
||||
updateMutation.mutate(
|
||||
{ id: CardReasonId, ...payload },
|
||||
{ onSuccess: () => navigate('/resources/card-states') }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const nameFieldKey = `name${activeLang.charAt(0).toUpperCase() + activeLang.slice(1)}` as
|
||||
| 'nameTk'
|
||||
| 'nameRu'
|
||||
| 'nameEn'
|
||||
const nameErrorKey = nameFieldKey as keyof FormErrors
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Language tabs */}
|
||||
<div className="flex gap-3 justify-end mb-4">
|
||||
{LANG_TABS.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
type="button"
|
||||
onClick={() => setActiveLang(tab.key)}
|
||||
className={`text-sm transition-colors ${
|
||||
activeLang === tab.key
|
||||
? 'text-primary font-semibold underline underline-offset-4'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Form rows */}
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
{/* Name row */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('CardReasons.fields.name', 'Ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form[nameFieldKey]}
|
||||
onChange={set(nameFieldKey)}
|
||||
placeholder={t('CardReasons.fields.name', 'Ady')}
|
||||
error={errors[nameErrorKey]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Value row */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('CardReasons.fields.value', 'Baha')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="number"
|
||||
value={form.value}
|
||||
onChange={set('value')}
|
||||
placeholder={t('CardReasons.fields.value', 'Baha')}
|
||||
error={errors.value}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description row */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('CardReasons.fields.description', 'Bellikler')}
|
||||
</span>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.description}
|
||||
onChange={set('description')}
|
||||
placeholder={t('CardReasons.fields.description', 'Bellikler')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* isActive row */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('CardReasons.fields.isActive', 'Işjeň')}
|
||||
</span>
|
||||
<Checkbox
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(checked) => set('isActive')(!!checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center justify-end gap-3 mt-6">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => navigate('/resources/card-states')}
|
||||
disabled={isPending}
|
||||
>
|
||||
{t('common.cancel', 'Ýatyr')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSubmit}
|
||||
disabled={isPending}
|
||||
className="bg-primary text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
{isPending
|
||||
? t('common.saving', 'Saklanýar...')
|
||||
: mode === 'create'
|
||||
? t('CardReasons.actions.create', 'Kartyň çykarylmagynyň sebäbini döretdiň')
|
||||
: t('CardReasons.actions.update', 'Täzelemek')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
101
src/features/cardReasons/hooks/useCardReasons.ts
Normal file
101
src/features/cardReasons/hooks/useCardReasons.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
fetchCardReasons,
|
||||
fetchCardReasonById,
|
||||
createCardReason,
|
||||
updateCardReason,
|
||||
deleteCardReason,
|
||||
type CreateCardReasonPayload,
|
||||
type UpdateCardReasonPayload,
|
||||
} from '../api/cardReasonsApi'
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const cardReasonKeys = {
|
||||
all: ['cardReasons'] as const,
|
||||
lists: () => [...cardReasonKeys.all, 'list'] as const,
|
||||
list: (params: Record<string, unknown>) =>
|
||||
[...cardReasonKeys.lists(), params] as const,
|
||||
detail: (id: number) => [...cardReasonKeys.all, 'detail', id] as const,
|
||||
}
|
||||
|
||||
// ─── useCardReasons ────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardReasons(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
}) {
|
||||
return useQuery({
|
||||
queryKey: cardReasonKeys.list(params),
|
||||
queryFn: () => fetchCardReasons(params),
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useCardReasonById ─────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardReasonById(id: number) {
|
||||
return useQuery({
|
||||
queryKey: cardReasonKeys.detail(id),
|
||||
queryFn: () => fetchCardReasonById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useCreateCardReason ───────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCardReason() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateCardReasonPayload) => createCardReason(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() })
|
||||
toast.success(t('CardReasons.toast.createSuccess', 'Kart ýagdaýy döredildi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('CardReasons.toast.createError', 'Döretmek başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useUpdateCardReason ───────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCardReason() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateCardReasonPayload) => updateCardReason(payload),
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.detail(data.id) })
|
||||
toast.success(t('CardReasons.toast.updateSuccess', 'Kart ýagdaýy täzelendi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('CardReasons.toast.updateError', 'Täzelemek başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useDeleteCardReason ───────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCardReason() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteCardReason(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() })
|
||||
toast.success(t('CardReasons.toast.deleteSuccess', 'Kart ýagdaýy öçürildi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('CardReasons.toast.deleteError', 'Öçürmek başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
107
src/features/cardTypes/api/cardTypesApi.ts
Normal file
107
src/features/cardTypes/api/cardTypesApi.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CardType {
|
||||
id: number
|
||||
name: Record<'tk' | 'ru' | 'en', string>
|
||||
value: number
|
||||
description: string | null
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
export interface CardTypeListResponse {
|
||||
data: CardType[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
}
|
||||
|
||||
export interface CreateCardTypePayload {
|
||||
name: Record<'tk' | 'ru' | 'en', string>
|
||||
value: number
|
||||
description: string | null
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
export interface UpdateCardTypePayload extends CreateCardTypePayload {
|
||||
id: number
|
||||
}
|
||||
|
||||
// ─── Mock Store ───────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_CARD_TYPES: CardType[] = [
|
||||
{ id: 1, name: { tk: 'Altyn Asyr', ru: 'Алтын Асыр', en: 'Altyn Asyr' }, value: 32, description: null, isActive: true },
|
||||
{ id: 2, name: { tk: 'Maşgala', ru: 'Семья', en: 'Family' }, value: 32, description: null, isActive: true },
|
||||
{ id: 3, name: { tk: 'Goýum', ru: 'Депозит', en: 'Deposit' }, value: 32, description: null, isActive: true },
|
||||
{ id: 4, name: { tk: 'Pensiýa', ru: 'Пенсия', en: 'Pension' }, value: 32, description: null, isActive: true },
|
||||
{ id: 5, name: { tk: 'Telekeçi', ru: 'Предприниматель', en: 'Entrepreneur' }, value: 32, description: null, isActive: true },
|
||||
{ id: 6, name: { tk: 'Karz', ru: 'Кредит', en: 'Credit' }, value: 32, description: null, isActive: false },
|
||||
{ id: 7, name: { tk: 'Owerdraft', ru: 'Овердрафт', en: 'Overdraft' }, value: 32, description: null, isActive: true },
|
||||
]
|
||||
|
||||
let mockStore = [...MOCK_CARD_TYPES]
|
||||
let nextId = 8
|
||||
|
||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchCardTypes(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
}): Promise<CardTypeListResponse> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 25, search = '', isActive } = params
|
||||
|
||||
let filtered = mockStore.filter((item) => {
|
||||
const matchSearch =
|
||||
!search ||
|
||||
Object.values(item.name).some((n) =>
|
||||
n.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
const matchActive =
|
||||
isActive === '' || isActive === undefined
|
||||
? true
|
||||
: isActive === 'true'
|
||||
? item.isActive
|
||||
: !item.isActive
|
||||
return matchSearch && matchActive
|
||||
})
|
||||
|
||||
filtered = [...filtered].sort((a, b) => b.id - a.id)
|
||||
|
||||
const total = filtered.length
|
||||
const start = (page - 1) * perPage
|
||||
const data = filtered.slice(start, start + perPage)
|
||||
|
||||
return { data, total, page, perPage }
|
||||
}
|
||||
|
||||
export async function fetchCardTypeById(id: number): Promise<CardType> {
|
||||
await delay()
|
||||
const item = mockStore.find((c) => c.id === id)
|
||||
if (!item) throw new Error('Not found')
|
||||
return { ...item }
|
||||
}
|
||||
|
||||
export async function createCardType(payload: CreateCardTypePayload): Promise<CardType> {
|
||||
await delay(400)
|
||||
const newItem: CardType = { id: nextId++, ...payload }
|
||||
mockStore = [newItem, ...mockStore]
|
||||
return newItem
|
||||
}
|
||||
|
||||
export async function updateCardType(payload: UpdateCardTypePayload): Promise<CardType> {
|
||||
await delay(400)
|
||||
const idx = mockStore.findIndex((c) => c.id === payload.id)
|
||||
if (idx === -1) throw new Error('Not found')
|
||||
const updated = { ...mockStore[idx], ...payload }
|
||||
mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c))
|
||||
return updated
|
||||
}
|
||||
|
||||
export async function deleteCardType(id: number): Promise<void> {
|
||||
await delay(300)
|
||||
mockStore = mockStore.filter((c) => c.id !== id)
|
||||
}
|
||||
224
src/features/cardTypes/components/cardTypesForm.tsx
Normal file
224
src/features/cardTypes/components/cardTypesForm.tsx
Normal file
@@ -0,0 +1,224 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import type { CardType, CreateCardTypePayload } from '../api/cardTypesApi'
|
||||
import { useCreateCardType, useUpdateCardType } from '../hooks/useCardTypes'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface FormErrors {
|
||||
nameTk?: string
|
||||
nameRu?: string
|
||||
nameEn?: string
|
||||
value?: string
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
nameTk: string
|
||||
nameRu: string
|
||||
nameEn: string
|
||||
value: string
|
||||
description: string
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
export interface CardTypeFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardType
|
||||
cardTypeId?: number
|
||||
}
|
||||
|
||||
type LangKey = 'tk' | 'ru' | 'en'
|
||||
|
||||
const LANG_TABS: { key: LangKey; label: string }[] = [
|
||||
{ key: 'tk', label: 'Türkmen' },
|
||||
{ key: 'ru', label: 'Русский' },
|
||||
{ key: 'en', label: 'English' },
|
||||
]
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function buildInitialState(data?: CardType): FormState {
|
||||
if (!data) {
|
||||
return { nameTk: '', nameRu: '', nameEn: '', value: '', description: '', isActive: true }
|
||||
}
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
value: String(data.value),
|
||||
description: data.description ?? '',
|
||||
isActive: data.isActive,
|
||||
}
|
||||
}
|
||||
|
||||
function validate(form: FormState, t: (k: string, fb: string) => string): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
if (!form.nameTk.trim()) errors.nameTk = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.nameRu.trim()) errors.nameRu = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.nameEn.trim()) errors.nameEn = t('validation.required', 'Hökmany meýdan')
|
||||
if (!form.value.trim() || isNaN(Number(form.value)) || Number(form.value) < 0)
|
||||
errors.value = t('validation.invalidNumber', 'Dogry san giriziň')
|
||||
return errors
|
||||
}
|
||||
|
||||
// ─── CardTypeForm ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createMutation = useCreateCardType()
|
||||
const updateMutation = useUpdateCardType()
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||
const [form, setForm] = useState<FormState>(() => buildInitialState(initialData))
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
useEffect(() => {
|
||||
if (initialData) setForm(buildInitialState(initialData))
|
||||
}, [initialData])
|
||||
|
||||
const set = (key: keyof FormState) => (value: string | boolean) =>
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
|
||||
const handleSubmit = () => {
|
||||
const errs = validate(form, t)
|
||||
if (Object.keys(errs).length > 0) {
|
||||
setErrors(errs)
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
|
||||
const payload: CreateCardTypePayload = {
|
||||
name: { tk: form.nameTk, ru: form.nameRu, en: form.nameEn },
|
||||
value: Number(form.value),
|
||||
description: form.description.trim() || null,
|
||||
isActive: form.isActive,
|
||||
}
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => navigate('/settings/card/card-types'),
|
||||
})
|
||||
} else if (cardTypeId !== undefined) {
|
||||
updateMutation.mutate(
|
||||
{ id: cardTypeId, ...payload },
|
||||
{ onSuccess: () => navigate('/settings/card/card-types') }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const nameFieldKey = `name${activeLang.charAt(0).toUpperCase() + activeLang.slice(1)}` as
|
||||
| 'nameTk'
|
||||
| 'nameRu'
|
||||
| 'nameEn'
|
||||
const nameErrorKey = nameFieldKey as keyof FormErrors
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Language tabs */}
|
||||
<div className="flex gap-3 justify-end mb-4">
|
||||
{LANG_TABS.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
type="button"
|
||||
onClick={() => setActiveLang(tab.key)}
|
||||
className={`text-sm transition-colors ${
|
||||
activeLang === tab.key
|
||||
? 'text-primary font-semibold underline underline-offset-4'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Form rows */}
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
{/* Name */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('cardTypes.fields.name', 'Ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form[nameFieldKey]}
|
||||
onChange={set(nameFieldKey)}
|
||||
placeholder={t('cardTypes.fields.name', 'Ady')}
|
||||
error={errors[nameErrorKey]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Value */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('cardTypes.fields.value', 'Baha')}
|
||||
</span>
|
||||
<FormInput
|
||||
type="number"
|
||||
value={form.value}
|
||||
onChange={set('value')}
|
||||
placeholder={t('cardTypes.fields.value', 'Baha')}
|
||||
error={errors.value}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('cardTypes.fields.description', 'Bellikler')}
|
||||
</span>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.description}
|
||||
onChange={set('description')}
|
||||
placeholder={t('cardTypes.fields.description', 'Bellikler')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* isActive */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('cardTypes.fields.isActive', 'Işjeň')}
|
||||
</span>
|
||||
<Checkbox
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(checked) => set('isActive')(!!checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center justify-end gap-3 mt-6">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => navigate('/settings/card/card-types')}
|
||||
disabled={isPending}
|
||||
>
|
||||
{t('common.cancel', 'Ýatyr')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSubmit}
|
||||
disabled={isPending}
|
||||
className="bg-primary text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
{isPending
|
||||
? t('common.saving', 'Saklanýar...')
|
||||
: mode === 'create'
|
||||
? t('cardTypes.actions.create', 'Kart görnüşi döretdiň')
|
||||
: t('cardTypes.actions.update', 'Täzelemek')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
101
src/features/cardTypes/hooks/useCardTypes.ts
Normal file
101
src/features/cardTypes/hooks/useCardTypes.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
fetchCardTypes,
|
||||
fetchCardTypeById,
|
||||
createCardType,
|
||||
updateCardType,
|
||||
deleteCardType,
|
||||
type CreateCardTypePayload,
|
||||
type UpdateCardTypePayload,
|
||||
} from '../api/cardTypesApi'
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const cardTypeKeys = {
|
||||
all: ['cardTypes'] as const,
|
||||
lists: () => [...cardTypeKeys.all, 'list'] as const,
|
||||
list: (params: Record<string, unknown>) =>
|
||||
[...cardTypeKeys.lists(), params] as const,
|
||||
detail: (id: number) => [...cardTypeKeys.all, 'detail', id] as const,
|
||||
}
|
||||
|
||||
// ─── useCardTypes ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardTypes(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
}) {
|
||||
return useQuery({
|
||||
queryKey: cardTypeKeys.list(params),
|
||||
queryFn: () => fetchCardTypes(params),
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useCardTypeById ──────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardTypeById(id: number) {
|
||||
return useQuery({
|
||||
queryKey: cardTypeKeys.detail(id),
|
||||
queryFn: () => fetchCardTypeById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useCreateCardType ────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCardType() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateCardTypePayload) => createCardType(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() })
|
||||
toast.success(t('cardTypes.toast.createSuccess', 'Kart görnüşi döredildi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('cardTypes.toast.createError', 'Döretmek başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useUpdateCardType ────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCardType() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateCardTypePayload) => updateCardType(payload),
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.detail(data.id) })
|
||||
toast.success(t('cardTypes.toast.updateSuccess', 'Kart görnüşi täzelendi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('cardTypes.toast.updateError', 'Täzelemek başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useDeleteCardType ────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCardType() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteCardType(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() })
|
||||
toast.success(t('cardTypes.toast.deleteSuccess', 'Kart görnüşi öçürildi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('cardTypes.toast.deleteError', 'Öçürmek başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user