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'))
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// features/onlinePaymentHistory/api/onlinePaymentHistoryApi.ts
|
||||
|
||||
export type PaymentStatus = 'GARAŞYLÝAR' | 'TÖLENEN' | 'YATYRYLAN'
|
||||
|
||||
export interface OnlinePayment {
|
||||
id: number
|
||||
orderId: string
|
||||
amount: number
|
||||
orderNumber: string
|
||||
apiClient: string
|
||||
description: string
|
||||
formUrl: string
|
||||
successUrl: string
|
||||
status: PaymentStatus
|
||||
callbackStatus: string | null
|
||||
username: string
|
||||
onlinePaymantableId: number
|
||||
onlinePaymantableType: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface OnlinePaymentListParams {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export interface OnlinePaymentListResponse {
|
||||
data: OnlinePayment[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
totalPages: number
|
||||
}
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
|
||||
const buildPayment = (
|
||||
id: number,
|
||||
orderId: string,
|
||||
amount: number,
|
||||
orderNumber: string,
|
||||
apiClient: string,
|
||||
description: string,
|
||||
status: PaymentStatus,
|
||||
username: string,
|
||||
paymantableId: number,
|
||||
paymantableType: string,
|
||||
createdAt: string,
|
||||
callbackStatus: string | null = null
|
||||
): OnlinePayment => ({
|
||||
id,
|
||||
orderId,
|
||||
amount,
|
||||
orderNumber,
|
||||
apiClient,
|
||||
description,
|
||||
formUrl: `https://mpi.gov.tm/payment/merchants/online/payment_ru.html?mdOrder=${orderId}`,
|
||||
successUrl: 'https://online.tbbank.gov.tm/online-payment-store-visa-master',
|
||||
status,
|
||||
callbackStatus,
|
||||
username,
|
||||
onlinePaymantableId: paymantableId,
|
||||
onlinePaymantableType: paymantableType,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
})
|
||||
|
||||
const VM_TYPE = 'App\\Modules\\VisaMasterPaymentOrder\\Models\\VisaMasterPaymentOrder'
|
||||
const SBER_TYPE = 'App\\Modules\\SberPaymentOrder\\Models\\SberPaymentOrder'
|
||||
const KART_TYPE = 'App\\Modules\\KartPaymentOrder\\Models\\KartPaymentOrder'
|
||||
|
||||
const MOCK_PAYMENTS: OnlinePayment[] = [
|
||||
buildPayment(1667, 'ed99d307-65fd-40ed-98ec-898019000af4', 99438, '110526160855', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040830', 5280, VM_TYPE, '2026-05-11T16:08:00Z'),
|
||||
buildPayment(1666, 'ab12c456-11aa-22bb-33cc-111111000001', 99438, '110526160800', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5279, VM_TYPE, '2026-05-11T16:06:00Z', 'SUCCESS'),
|
||||
buildPayment(1665, 'bc23d567-22bb-33cc-44dd-222222000002', 99438, '110526160745', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5278, VM_TYPE, '2026-05-11T16:04:00Z', 'SUCCESS'),
|
||||
buildPayment(1664, 'cd34e678-33cc-44dd-55ee-333333000003', 99438, '110526160730', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5277, VM_TYPE, '2026-05-11T16:03:00Z', 'SUCCESS'),
|
||||
buildPayment(1663, 'de45f789-44dd-55ee-66ff-444444000004', 99438, '110526160715', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5276, VM_TYPE, '2026-05-11T16:01:00Z', 'SUCCESS'),
|
||||
buildPayment(1662, 'ef56a890-55ee-66ff-77aa-555555000005', 99438, '110526155900', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5275, VM_TYPE, '2026-05-11T15:40:00Z', 'SUCCESS'),
|
||||
buildPayment(1661, 'fa67b901-66ff-77aa-88bb-666666000006', 99438, '110526155830', 'billing_visa_master_username', 'Visa/Master tölegi', 'YATYRYLAN', '10130100040844', 5274, VM_TYPE, '2026-05-11T15:39:00Z'),
|
||||
buildPayment(1660, 'ab78c012-77aa-88bb-99cc-777777000007', 99438, '110526155800', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5273, VM_TYPE, '2026-05-11T15:38:00Z', 'SUCCESS'),
|
||||
buildPayment(1659, 'bc89d123-88bb-99cc-00dd-888888000008', 99438, '110526155730', 'billing_visa_master_username', 'Visa/Master tölegi', 'YATYRYLAN', '10130100040844', 5272, VM_TYPE, '2026-05-11T15:35:00Z'),
|
||||
buildPayment(1658, 'cd90e234-99cc-00dd-11ee-999999000009', 99438, '110526152900', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5271, VM_TYPE, '2026-05-11T15:29:00Z', 'SUCCESS'),
|
||||
buildPayment(1657, 'de01f345-00dd-11ee-22ff-000000000010', 99438, '110526103900', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040862', 5270, VM_TYPE, '2026-05-11T10:39:00Z'),
|
||||
buildPayment(1656, 'ef12a456-11ee-22ff-33aa-111111000011', 99438, '110526103800', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040862', 5269, VM_TYPE, '2026-05-11T10:39:00Z'),
|
||||
buildPayment(1655, 'fa23b567-22ff-33aa-44bb-222222000012', 99438, '110526103700', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040862', 5268, VM_TYPE, '2026-05-11T10:38:00Z'),
|
||||
buildPayment(1654, 'ab34c678-33aa-44bb-55cc-333333000013', 99438, '110526103600', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040862', 5267, VM_TYPE, '2026-05-11T10:38:00Z'),
|
||||
buildPayment(1653, 'bc45d789-44bb-55cc-66dd-444444000014', 99438, '110526085200', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040828', 5266, VM_TYPE, '2026-05-11T08:52:00Z'),
|
||||
buildPayment(1652, 'cd56e890-55cc-66dd-77ee-555555000015', 99438, '060526142300', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040826', 5265, VM_TYPE, '2026-05-06T14:23:00Z'),
|
||||
buildPayment(1651, 'de67f901-66dd-77ee-88ff-666666000016', 106345,'280426161300', 'billing_sber_username', 'Sber tölegi', 'GARAŞYLÝAR', '10130100040827', 5264, SBER_TYPE, '2026-04-28T16:13:00Z'),
|
||||
buildPayment(1650, 'ef78a012-77ee-88ff-99aa-777777000017', 32, '250426130100', 'billing_username', 'Kart tölegi', 'GARAŞYLÝAR', '10130100004083', 5263, KART_TYPE, '2026-04-25T13:01:00Z'),
|
||||
buildPayment(1649, 'fa89b123-88ff-99aa-00bb-888888000018', 32, '240426101900', 'billing_username', 'Kart tölegi', 'GARAŞYLÝAR', '10130100004083', 5262, KART_TYPE, '2026-04-24T10:19:00Z'),
|
||||
buildPayment(1648, 'ab90c234-99aa-00bb-11cc-999999000019', 106344,'210426105900', 'billing_sber_username', 'Sber tölegi', 'TÖLENEN', '10130100040827', 5261, SBER_TYPE, '2026-04-21T10:59:00Z', 'SUCCESS'),
|
||||
buildPayment(1647, 'bc01d345-00bb-11cc-22dd-000000000020', 106243,'200426153100', 'billing_sber_username', 'Sber tölegi', 'GARAŞYLÝAR', '10130100040833', 5260, SBER_TYPE, '2026-04-20T15:31:00Z'),
|
||||
buildPayment(1646, 'cd12e456-11cc-22dd-33ee-111111000021', 99438, '170426111400', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040832', 5259, VM_TYPE, '2026-04-17T11:14:00Z', 'SUCCESS'),
|
||||
buildPayment(1645, 'de23f567-22dd-33ee-44ff-222222000022', 99438, '170426103400', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040832', 5258, VM_TYPE, '2026-04-17T10:34:00Z'),
|
||||
buildPayment(1644, 'ef34a678-33ee-44ff-55aa-333333000023', 99438, '160426175600', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040830', 5257, VM_TYPE, '2026-04-16T17:56:00Z'),
|
||||
buildPayment(1643, 'fa45b789-44ff-55aa-66bb-444444000024', 99438, '150426155000', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040826', 5256, VM_TYPE, '2026-04-15T15:50:00Z', 'SUCCESS'),
|
||||
]
|
||||
|
||||
// Total mock count is 1664 per screenshot — we serve paginated slices of the 25 above
|
||||
const TOTAL_MOCK = 1664
|
||||
|
||||
const delay = (ms = 400) => new Promise<void>((res) => setTimeout(res, ms))
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchOnlinePayments(
|
||||
params: OnlinePaymentListParams = {}
|
||||
): Promise<OnlinePaymentListResponse> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 25, search = '' } = params
|
||||
|
||||
let filtered = [...MOCK_PAYMENTS]
|
||||
|
||||
if (search.trim()) {
|
||||
const q = search.toLowerCase()
|
||||
filtered = filtered.filter(
|
||||
(r) =>
|
||||
String(r.amount).includes(q) ||
|
||||
r.apiClient.toLowerCase().includes(q) ||
|
||||
r.description.toLowerCase().includes(q)||
|
||||
r.username.toLowerCase().includes(q) ||
|
||||
r.status.toLowerCase().includes(q) ||
|
||||
r.orderId.toLowerCase().includes(q)
|
||||
)
|
||||
}
|
||||
|
||||
const total = search.trim() ? filtered.length : TOTAL_MOCK
|
||||
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 fetchOnlinePaymentById(id: number): Promise<OnlinePayment> {
|
||||
await delay()
|
||||
const item = MOCK_PAYMENTS.find((r) => r.id === id)
|
||||
if (!item) throw new Error(`OnlinePayment with id ${id} not found`)
|
||||
return { ...item }
|
||||
}
|
||||
|
||||
// Callback trigger — mock only logs; in real impl would POST to backend
|
||||
export async function triggerPaymentCallback(id: number): Promise<void> {
|
||||
await delay(600)
|
||||
const item = MOCK_PAYMENTS.find((r) => r.id === id)
|
||||
if (!item) throw new Error(`OnlinePayment with id ${id} not found`)
|
||||
// no-op in mock
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {
|
||||
StatusBadge,
|
||||
type StatusBadgeVariant,
|
||||
} from '@/components/ui/statusBadge'
|
||||
import { AlertCircle, CheckCircle2, XCircle } from 'lucide-react'
|
||||
import type { PaymentStatus } from '@/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi'
|
||||
|
||||
const STATUS_CONFIG = {
|
||||
GARAŞYLÝAR: {
|
||||
label: 'Garaşylýar',
|
||||
variant: 'warning' as StatusBadgeVariant,
|
||||
icon: AlertCircle,
|
||||
},
|
||||
TÖLENEN: {
|
||||
label: 'Tölenen',
|
||||
variant: 'success' as StatusBadgeVariant,
|
||||
icon: CheckCircle2,
|
||||
},
|
||||
YATYRYLAN: {
|
||||
label: 'Ýatyrylan',
|
||||
variant: 'error' as StatusBadgeVariant,
|
||||
icon: XCircle,
|
||||
},
|
||||
} satisfies Record<
|
||||
PaymentStatus,
|
||||
{ label: string; variant: StatusBadgeVariant; icon: React.ElementType }
|
||||
>
|
||||
|
||||
export function PaymentStatusBadge({ status }: { status: PaymentStatus }) {
|
||||
const cfg = STATUS_CONFIG[status]
|
||||
if (!cfg) return <span className="text-xs text-muted-foreground">{String(status)}</span>
|
||||
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// features/onlinePaymentHistory/hooks/useOnlinePaymentHistory.ts
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
fetchOnlinePayments,
|
||||
fetchOnlinePaymentById,
|
||||
triggerPaymentCallback,
|
||||
type OnlinePaymentListParams,
|
||||
} from '../api/onlinePaymentsHistoryApi'
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const onlinePaymentKeys = {
|
||||
all: ['onlinePayments'] as const,
|
||||
lists: () => [...onlinePaymentKeys.all, 'list'] as const,
|
||||
list: (params: OnlinePaymentListParams) =>
|
||||
[...onlinePaymentKeys.lists(), params] as const,
|
||||
detail: (id: number) =>
|
||||
[...onlinePaymentKeys.all, 'detail', id] as const,
|
||||
}
|
||||
|
||||
// ─── useGetOnlinePayments ─────────────────────────────────────────────────────
|
||||
|
||||
export function useGetOnlinePayments(params: OnlinePaymentListParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: onlinePaymentKeys.list(params),
|
||||
queryFn: () => fetchOnlinePayments(params),
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useGetOnlinePaymentById ──────────────────────────────────────────────────
|
||||
|
||||
export function useGetOnlinePaymentById(id: number) {
|
||||
return useQuery({
|
||||
queryKey: onlinePaymentKeys.detail(id),
|
||||
queryFn: () => fetchOnlinePaymentById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useTriggerPaymentCallback ────────────────────────────────────────────────
|
||||
|
||||
export function useTriggerPaymentCallback() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => triggerPaymentCallback(id),
|
||||
onSuccess: (_data, id) => {
|
||||
queryClient.invalidateQueries({ queryKey: onlinePaymentKeys.detail(id) })
|
||||
queryClient.invalidateQueries({ queryKey: onlinePaymentKeys.lists() })
|
||||
toast.success(t('onlinePayments.toast.callbackTriggered', 'Callback ugradyldy'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('onlinePayments.toast.callbackError', 'Callback ugratmak başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
134
src/features/permissions/api/permissionsApi.ts
Normal file
134
src/features/permissions/api/permissionsApi.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
// import {apiClient} from '@/lib/api/client'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface PermissionTranslation {
|
||||
tk: string
|
||||
ru: string
|
||||
en: string
|
||||
}
|
||||
|
||||
export interface AuditLog {
|
||||
id: number
|
||||
action: string
|
||||
by: string
|
||||
target: string
|
||||
status: string
|
||||
date: string
|
||||
}
|
||||
|
||||
export interface Permission {
|
||||
id: number
|
||||
code: string
|
||||
name: PermissionTranslation
|
||||
guard_name: string
|
||||
audit_logs?: AuditLog[]
|
||||
}
|
||||
|
||||
export interface PermissionPayload {
|
||||
code: string
|
||||
name: PermissionTranslation
|
||||
guard_name: string
|
||||
}
|
||||
|
||||
export interface PermissionsListParams {
|
||||
search?: string
|
||||
page?: number
|
||||
per_page?: number
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[]
|
||||
meta: {
|
||||
current_page: number
|
||||
last_page: number
|
||||
per_page: number
|
||||
total: number
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_PERMISSIONS: Permission[] = [
|
||||
{ id: 1, code: 'users.view', guard_name: 'web', name: { tk: 'Ulanyjylary görmek', ru: 'Просмотр пользователей', en: 'View users' } },
|
||||
{ id: 2, code: 'users.create', guard_name: 'web', name: { tk: 'Ulanyjy döretmek', ru: 'Создание пользователя', en: 'Create user' } },
|
||||
{ id: 3, code: 'users.edit', guard_name: 'web', name: { tk: 'Ulanyjyny üýtgetmek', ru: 'Редактирование пользователя', en: 'Edit user' } },
|
||||
{ id: 4, code: 'users.delete', guard_name: 'web', name: { tk: 'Ulanyjyny pozmak', ru: 'Удаление пользователя', en: 'Delete user' } },
|
||||
{ id: 5, code: 'roles.view', guard_name: 'web', name: { tk: 'Rollary görmek', ru: 'Просмотр ролей', en: 'View roles' } },
|
||||
{ id: 6, code: 'roles.create', guard_name: 'web', name: { tk: 'Rol döretmek', ru: 'Создание роли', en: 'Create role' } },
|
||||
{ id: 7, code: 'roles.edit', guard_name: 'web', name: { tk: 'Roly üýtgetmek', ru: 'Редактирование роли', en: 'Edit role' } },
|
||||
{ id: 8, code: 'roles.delete', guard_name: 'web', name: { tk: 'Roly pozmak', ru: 'Удаление роли', en: 'Delete role' } },
|
||||
{ id: 9, code: 'permissions.view', guard_name: 'web', name: { tk: 'Rugsatlary görmek', ru: 'Просмотр разрешений', en: 'View permissions' } },
|
||||
{ id: 10, code: 'permissions.edit', guard_name: 'web', name: { tk: 'Rugsady üýtgetmek', ru: 'Редактирование разрешения', en: 'Edit permission' } },
|
||||
]
|
||||
|
||||
const delay = (ms = 500) => new Promise((res) => setTimeout(res, ms))
|
||||
|
||||
// ─── API functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export const permissionsApi = {
|
||||
getAll: async (params?: PermissionsListParams): Promise<{ data: PaginatedResponse<Permission> }> => {
|
||||
await delay()
|
||||
const { search = '', page = 1, per_page = 25 } = params ?? {}
|
||||
|
||||
let filtered = [...MOCK_PERMISSIONS]
|
||||
if (search) {
|
||||
const s = search.toLowerCase()
|
||||
filtered = filtered.filter(
|
||||
(p) =>
|
||||
p.code.toLowerCase().includes(s) ||
|
||||
p.name.tk.toLowerCase().includes(s) ||
|
||||
p.name.ru.toLowerCase().includes(s) ||
|
||||
p.name.en.toLowerCase().includes(s)
|
||||
)
|
||||
}
|
||||
|
||||
const total = filtered.length
|
||||
const last_page = Math.ceil(total / per_page)
|
||||
const start = (page - 1) * per_page
|
||||
const data = filtered.slice(start, start + per_page)
|
||||
|
||||
return {
|
||||
data: {
|
||||
data,
|
||||
meta: {
|
||||
current_page: page,
|
||||
last_page,
|
||||
per_page,
|
||||
total,
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
getById: async (id: number): Promise<{ data: Permission }> => {
|
||||
await delay()
|
||||
const item = MOCK_PERMISSIONS.find((p) => p.id === id)
|
||||
if (!item) throw new Error('Not found')
|
||||
return { data: item }
|
||||
},
|
||||
|
||||
create: async (payload: PermissionPayload): Promise<{ data: Permission }> => {
|
||||
await delay()
|
||||
const newItem: Permission = {
|
||||
...payload,
|
||||
id: Math.floor(Math.random() * 10000),
|
||||
}
|
||||
MOCK_PERMISSIONS.push(newItem)
|
||||
return { data: newItem }
|
||||
},
|
||||
|
||||
update: async (id: number, payload: PermissionPayload): Promise<{ data: Permission }> => {
|
||||
await delay()
|
||||
const index = MOCK_PERMISSIONS.findIndex((p) => p.id === id)
|
||||
if (index === -1) throw new Error('Not found')
|
||||
MOCK_PERMISSIONS[index] = { ...MOCK_PERMISSIONS[index], ...payload }
|
||||
return { data: MOCK_PERMISSIONS[index] }
|
||||
},
|
||||
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await delay()
|
||||
const index = MOCK_PERMISSIONS.findIndex((p) => p.id === id)
|
||||
if (index !== -1) MOCK_PERMISSIONS.splice(index, 1)
|
||||
},
|
||||
}
|
||||
202
src/features/permissions/components/permissionsForm.tsx
Normal file
202
src/features/permissions/components/permissionsForm.tsx
Normal file
@@ -0,0 +1,202 @@
|
||||
import { 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 { useCreatePermission, useUpdatePermission } from '../hooks/usePermissions'
|
||||
import type { Permission, PermissionPayload } from '../api/permissionsApi'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface PermissionFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: Permission
|
||||
permissionId?: number
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
code?: string
|
||||
name_tk?: string
|
||||
name_ru?: string
|
||||
name_en?: string
|
||||
guard_name?: string
|
||||
}
|
||||
|
||||
type LangKey = 'tk' | 'ru' | 'en'
|
||||
|
||||
const LANG_TABS: { key: LangKey; label: string }[] = [
|
||||
{ key: 'tk', label: 'Türkmen' },
|
||||
{ key: 'ru', label: 'Русский' },
|
||||
{ key: 'en', label: 'English' },
|
||||
]
|
||||
|
||||
const GUARD_OPTIONS = [
|
||||
{ value: 'web', label: 'web' },
|
||||
{ value: 'api', label: 'api' },
|
||||
{ value: 'sanctum', label: 'sanctum' },
|
||||
]
|
||||
|
||||
// ─── PermissionForm ───────────────────────────────────────────────────────────
|
||||
|
||||
export function PermissionForm({ mode, initialData, permissionId }: PermissionFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createPermission = useCreatePermission()
|
||||
const updatePermission = useUpdatePermission(permissionId ?? 0)
|
||||
|
||||
const isPending = createPermission.isPending || updatePermission.isPending
|
||||
|
||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
const [form, setForm] = useState<PermissionPayload>({
|
||||
code: initialData?.code ?? '',
|
||||
guard_name: initialData?.guard_name ?? 'web',
|
||||
name: {
|
||||
tk: initialData?.name?.tk ?? '',
|
||||
ru: initialData?.name?.ru ?? '',
|
||||
en: initialData?.name?.en ?? '',
|
||||
},
|
||||
})
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
const setField = (field: keyof Omit<PermissionPayload, 'name'>, value: string) => {
|
||||
setForm((prev) => ({ ...prev, [field]: value }))
|
||||
setErrors((prev) => ({ ...prev, [field]: undefined }))
|
||||
}
|
||||
|
||||
const setNameField = (lang: LangKey, value: string) => {
|
||||
setForm((prev) => ({ ...prev, name: { ...prev.name, [lang]: value } }))
|
||||
setErrors((prev) => ({ ...prev, [`name_${lang}`]: undefined }))
|
||||
}
|
||||
|
||||
// ── Validation ─────────────────────────────────────────────────────────────
|
||||
|
||||
const validate = (): boolean => {
|
||||
const newErrors: FormErrors = {}
|
||||
|
||||
if (!form.code.trim())
|
||||
newErrors.code = t('permissions.validation.codeRequired', 'Kod hökman!')
|
||||
if (!form.name.tk.trim())
|
||||
newErrors.name_tk = t('permissions.validation.nameTkRequired', 'Türkmençe ady hökman!')
|
||||
if (!form.guard_name.trim())
|
||||
newErrors.guard_name = t('permissions.validation.guardRequired', 'Guard name hökman!')
|
||||
|
||||
setErrors(newErrors)
|
||||
return Object.keys(newErrors).length === 0
|
||||
}
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!validate()) return
|
||||
|
||||
if (mode === 'create') {
|
||||
createPermission.mutate(form, {
|
||||
onSuccess: () => navigate('/settings/users/permissions'),
|
||||
})
|
||||
} else {
|
||||
updatePermission.mutate(form, {
|
||||
onSuccess: () => navigate('/settings/users/permissions'),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
|
||||
{/* Code */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start p-5 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('permissions.fields.code', 'Kod')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.code}
|
||||
onChange={(v) => setField('code', v)}
|
||||
placeholder={t('permissions.fields.code', 'Kod')}
|
||||
error={errors.code}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Name (multilingual) */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start p-5 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('permissions.fields.name', 'Ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<div className="space-y-2">
|
||||
<div className="flex gap-1 justify-end">
|
||||
{LANG_TABS.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
type="button"
|
||||
onClick={() => setActiveLang(tab.key)}
|
||||
className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${
|
||||
activeLang === tab.key
|
||||
? 'text-primary border-b-2 border-primary'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.name[activeLang]}
|
||||
onChange={(v) => setNameField(activeLang, v)}
|
||||
placeholder={t('permissions.fields.name', 'Ady')}
|
||||
error={errors[`name_${activeLang}` as keyof FormErrors]}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Guard name */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start p-5">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('permissions.fields.guardName', 'Guard name')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="select"
|
||||
value={form.guard_name}
|
||||
onChange={(v) => setField('guard_name', v)}
|
||||
options={GUARD_OPTIONS}
|
||||
error={errors.guard_name}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center justify-end gap-3 px-5 py-4 border-t border-border bg-muted/20">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => navigate('/settings/users/permissions')}
|
||||
disabled={isPending}
|
||||
>
|
||||
{t('common.cancel', 'Ýatyr')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSubmit}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending
|
||||
? t('common.saving', 'Ýüklenýär...')
|
||||
: mode === 'create'
|
||||
? t('permissions.actions.create', 'Rugsat dörediň')
|
||||
: t('permissions.actions.save', 'Ýatda sakla')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
92
src/features/permissions/hooks/usePermissions.ts
Normal file
92
src/features/permissions/hooks/usePermissions.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
permissionsApi,
|
||||
type PermissionPayload,
|
||||
type PermissionsListParams,
|
||||
} from '../api/permissionsApi'
|
||||
|
||||
// ─── Query keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const permissionKeys = {
|
||||
all: ['permissions'] as const,
|
||||
list: (params: PermissionsListParams) => ['permissions', 'list', params] as const,
|
||||
detail: (id: number) => ['permissions', 'detail', id] as const,
|
||||
}
|
||||
|
||||
// ─── usePermissions (list) ────────────────────────────────────────────────────
|
||||
|
||||
export function usePermissions(params: PermissionsListParams) {
|
||||
return useQuery({
|
||||
queryKey: permissionKeys.list(params),
|
||||
queryFn: () => permissionsApi.getAll(params).then((r) => r.data),
|
||||
})
|
||||
}
|
||||
|
||||
// ─── usePermission (single) ───────────────────────────────────────────────────
|
||||
|
||||
export function usePermission(id: number) {
|
||||
return useQuery({
|
||||
queryKey: permissionKeys.detail(id),
|
||||
queryFn: () => permissionsApi.getById(id).then((r) => r.data),
|
||||
enabled: !!id,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useCreatePermission ──────────────────────────────────────────────────────
|
||||
|
||||
export function useCreatePermission() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: PermissionPayload) =>
|
||||
permissionsApi.create(payload).then((r) => r.data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.all })
|
||||
toast.success(t('permissions.toast.created', 'Rugsat üstünlikli döredildi!'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('permissions.toast.createError', 'Rugsat döretmekde ýalňyşlyk ýüze çykdy.'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useUpdatePermission ──────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdatePermission(id: number) {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: PermissionPayload) =>
|
||||
permissionsApi.update(id, payload).then((r) => r.data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.all })
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.detail(id) })
|
||||
toast.success(t('permissions.toast.updated', 'Rugsat üstünlikli üýtgedildi!'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('permissions.toast.updateError', 'Rugsat üýtgetmekde ýalňyşlyk ýüze çykdy.'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useDeletePermission ──────────────────────────────────────────────────────
|
||||
|
||||
export function useDeletePermission() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => permissionsApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.all })
|
||||
toast.success(t('permissions.toast.deleted', 'Rugsat üstünlikli pozuldy!'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('permissions.toast.deleteError', 'Rugsat pozmakda ýalňyşlyk ýüze çykdy.'))
|
||||
},
|
||||
})
|
||||
}
|
||||
118
src/features/roles/api/rolesApi.ts
Normal file
118
src/features/roles/api/rolesApi.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
// import {apiClient} from '@/lib/api/client'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface RoleTranslation {
|
||||
tk: string
|
||||
ru: string
|
||||
en: string
|
||||
}
|
||||
|
||||
export interface Role {
|
||||
id: number
|
||||
code: string
|
||||
name: RoleTranslation
|
||||
guard_name: string
|
||||
}
|
||||
|
||||
export interface RolePayload {
|
||||
code: string
|
||||
name: RoleTranslation
|
||||
guard_name: string
|
||||
}
|
||||
|
||||
export interface RolesListParams {
|
||||
search?: string
|
||||
page?: number
|
||||
per_page?: number
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[]
|
||||
meta: {
|
||||
current_page: number
|
||||
last_page: number
|
||||
per_page: number
|
||||
total: number
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_ROLES: Role[] = [
|
||||
{ id: 1, code: 'admin', guard_name: 'web', name: { tk: 'Administrator', ru: 'Администратор', en: 'Administrator' } },
|
||||
{ id: 2, code: 'operator', guard_name: 'web', name: { tk: 'Operator', ru: 'Оператор', en: 'Operator' } },
|
||||
{ id: 3, code: 'manager', guard_name: 'web', name: { tk: 'Menijer', ru: 'Менеджер', en: 'Manager' } },
|
||||
{ id: 4, code: 'editor', guard_name: 'web', name: { tk: 'Redaktor', ru: 'Редактор', en: 'Editor' } },
|
||||
]
|
||||
|
||||
const delay = (ms = 500) => new Promise((res) => setTimeout(res, ms))
|
||||
|
||||
// ─── API functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export const rolesApi = {
|
||||
getAll: async (params?: RolesListParams): Promise<{ data: PaginatedResponse<Role> }> => {
|
||||
await delay()
|
||||
const { search = '', page = 1, per_page = 25 } = params ?? {}
|
||||
|
||||
let filtered = [...MOCK_ROLES]
|
||||
if (search) {
|
||||
const s = search.toLowerCase()
|
||||
filtered = filtered.filter(
|
||||
(r) =>
|
||||
r.code.toLowerCase().includes(s) ||
|
||||
r.name.tk.toLowerCase().includes(s) ||
|
||||
r.name.ru.toLowerCase().includes(s) ||
|
||||
r.name.en.toLowerCase().includes(s)
|
||||
)
|
||||
}
|
||||
|
||||
const total = filtered.length
|
||||
const last_page = Math.ceil(total / per_page)
|
||||
const start = (page - 1) * per_page
|
||||
const data = filtered.slice(start, start + per_page)
|
||||
|
||||
return {
|
||||
data: {
|
||||
data,
|
||||
meta: {
|
||||
current_page: page,
|
||||
last_page,
|
||||
per_page,
|
||||
total,
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
getById: async (id: number): Promise<{ data: Role }> => {
|
||||
await delay()
|
||||
const item = MOCK_ROLES.find((r) => r.id === id)
|
||||
if (!item) throw new Error('Not found')
|
||||
return { data: item }
|
||||
},
|
||||
|
||||
create: async (payload: RolePayload): Promise<{ data: Role }> => {
|
||||
await delay()
|
||||
const newItem: Role = {
|
||||
...payload,
|
||||
id: Math.floor(Math.random() * 10000),
|
||||
}
|
||||
MOCK_ROLES.push(newItem)
|
||||
return { data: newItem }
|
||||
},
|
||||
|
||||
update: async (id: number, payload: RolePayload): Promise<{ data: Role }> => {
|
||||
await delay()
|
||||
const index = MOCK_ROLES.findIndex((r) => r.id === id)
|
||||
if (index === -1) throw new Error('Not found')
|
||||
MOCK_ROLES[index] = { ...MOCK_ROLES[index], ...payload }
|
||||
return { data: MOCK_ROLES[index] }
|
||||
},
|
||||
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await delay()
|
||||
const index = MOCK_ROLES.findIndex((r) => r.id === id)
|
||||
if (index !== -1) MOCK_ROLES.splice(index, 1)
|
||||
},
|
||||
}
|
||||
203
src/features/roles/components/roleForm.tsx
Normal file
203
src/features/roles/components/roleForm.tsx
Normal file
@@ -0,0 +1,203 @@
|
||||
import { 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 { useCreateRole, useUpdateRole } from '../hooks/useRoles'
|
||||
import type { Role, RolePayload } from '../api/rolesApi'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface RoleFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: Role
|
||||
roleId?: number
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
code?: string
|
||||
name_tk?: string
|
||||
name_ru?: string
|
||||
name_en?: string
|
||||
guard_name?: string
|
||||
}
|
||||
|
||||
type LangKey = 'tk' | 'ru' | 'en'
|
||||
|
||||
const LANG_TABS: { key: LangKey; label: string }[] = [
|
||||
{ key: 'tk', label: 'Türkmen' },
|
||||
{ key: 'ru', label: 'Русский' },
|
||||
{ key: 'en', label: 'English' },
|
||||
]
|
||||
|
||||
const GUARD_OPTIONS = [
|
||||
{ value: 'web', label: 'web' },
|
||||
{ value: 'api', label: 'api' },
|
||||
{ value: 'sanctum', label: 'sanctum' },
|
||||
]
|
||||
|
||||
// ─── RoleForm ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export function RoleForm({ mode, initialData, roleId }: RoleFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createRole = useCreateRole()
|
||||
const updateRole = useUpdateRole(roleId ?? 0)
|
||||
|
||||
const isPending = createRole.isPending || updateRole.isPending
|
||||
|
||||
const [activeLang, setActiveLang] = useState<LangKey>('tk')
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
const [form, setForm] = useState<RolePayload>({
|
||||
code: initialData?.code ?? '',
|
||||
guard_name: initialData?.guard_name ?? 'web',
|
||||
name: {
|
||||
tk: initialData?.name?.tk ?? '',
|
||||
ru: initialData?.name?.ru ?? '',
|
||||
en: initialData?.name?.en ?? '',
|
||||
},
|
||||
})
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
const setField = (field: keyof Omit<RolePayload, 'name'>, value: string) => {
|
||||
setForm((prev) => ({ ...prev, [field]: value }))
|
||||
setErrors((prev) => ({ ...prev, [field]: undefined }))
|
||||
}
|
||||
|
||||
const setNameField = (lang: LangKey, value: string) => {
|
||||
setForm((prev) => ({ ...prev, name: { ...prev.name, [lang]: value } }))
|
||||
setErrors((prev) => ({ ...prev, [`name_${lang}`]: undefined }))
|
||||
}
|
||||
|
||||
// ── Validation ─────────────────────────────────────────────────────────────
|
||||
|
||||
const validate = (): boolean => {
|
||||
const newErrors: FormErrors = {}
|
||||
|
||||
if (!form.code.trim())
|
||||
newErrors.code = t('roles.validation.codeRequired', 'Kod hökman!')
|
||||
if (!form.name.tk.trim())
|
||||
newErrors.name_tk = t('roles.validation.nameTkRequired', 'Türkmençe ady hökman!')
|
||||
if (!form.guard_name.trim())
|
||||
newErrors.guard_name = t('roles.validation.guardRequired', 'Guard name hökman!')
|
||||
|
||||
setErrors(newErrors)
|
||||
return Object.keys(newErrors).length === 0
|
||||
}
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!validate()) return
|
||||
|
||||
if (mode === 'create') {
|
||||
createRole.mutate(form, {
|
||||
onSuccess: () => navigate('/settings/users/roles'),
|
||||
})
|
||||
} else {
|
||||
updateRole.mutate(form, {
|
||||
onSuccess: () => navigate('/settings/users/roles'),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
|
||||
{/* Code */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start p-5 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('roles.fields.code', 'Kod')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.code}
|
||||
onChange={(v) => setField('code', v)}
|
||||
placeholder={t('roles.fields.code', 'Kod')}
|
||||
error={errors.code}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Name (multilingual) */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start p-5 border-b border-border">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('roles.fields.name', 'Ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<div className="space-y-2">
|
||||
{/* Language tabs */}
|
||||
<div className="flex gap-1 justify-end">
|
||||
{LANG_TABS.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
type="button"
|
||||
onClick={() => setActiveLang(tab.key)}
|
||||
className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${
|
||||
activeLang === tab.key
|
||||
? 'text-primary border-b-2 border-primary'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.name[activeLang]}
|
||||
onChange={(v) => setNameField(activeLang, v)}
|
||||
placeholder={t('roles.fields.name', 'Ady')}
|
||||
error={errors[`name_${activeLang}` as keyof FormErrors]}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Guard name */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start p-5">
|
||||
<span className="text-sm text-muted-foreground pt-2">
|
||||
{t('roles.fields.guardName', 'Guard name')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</span>
|
||||
<FormInput
|
||||
type="select"
|
||||
value={form.guard_name}
|
||||
onChange={(v) => setField('guard_name', v)}
|
||||
options={GUARD_OPTIONS}
|
||||
error={errors.guard_name}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center justify-end gap-3 px-5 py-4 border-t border-border bg-muted/20">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => navigate('/settings/users/roles')}
|
||||
disabled={isPending}
|
||||
>
|
||||
{t('common.cancel', 'Ýatyr')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSubmit}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending
|
||||
? t('common.saving', 'Ýüklenýär...')
|
||||
: mode === 'create'
|
||||
? t('roles.actions.create', 'Rol dörediň')
|
||||
: t('roles.actions.save', 'Ýatda sakla')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
86
src/features/roles/hooks/useRoles.ts
Normal file
86
src/features/roles/hooks/useRoles.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { rolesApi, type RolePayload, type RolesListParams } from '../api/rolesApi'
|
||||
|
||||
// ─── Query keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const roleKeys = {
|
||||
all: ['roles'] as const,
|
||||
list: (params: RolesListParams) => ['roles', 'list', params] as const,
|
||||
detail: (id: number) => ['roles', 'detail', id] as const,
|
||||
}
|
||||
|
||||
// ─── useRoles (list) ──────────────────────────────────────────────────────────
|
||||
|
||||
export function useRoles(params: RolesListParams) {
|
||||
return useQuery({
|
||||
queryKey: roleKeys.list(params),
|
||||
queryFn: () => rolesApi.getAll(params).then((r) => r.data),
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useRole (single) ─────────────────────────────────────────────────────────
|
||||
|
||||
export function useRole(id: number) {
|
||||
return useQuery({
|
||||
queryKey: roleKeys.detail(id),
|
||||
queryFn: () => rolesApi.getById(id).then((r) => r.data),
|
||||
enabled: !!id,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useCreateRole ────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateRole() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: RolePayload) => rolesApi.create(payload).then((r) => r.data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.all })
|
||||
toast.success(t('roles.toast.created', 'Rol üstünlikli döredildi!'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('roles.toast.createError', 'Rol döretmekde ýalňyşlyk ýüze çykdy.'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useUpdateRole ────────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateRole(id: number) {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: RolePayload) => rolesApi.update(id, payload).then((r) => r.data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.all })
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.detail(id) })
|
||||
toast.success(t('roles.toast.updated', 'Rol üstünlikli üýtgedildi!'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('roles.toast.updateError', 'Roly üýtgetmekde ýalňyşlyk ýüze çykdy.'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useDeleteRole ────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteRole() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => rolesApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.all })
|
||||
toast.success(t('roles.toast.deleted', 'Rol üstünlikli pozuldy!'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('roles.toast.deleteError', 'Roly pozmakda ýalňyşlyk ýüze çykdy.'))
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
// features/visaMasterSettings/api/visaMasterSettingsApi.ts
|
||||
|
||||
export interface VisaMasterSetting {
|
||||
id: number
|
||||
kod: string
|
||||
ady: string
|
||||
yazgy: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface VisaMasterSettingListParams {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export interface VisaMasterSettingListResponse {
|
||||
data: VisaMasterSetting[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
totalPages: number
|
||||
}
|
||||
|
||||
export interface VisaMasterSettingPayload {
|
||||
kod: string
|
||||
ady: string
|
||||
yazgy: string
|
||||
}
|
||||
|
||||
// ─── Mock Store ───────────────────────────────────────────────────────────────
|
||||
|
||||
let mockStore: VisaMasterSetting[] = [
|
||||
{
|
||||
id: 2,
|
||||
kod: 'sber_payment_warning',
|
||||
ady: 'Sber töleg duýduryş',
|
||||
yazgy: 'Sber töleg duýduryş',
|
||||
createdAt: '2026-03-10T08:00:00Z',
|
||||
updatedAt: '2026-05-01T08:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
kod: 'payment_warning_text',
|
||||
ady: 'Visa/Master töleg duýduryş',
|
||||
yazgy: 'Dogry töleg aýyny saýlamagyňyzy haýyş edýäris!!!!',
|
||||
createdAt: '2026-01-05T09:00:00Z',
|
||||
updatedAt: '2026-04-20T09:00:00Z',
|
||||
},
|
||||
]
|
||||
|
||||
let nextId = 3
|
||||
|
||||
const delay = (ms = 400) => new Promise<void>((res) => setTimeout(res, ms))
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchVisaMasterSettings(
|
||||
params: VisaMasterSettingListParams = {}
|
||||
): Promise<VisaMasterSettingListResponse> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 25, search = '' } = params
|
||||
|
||||
let filtered = [...mockStore]
|
||||
|
||||
if (search.trim()) {
|
||||
const q = search.toLowerCase()
|
||||
filtered = filtered.filter(
|
||||
(r) =>
|
||||
r.kod.toLowerCase().includes(q) ||
|
||||
r.ady.toLowerCase().includes(q) ||
|
||||
r.yazgy.toLowerCase().includes(q) ||
|
||||
String(r.id).includes(q)
|
||||
)
|
||||
}
|
||||
|
||||
filtered.sort((a, b) => b.id - a.id)
|
||||
|
||||
const total = filtered.length
|
||||
const totalPages = Math.ceil(total / perPage) || 1
|
||||
const start = (page - 1) * perPage
|
||||
const data = filtered.slice(start, start + perPage)
|
||||
|
||||
return { data, total, page, perPage, totalPages }
|
||||
}
|
||||
|
||||
export async function fetchVisaMasterSettingById(id: number): Promise<VisaMasterSetting> {
|
||||
await delay()
|
||||
const item = mockStore.find((r) => r.id === id)
|
||||
if (!item) throw new Error(`VisaMasterSetting with id ${id} not found`)
|
||||
return { ...item }
|
||||
}
|
||||
|
||||
export async function createVisaMasterSetting(
|
||||
payload: VisaMasterSettingPayload
|
||||
): Promise<VisaMasterSetting> {
|
||||
await delay()
|
||||
const now = new Date().toISOString()
|
||||
const created: VisaMasterSetting = { id: nextId++, ...payload, createdAt: now, updatedAt: now }
|
||||
mockStore = [created, ...mockStore]
|
||||
return created
|
||||
}
|
||||
|
||||
export async function updateVisaMasterSetting(
|
||||
id: number,
|
||||
payload: VisaMasterSettingPayload
|
||||
): Promise<VisaMasterSetting> {
|
||||
await delay()
|
||||
const idx = mockStore.findIndex((r) => r.id === id)
|
||||
if (idx === -1) throw new Error(`VisaMasterSetting with id ${id} not found`)
|
||||
const updated: VisaMasterSetting = {
|
||||
...mockStore[idx],
|
||||
...payload,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
mockStore = mockStore.map((r) => (r.id === id ? updated : r))
|
||||
return updated
|
||||
}
|
||||
|
||||
export async function deleteVisaMasterSetting(id: number): Promise<void> {
|
||||
await delay()
|
||||
if (!mockStore.some((r) => r.id === id))
|
||||
throw new Error(`VisaMasterSetting with id ${id} not found`)
|
||||
mockStore = mockStore.filter((r) => r.id !== id)
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// features/visaMasterSettings/components/VisaMasterSettingForm.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 { type VisaMasterSetting } from '../api/visaMasterSberSettingsApi'
|
||||
import {
|
||||
useCreateVisaMasterSetting,
|
||||
useUpdateVisaMasterSetting,
|
||||
} from '../hooks/useVisaMasterSettings'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface FormState {
|
||||
kod: string
|
||||
ady: string
|
||||
yazgy: string
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
kod?: string
|
||||
ady?: string
|
||||
yazgy?: string
|
||||
}
|
||||
|
||||
export interface VisaMasterSettingFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: VisaMasterSetting
|
||||
settingId?: number
|
||||
}
|
||||
|
||||
// ─── Validation ───────────────────────────────────────────────────────────────
|
||||
|
||||
function validate(
|
||||
form: FormState,
|
||||
t: (key: string, fallback: string) => string
|
||||
): FormErrors {
|
||||
const errors: FormErrors = {}
|
||||
|
||||
if (!form.kod.trim())
|
||||
errors.kod = t('visaMasterSettings.errors.kodRequired', 'Kod giriziň')
|
||||
|
||||
if (!form.ady.trim())
|
||||
errors.ady = t('visaMasterSettings.errors.adyRequired', 'Ady giriziň')
|
||||
|
||||
if (!form.yazgy.trim())
|
||||
errors.yazgy = t('visaMasterSettings.errors.yazgyRequired', 'Yazgy giriziň')
|
||||
|
||||
return errors
|
||||
}
|
||||
|
||||
// ─── VisaMasterSettingForm ────────────────────────────────────────────────────
|
||||
|
||||
export function VisaMasterSettingForm({
|
||||
mode,
|
||||
initialData,
|
||||
settingId,
|
||||
}: VisaMasterSettingFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [form, setForm] = useState<FormState>({
|
||||
kod: initialData?.kod ?? '',
|
||||
ady: initialData?.ady ?? '',
|
||||
yazgy: initialData?.yazgy ?? '',
|
||||
})
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
|
||||
const createMutation = useCreateVisaMasterSetting()
|
||||
const updateMutation = useUpdateVisaMasterSetting(settingId ?? 0)
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
// Sync when initialData arrives (edit mode async fetch)
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
setForm({
|
||||
kod: initialData.kod,
|
||||
ady: initialData.ady,
|
||||
yazgy: initialData.yazgy,
|
||||
})
|
||||
}
|
||||
}, [mode, initialData])
|
||||
|
||||
const setField = (field: keyof FormState) => (val: string) => {
|
||||
setForm((prev) => ({ ...prev, [field]: val }))
|
||||
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 = { kod: form.kod.trim(), ady: form.ady.trim(), yazgy: form.yazgy.trim() }
|
||||
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(payload)
|
||||
navigate('/resources/visa-master-settings')
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload)
|
||||
navigate('/resources/visa-master-settings')
|
||||
}
|
||||
}
|
||||
|
||||
const handleCancel = () => navigate('/resources/visa-master-settings')
|
||||
|
||||
// ─── Render ───────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="space-y-0">
|
||||
{/* Kod */}
|
||||
<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('visaMasterSettings.fields.kod', 'Kod')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.kod}
|
||||
onChange={setField('kod')}
|
||||
placeholder={t('visaMasterSettings.fields.kod', 'Kod')}
|
||||
error={errors.kod}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Ady */}
|
||||
<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('visaMasterSettings.fields.ady', 'Ady')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<FormInput
|
||||
type="text"
|
||||
value={form.ady}
|
||||
onChange={setField('ady')}
|
||||
placeholder={t('visaMasterSettings.fields.ady', 'Ady')}
|
||||
error={errors.ady}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Yazgy */}
|
||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6">
|
||||
<label className="text-sm text-muted-foreground pt-1.5">
|
||||
{t('visaMasterSettings.fields.yazgy', 'Yazgy')}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</label>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
value={form.yazgy}
|
||||
onChange={setField('yazgy')}
|
||||
placeholder={t('visaMasterSettings.fields.yazgy', 'Yazgy')}
|
||||
error={errors.yazgy}
|
||||
disabled={isPending}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<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('visaMasterSettings.actions.create', 'Visa/Master, Sber sazlamalar dörediň')
|
||||
: t('visaMasterSettings.actions.update', 'Ýatda sakla')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// features/visaMasterSettings/hooks/useVisaMasterSettings.ts
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
fetchVisaMasterSettings,
|
||||
fetchVisaMasterSettingById,
|
||||
createVisaMasterSetting,
|
||||
updateVisaMasterSetting,
|
||||
deleteVisaMasterSetting,
|
||||
type VisaMasterSettingListParams,
|
||||
type VisaMasterSettingPayload,
|
||||
} from '../api/visaMasterSberSettingsApi'
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const visaMasterSettingKeys = {
|
||||
all: ['visaMasterSettings'] as const,
|
||||
lists: () => [...visaMasterSettingKeys.all, 'list'] as const,
|
||||
list: (params: VisaMasterSettingListParams) =>
|
||||
[...visaMasterSettingKeys.lists(), params] as const,
|
||||
detail: (id: number) =>
|
||||
[...visaMasterSettingKeys.all, 'detail', id] as const,
|
||||
}
|
||||
|
||||
// ─── useGetVisaMasterSettings ─────────────────────────────────────────────────
|
||||
|
||||
export function useGetVisaMasterSettings(params: VisaMasterSettingListParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: visaMasterSettingKeys.list(params),
|
||||
queryFn: () => fetchVisaMasterSettings(params),
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useGetVisaMasterSettingById ──────────────────────────────────────────────
|
||||
|
||||
export function useGetVisaMasterSettingById(id: number) {
|
||||
return useQuery({
|
||||
queryKey: visaMasterSettingKeys.detail(id),
|
||||
queryFn: () => fetchVisaMasterSettingById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useCreateVisaMasterSetting ───────────────────────────────────────────────
|
||||
|
||||
export function useCreateVisaMasterSetting() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: VisaMasterSettingPayload) => createVisaMasterSetting(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.lists() })
|
||||
toast.success(t('visaMasterSettings.toast.created', 'Sazlama döredildi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('visaMasterSettings.toast.createError', 'Döretmek başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useUpdateVisaMasterSetting ───────────────────────────────────────────────
|
||||
|
||||
export function useUpdateVisaMasterSetting(id: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: VisaMasterSettingPayload) => updateVisaMasterSetting(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.detail(id) })
|
||||
toast.success(t('visaMasterSettings.toast.updated', 'Sazlama üýtgedildi'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('visaMasterSettings.toast.updateError', 'Üýtgetmek başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useDeleteVisaMasterSetting ───────────────────────────────────────────────
|
||||
|
||||
export function useDeleteVisaMasterSetting() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteVisaMasterSetting(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.lists() })
|
||||
toast.success(t('visaMasterSettings.toast.deleted', 'Sazlama pozuldy'))
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('visaMasterSettings.toast.deleteError', 'Pozmak başartmady'))
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user