added some new pages
This commit is contained in:
141
src/features/currencyRates/api/currencyRatesApi.ts
Normal file
141
src/features/currencyRates/api/currencyRatesApi.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
// features/currencyRates/api/currencyRatesApi.ts
|
||||
|
||||
export type CurrencyCode = 'USD' | 'RUB' | 'TMT' | 'EUR' | 'GBP' | 'CNY' | 'TRY'
|
||||
|
||||
export interface CurrencyRate {
|
||||
id: number
|
||||
currencyFrom: CurrencyCode
|
||||
currencyTo: CurrencyCode
|
||||
value: number
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface CurrencyRateListParams {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export interface CurrencyRateListResponse {
|
||||
data: CurrencyRate[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
totalPages: number
|
||||
}
|
||||
|
||||
export interface CreateCurrencyRatePayload {
|
||||
currencyFrom: CurrencyCode
|
||||
currencyTo: CurrencyCode
|
||||
value: number
|
||||
}
|
||||
|
||||
export type UpdateCurrencyRatePayload = CreateCurrencyRatePayload
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_RATES: CurrencyRate[] = [
|
||||
{ id: 6, currencyFrom: 'USD', currencyTo: 'USD', value: 250, createdAt: '2026-04-01T10:00:00Z', updatedAt: '2026-05-01T10:00:00Z' },
|
||||
{ id: 5, currencyFrom: 'RUB', currencyTo: 'TMT', value: 0.047504, createdAt: '2026-03-15T08:30:00Z', updatedAt: '2026-05-10T08:30:00Z' },
|
||||
{ id: 4, currencyFrom: 'USD', currencyTo: 'RUB', value: 74.0455, createdAt: '2026-02-20T14:00:00Z', updatedAt: '2026-05-08T14:00:00Z' },
|
||||
{ id: 2, currencyFrom: 'USD', currencyTo: 'TMT', value: 3.5175, createdAt: '2026-01-10T09:00:00Z', updatedAt: '2026-05-05T09:00:00Z' },
|
||||
{ id: 1, currencyFrom: 'EUR', currencyTo: 'TMT', value: 3.8120, createdAt: '2026-01-05T09:00:00Z', updatedAt: '2026-05-03T09:00:00Z' },
|
||||
{ id: 3, currencyFrom: 'EUR', currencyTo: 'RUB', value: 80.2300, createdAt: '2026-01-12T11:00:00Z', updatedAt: '2026-04-28T11:00:00Z' },
|
||||
{ id: 7, currencyFrom: 'GBP', currencyTo: 'TMT', value: 4.4500, createdAt: '2026-04-10T13:00:00Z', updatedAt: '2026-05-11T13:00:00Z' },
|
||||
{ id: 8, currencyFrom: 'CNY', currencyTo: 'TMT', value: 0.4850, createdAt: '2026-04-15T10:00:00Z', updatedAt: '2026-05-09T10:00:00Z' },
|
||||
]
|
||||
|
||||
let mockStore: CurrencyRate[] = [...MOCK_RATES]
|
||||
let nextId = 9
|
||||
|
||||
const delay = (ms = 400) => new Promise<void>((res) => setTimeout(res, ms))
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchCurrencyRates(
|
||||
params: CurrencyRateListParams = {}
|
||||
): Promise<CurrencyRateListResponse> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 25, search = '' } = params
|
||||
|
||||
let filtered = [...mockStore]
|
||||
|
||||
if (search.trim()) {
|
||||
const q = search.toLowerCase()
|
||||
filtered = filtered.filter(
|
||||
(r) =>
|
||||
r.currencyFrom.toLowerCase().includes(q) ||
|
||||
r.currencyTo.toLowerCase().includes(q) ||
|
||||
String(r.value).includes(q) ||
|
||||
String(r.id).includes(q)
|
||||
)
|
||||
}
|
||||
|
||||
// Sort by id desc
|
||||
filtered.sort((a, b) => b.id - a.id)
|
||||
|
||||
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 fetchCurrencyRateById(id: number): Promise<CurrencyRate> {
|
||||
await delay()
|
||||
const rate = mockStore.find((r) => r.id === id)
|
||||
if (!rate) throw new Error(`Currency rate with id ${id} not found`)
|
||||
return { ...rate }
|
||||
}
|
||||
|
||||
export async function createCurrencyRate(
|
||||
payload: CreateCurrencyRatePayload
|
||||
): Promise<CurrencyRate> {
|
||||
await delay()
|
||||
const now = new Date().toISOString()
|
||||
const newRate: CurrencyRate = {
|
||||
id: nextId++,
|
||||
...payload,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
mockStore = [newRate, ...mockStore]
|
||||
return newRate
|
||||
}
|
||||
|
||||
export async function updateCurrencyRate(
|
||||
id: number,
|
||||
payload: UpdateCurrencyRatePayload
|
||||
): Promise<CurrencyRate> {
|
||||
await delay()
|
||||
const idx = mockStore.findIndex((r) => r.id === id)
|
||||
if (idx === -1) throw new Error(`Currency rate with id ${id} not found`)
|
||||
const updated: CurrencyRate = {
|
||||
...mockStore[idx],
|
||||
...payload,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
mockStore = mockStore.map((r) => (r.id === id ? updated : r))
|
||||
return updated
|
||||
}
|
||||
|
||||
export async function deleteCurrencyRate(id: number): Promise<void> {
|
||||
await delay()
|
||||
const exists = mockStore.some((r) => r.id === id)
|
||||
if (!exists) throw new Error(`Currency rate with id ${id} not found`)
|
||||
mockStore = mockStore.filter((r) => r.id !== id)
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
export const CURRENCY_OPTIONS: { value: CurrencyCode; label: string }[] = [
|
||||
{ value: 'USD', label: 'USD — US Dollar' },
|
||||
{ value: 'RUB', label: 'RUB — Russian Ruble' },
|
||||
{ value: 'TMT', label: 'TMT — Turkmen Manat' },
|
||||
{ value: 'EUR', label: 'EUR — Euro' },
|
||||
{ value: 'GBP', label: 'GBP — British Pound' },
|
||||
{ value: 'CNY', label: 'CNY — Chinese Yuan' },
|
||||
{ value: 'TRY', label: 'TRY — Turkish Lira' },
|
||||
]
|
||||
203
src/features/currencyRates/components/currencyRatesForm.tsx
Normal file
203
src/features/currencyRates/components/currencyRatesForm.tsx
Normal file
@@ -0,0 +1,203 @@
|
||||
// features/currencyRates/components/CurrencyRateForm.tsx
|
||||
|
||||
import { useEffect, useState } 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 { CURRENCY_OPTIONS, type CurrencyCode, type CurrencyRate } from '../api/currencyRatesApi'
|
||||
import { useCreateCurrencyRate, useUpdateCurrencyRate } from '../hooks/useCurrencyRates'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface FormState {
|
||||
currencyFrom: string
|
||||
currencyTo: string
|
||||
value: string
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
currencyFrom?: string
|
||||
currencyTo?: string
|
||||
value?: string
|
||||
}
|
||||
|
||||
export interface CurrencyRateFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CurrencyRate
|
||||
rateId?: number
|
||||
}
|
||||
|
||||
// ─── Validation ───────────────────────────────────────────────────────────────
|
||||
|
||||
function validate(form: FormState, t: (key: string, fallback: string) => string): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
|
||||
if (!form.currencyFrom) {
|
||||
errors.currencyFrom = t('currencyRates.errors.currencyFromRequired', 'Walýuta saýlaň')
|
||||
}
|
||||
if (!form.currencyTo) {
|
||||
errors.currencyTo = t('currencyRates.errors.currencyToRequired', 'Walýuta saýlaň')
|
||||
}
|
||||
if (!form.value.trim()) {
|
||||
errors.value = t('currencyRates.errors.valueRequired', 'Bahany giriziň')
|
||||
} else if (isNaN(Number(form.value)) || Number(form.value) <= 0) {
|
||||
errors.value = t('currencyRates.errors.valueInvalid', 'Baha 0-dan uly bolmaly')
|
||||
}
|
||||
|
||||
return errors
|
||||
}
|
||||
|
||||
// ─── CurrencyRateForm ─────────────────────────────────────────────────────────
|
||||
|
||||
export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [form, setForm] = useState<FormState>({
|
||||
currencyFrom: initialData?.currencyFrom ?? '',
|
||||
currencyTo: initialData?.currencyTo ?? '',
|
||||
value: initialData?.value != null ? String(initialData.value) : '',
|
||||
})
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
const createMutation = useCreateCurrencyRate()
|
||||
const updateMutation = useUpdateCurrencyRate(rateId ?? 0)
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
// Sync form when initialData loads (edit mode)
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
setForm({
|
||||
currencyFrom: initialData.currencyFrom,
|
||||
currencyTo: initialData.currencyTo,
|
||||
value: String(initialData.value),
|
||||
})
|
||||
}
|
||||
}, [mode, initialData])
|
||||
|
||||
const setField = (field: keyof FormState) => (val: string) => {
|
||||
setForm((prev) => ({ ...prev, [field]: val }))
|
||||
// Clear error on change
|
||||
if (errors[field]) setErrors((prev) => ({ ...prev, [field]: undefined }))
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const validationErrors = validate(form, t)
|
||||
if (Object.keys(validationErrors).length > 0) {
|
||||
setErrors(validationErrors)
|
||||
return
|
||||
}
|
||||
|
||||
const payload = {
|
||||
currencyFrom: form.currencyFrom as CurrencyCode,
|
||||
currencyTo: form.currencyTo as CurrencyCode,
|
||||
value: Number(form.value),
|
||||
}
|
||||
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(payload)
|
||||
navigate('/resources/currency-rates')
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload)
|
||||
navigate(`/resources/currency-rates/${rateId}`)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
if (mode === 'create') {
|
||||
navigate('/resources/currency-rates')
|
||||
} else {
|
||||
navigate(`/resources/currency-rates/${rateId}`)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Currency From */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
||||
<label className="text-sm text-muted-foreground pt-1.5">
|
||||
{t('currencyRates.fields.currencyFrom', 'Currency from')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<div className="space-y-1">
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
value={form.currencyFrom}
|
||||
onChange={setField('currencyFrom')}
|
||||
options={CURRENCY_OPTIONS}
|
||||
placeholder={t('common.selectPlaceholder', 'Saýlamak üçin basyň')}
|
||||
error={errors.currencyFrom}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('currencyRates.hints.oneUnit', '1 möçberi')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Currency To */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
||||
<label className="text-sm text-muted-foreground pt-1.5">
|
||||
{t('currencyRates.fields.currencyTo', 'Currency to')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
value={form.currencyTo}
|
||||
onChange={setField('currencyTo')}
|
||||
options={CURRENCY_OPTIONS}
|
||||
placeholder={t('common.selectPlaceholder', 'Saýlamak üçin basyň')}
|
||||
error={errors.currencyTo}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Value */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6">
|
||||
<label className="text-sm text-muted-foreground pt-1.5">
|
||||
{t('currencyRates.fields.value', 'Value')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<div className="space-y-1">
|
||||
<FormInput
|
||||
type="number"
|
||||
value={form.value}
|
||||
onChange={setField('value')}
|
||||
placeholder={t('currencyRates.fields.value', 'Value')}
|
||||
error={errors.value}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground italic">
|
||||
{t('currencyRates.hints.decimalNote', 'Bitin däl sanlary "." bilen ýazmaly')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer Actions */}
|
||||
<div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-border">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={handleCancel}
|
||||
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('currencyRates.actions.create', 'Walýuta kursy dörediň')
|
||||
: t('currencyRates.actions.update', 'Ýatda sakla')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
100
src/features/currencyRates/hooks/useCurrencyRates.ts
Normal file
100
src/features/currencyRates/hooks/useCurrencyRates.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
// features/currencyRates/hooks/useCurrencyRates.ts
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
fetchCurrencyRates,
|
||||
fetchCurrencyRateById,
|
||||
createCurrencyRate,
|
||||
updateCurrencyRate,
|
||||
deleteCurrencyRate,
|
||||
type CurrencyRateListParams,
|
||||
type CreateCurrencyRatePayload,
|
||||
type UpdateCurrencyRatePayload,
|
||||
} from '../api/currencyRatesApi'
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const currencyRateKeys = {
|
||||
all: ['currencyRates'] as const,
|
||||
lists: () => [...currencyRateKeys.all, 'list'] as const,
|
||||
list: (params: CurrencyRateListParams) =>
|
||||
[...currencyRateKeys.lists(), params] as const,
|
||||
detail: (id: number) =>
|
||||
[...currencyRateKeys.all, 'detail', id] as const,
|
||||
}
|
||||
|
||||
// ─── useGetCurrencyRates ──────────────────────────────────────────────────────
|
||||
|
||||
export function useGetCurrencyRates(params: CurrencyRateListParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: currencyRateKeys.list(params),
|
||||
queryFn: () => fetchCurrencyRates(params),
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useGetCurrencyRateById ───────────────────────────────────────────────────
|
||||
|
||||
export function useGetCurrencyRateById(id: number) {
|
||||
return useQuery({
|
||||
queryKey: currencyRateKeys.detail(id),
|
||||
queryFn: () => fetchCurrencyRateById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useCreateCurrencyRate ────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCurrencyRate() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateCurrencyRatePayload) => createCurrencyRate(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() })
|
||||
toast.success(t('currencyRates.toast.created', 'Walýuta kursy döredildi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('currencyRates.toast.createError', 'Döretmek başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useUpdateCurrencyRate ────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCurrencyRate(id: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateCurrencyRatePayload) => updateCurrencyRate(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.detail(id) })
|
||||
toast.success(t('currencyRates.toast.updated', 'Walýuta kursy üýtgedildi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('currencyRates.toast.updateError', 'Üýtgetmek başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useDeleteCurrencyRate ────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCurrencyRate() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteCurrencyRate(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() })
|
||||
toast.success(t('currencyRates.toast.deleted', 'Walýuta kursy pozuldy'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('currencyRates.toast.deleteError', 'Pozmak başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user