connected with backups and currency rates
This commit is contained in:
@@ -1,78 +1,95 @@
|
||||
import apiClient from '@/lib/api/client'
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
export type BackupStatus = 'completed' | 'failed' | 'in_progress'
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type BackupStatus = "pending" | "in_progress" | "completed" | "failed";
|
||||
|
||||
export interface BackupUser {
|
||||
id: number;
|
||||
name: string;
|
||||
username: string;
|
||||
phone: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
/** Raw backend entity (GET responses mirror this shape). */
|
||||
export interface Backup {
|
||||
id: number
|
||||
fileName: string
|
||||
fileSize: string
|
||||
status: BackupStatus
|
||||
createdAt: string
|
||||
createdBy: string
|
||||
id: number;
|
||||
fileName: string;
|
||||
sizeBytes: number;
|
||||
size: string;
|
||||
status: BackupStatus;
|
||||
createdBy: BackupUser;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** LIST RESPONSE: GET /backups */
|
||||
export interface BackupListResponse {
|
||||
data: Backup[]
|
||||
total: number
|
||||
page: number
|
||||
per_page: number
|
||||
count: number;
|
||||
backups: Backup[];
|
||||
}
|
||||
|
||||
/** LIST PARAMS */
|
||||
export interface BackupListParams {
|
||||
page?: number
|
||||
per_page?: number
|
||||
search?: string
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
const MOCK_BACKUPS: Backup[] = [
|
||||
{ id: 1, fileName: 'backup_2026_05_22_01.sql', fileSize: '256 MB', status: 'completed', createdAt: '2026-05-22 03:00', createdBy: 'Admin' },
|
||||
{ id: 2, fileName: 'backup_2026_05_21_01.sql', fileSize: '251 MB', status: 'completed', createdAt: '2026-05-21 03:00', createdBy: 'Admin' },
|
||||
{ id: 3, fileName: 'backup_2026_05_20_01.sql', fileSize: '248 MB', status: 'completed', createdAt: '2026-05-20 03:00', createdBy: 'Admin' },
|
||||
{ id: 4, fileName: 'backup_2026_05_19_01.sql', fileSize: '245 MB', status: 'failed', createdAt: '2026-05-19 03:05', createdBy: 'Admin' },
|
||||
{ id: 5, fileName: 'backup_2026_05_18_01.sql', fileSize: '242 MB', status: 'completed', createdAt: '2026-05-18 03:00', createdBy: 'System' },
|
||||
]
|
||||
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||
|
||||
export const backupsApi = {
|
||||
getAll: async (params?: BackupListParams): Promise<BackupListResponse> => {
|
||||
const { data } = await apiClient.get('/backups', { params }).catch(() => ({ data: null }))
|
||||
if (data) return data
|
||||
|
||||
const { search = '', page = 1, per_page = 25 } = params ?? {}
|
||||
let filtered = [...MOCK_BACKUPS]
|
||||
if (search) {
|
||||
const s = search.toLowerCase()
|
||||
filtered = filtered.filter((b) => b.fileName.toLowerCase().includes(s))
|
||||
}
|
||||
const total = filtered.length
|
||||
const start = (page - 1) * per_page
|
||||
return { data: filtered.slice(start, start + per_page), total, page, per_page }
|
||||
getList: async (params: BackupListParams = {}, signal?: AbortSignal): Promise<BackupListResponse> => {
|
||||
const { page, limit, search, status } = params;
|
||||
const { data } = await apiClient.get<BackupListResponse>("/backups", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
search: search || undefined,
|
||||
status: status || undefined,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
getById: async (id: number): Promise<Backup> => {
|
||||
const { data } = await apiClient.get<Backup>(`/backups/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
/** POST /backups — no payload, backend creates the backup. */
|
||||
create: async (): Promise<Backup> => {
|
||||
const { data } = await apiClient.post('/backups').catch(() => ({ data: null }))
|
||||
if (data) return data
|
||||
|
||||
const newBackup: Backup = {
|
||||
id: Math.floor(Math.random() * 10000),
|
||||
fileName: `backup_${new Date().toISOString().slice(0, 10).replace(/-/g, '_')}_01.sql`,
|
||||
fileSize: '0 MB',
|
||||
status: 'in_progress',
|
||||
createdAt: new Date().toLocaleString('tr-TR'),
|
||||
createdBy: 'Admin',
|
||||
}
|
||||
MOCK_BACKUPS.unshift(newBackup)
|
||||
return newBackup
|
||||
const { data } = await apiClient.post<Backup>("/backups");
|
||||
return data;
|
||||
},
|
||||
|
||||
download: async (id: number): Promise<Blob> => {
|
||||
const { data } = await apiClient.get(`/backups/${id}/download`, { responseType: 'blob' }).catch(() => ({ data: null }))
|
||||
if (data) return data
|
||||
return new Blob(['mock backup content'], { type: 'application/sql' })
|
||||
download: async (id: number): Promise<{ blob: Blob; fileName?: string }> => {
|
||||
const response = await apiClient.get<Blob>(`/backups/${id}/download`, {
|
||||
responseType: "blob",
|
||||
});
|
||||
|
||||
let fileName: string | undefined;
|
||||
const disposition =
|
||||
(response.headers?.["content-disposition"] as string | undefined) ||
|
||||
(response.headers?.["Content-Disposition"] as string | undefined);
|
||||
|
||||
if (disposition) {
|
||||
const match = disposition.match(/filename\*?=(?:UTF-8'')?["']?([^"';]+)["']?/i);
|
||||
if (match && match[1]) {
|
||||
fileName = decodeURIComponent(match[1].trim());
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
blob: response.data,
|
||||
fileName,
|
||||
};
|
||||
},
|
||||
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await apiClient.delete(`/backups/${id}`).catch(() => {})
|
||||
const index = MOCK_BACKUPS.findIndex((b) => b.id === id)
|
||||
if (index !== -1) MOCK_BACKUPS.splice(index, 1)
|
||||
await apiClient.delete(`/backups/${id}`);
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,58 +1,91 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { backupsApi, type BackupListParams } from '../api/backupsApi'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { backupsApi, type BackupListParams } from "../api/backupsApi";
|
||||
|
||||
const QUERY_KEY = 'backups'
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function useBackups(params?: BackupListParams) {
|
||||
export const backupKeys = {
|
||||
all: ["backups"] as const,
|
||||
lists: () => [...backupKeys.all, "list"] as const,
|
||||
list: (params: BackupListParams) => [...backupKeys.lists(), params] as const,
|
||||
details: () => [...backupKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...backupKeys.details(), id] as const,
|
||||
};
|
||||
|
||||
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useBackups(params: BackupListParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: [QUERY_KEY, params],
|
||||
queryFn: () => backupsApi.getAll(params),
|
||||
})
|
||||
queryKey: backupKeys.list(params),
|
||||
queryFn: ({ signal }) => backupsApi.getList(params, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Single ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useBackup(id: number) {
|
||||
return useQuery({
|
||||
queryKey: backupKeys.detail(id),
|
||||
queryFn: () => backupsApi.getById(id),
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateBackup() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: () => backupsApi.create(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
||||
toast.success(t('backups.toast.created', 'Backup üstünlikli döredildi!'))
|
||||
queryClient.invalidateQueries({ queryKey: backupKeys.lists() });
|
||||
toast.success(t("backups.toast.created", "Backup üstünlikli döredildi!"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadBackup() {
|
||||
const { t } = useTranslation()
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (id: number) => {
|
||||
const blob = await backupsApi.download(id)
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `backup-${id}.sql`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
mutationFn: async (param: number | { id: number; fileName?: string }) => {
|
||||
const id = typeof param === "number" ? param : param.id;
|
||||
const fallbackName = typeof param === "object" ? param.fileName : undefined;
|
||||
|
||||
const { blob, fileName } = await backupsApi.download(id);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = fileName || fallbackName || `backup-${id}.sql`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(t('backups.toast.downloaded', 'Backup üstünlikli ýüklenildi'))
|
||||
toast.success(t("backups.toast.downloaded", "Backup üstünlikli ýüklenildi"));
|
||||
},
|
||||
})
|
||||
onError: () => {
|
||||
toast.error(t("common.error", "Ýalňyşlyk ýüze çykdy"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteBackup() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => backupsApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
||||
toast.success(t('backups.toast.deleted', 'Backup üstünlikli pozuldy!'))
|
||||
queryClient.invalidateQueries({ queryKey: backupKeys.lists() });
|
||||
toast.success(t("backups.toast.deleted", "Backup üstünlikli pozuldy!"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import type { CardBalanceStatus } from "../api/cardBalanceApi";
|
||||
|
||||
const STATUS_CONFIG: Record<
|
||||
CardBalanceStatus,
|
||||
{ labelKey: string; fallback: string; variant: StatusBadgeVariant; icon: React.ElementType }
|
||||
> = {
|
||||
pending: { labelKey: "cardBalance.status.pending", fallback: "Garaşylýar", variant: "warning", icon: AlertCircle },
|
||||
approved: { labelKey: "cardBalance.status.approved", fallback: "Tassyklanan", variant: "success", icon: CheckCircle2 },
|
||||
rejected: { labelKey: "cardBalance.status.rejected", fallback: "Ret edilen", variant: "error", icon: XCircle },
|
||||
};
|
||||
|
||||
export function CardBalanceStatusBadge({ status }: { status: string }) {
|
||||
const { t } = useTranslation();
|
||||
const cfg = STATUS_CONFIG[status as CardBalanceStatus];
|
||||
if (!cfg) return <span className="text-xs text-muted-foreground">{status}</span>;
|
||||
return <StatusBadge label={t(cfg.labelKey, cfg.fallback)} variant={cfg.variant} icon={cfg.icon} />;
|
||||
}
|
||||
@@ -2,6 +2,17 @@ import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CardTypeInfo {
|
||||
id: number;
|
||||
name:
|
||||
| {
|
||||
en?: string;
|
||||
ru?: string;
|
||||
tm?: string;
|
||||
}
|
||||
| string;
|
||||
}
|
||||
|
||||
export interface Card {
|
||||
id: number;
|
||||
user: { id: number; name: string; username: string; phone: string; email: string } | null;
|
||||
@@ -9,7 +20,8 @@ export interface Card {
|
||||
name: string;
|
||||
month: string;
|
||||
year: string;
|
||||
type: string;
|
||||
type?: string;
|
||||
cardType?: CardTypeInfo | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
@@ -1,141 +1,97 @@
|
||||
// features/currencyRates/api/currencyRatesApi.ts
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
export type CurrencyCode = 'USD' | 'RUB' | 'TMT' | 'EUR' | 'GBP' | 'CNY' | 'TRY'
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CurrencyRateUser {
|
||||
id: number;
|
||||
name: string;
|
||||
username: string;
|
||||
phone: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
/** Raw backend entity (GET responses mirror this shape). */
|
||||
export interface CurrencyRate {
|
||||
id: number
|
||||
currencyFrom: CurrencyCode
|
||||
currencyTo: CurrencyCode
|
||||
value: number
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface CurrencyRateListParams {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
id: number;
|
||||
currencyFrom: string;
|
||||
currencyTo: string;
|
||||
value: number;
|
||||
createdBy: CurrencyRateUser;
|
||||
updatedBy: CurrencyRateUser;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** LIST RESPONSE: GET /currencies */
|
||||
export interface CurrencyRateListResponse {
|
||||
data: CurrencyRate[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
totalPages: number
|
||||
count: number;
|
||||
currencies: CurrencyRate[];
|
||||
}
|
||||
|
||||
/** LIST PARAMS */
|
||||
export interface CurrencyRateListParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
currency_from?: string;
|
||||
currency_to?: string;
|
||||
}
|
||||
|
||||
/** CREATE / UPDATE PAYLOAD (camelCase, JSON) */
|
||||
export interface CreateCurrencyRatePayload {
|
||||
currencyFrom: CurrencyCode
|
||||
currencyTo: CurrencyCode
|
||||
value: number
|
||||
currencyFrom: string;
|
||||
currencyTo: string;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export type UpdateCurrencyRatePayload = CreateCurrencyRatePayload
|
||||
export type UpdateCurrencyRatePayload = CreateCurrencyRatePayload;
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||
|
||||
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' },
|
||||
]
|
||||
export const currencyRatesApi = {
|
||||
getList: async (params: CurrencyRateListParams = {}, signal?: AbortSignal): Promise<CurrencyRateListResponse> => {
|
||||
const { page, limit, search, currency_from, currency_to } = params;
|
||||
const { data } = await apiClient.get<CurrencyRateListResponse>("/currencies", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
search: search || undefined,
|
||||
currency_from: currency_from || undefined,
|
||||
currency_to: currency_to || undefined,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
let mockStore: CurrencyRate[] = [...MOCK_RATES]
|
||||
let nextId = 9
|
||||
getById: async (id: number): Promise<CurrencyRate> => {
|
||||
const { data } = await apiClient.get<CurrencyRate>(`/currencies/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
const delay = (ms = 400) => new Promise<void>((res) => setTimeout(res, ms))
|
||||
create: async (payload: CreateCurrencyRatePayload): Promise<CurrencyRate> => {
|
||||
const { data } = await apiClient.post<CurrencyRate>("/currencies", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
update: async (id: number, payload: UpdateCurrencyRatePayload): Promise<CurrencyRate> => {
|
||||
const { data } = await apiClient.put<CurrencyRate>(`/currencies/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
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)
|
||||
}
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await apiClient.delete(`/currencies/${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' },
|
||||
]
|
||||
export const CURRENCY_OPTIONS: { value: string; 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" },
|
||||
];
|
||||
|
||||
@@ -47,6 +47,16 @@ export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) {
|
||||
|
||||
const schema = useMemo(() => createCurrencyRateFormSchema(t), [t, i18n.language]);
|
||||
|
||||
const currencyOptions = useMemo(() => {
|
||||
const opts = [...CURRENCY_OPTIONS];
|
||||
if (initialData) {
|
||||
for (const v of [initialData.currencyFrom, initialData.currencyTo]) {
|
||||
if (v && !opts.some((o) => o.value === v)) opts.push({ value: v, label: v });
|
||||
}
|
||||
}
|
||||
return opts;
|
||||
}, [initialData]);
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
@@ -92,18 +102,18 @@ export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) {
|
||||
|
||||
if (mode === "create") {
|
||||
await createMutation.mutateAsync(payload);
|
||||
navigate("/resources/currency-rates");
|
||||
navigate("/currency-rates");
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload);
|
||||
navigate(`/resources/currency-rates/${initialData!.id}`);
|
||||
navigate(`/currency-rates/${initialData!.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
if (mode === "create") {
|
||||
navigate("/resources/currency-rates");
|
||||
navigate("/currency-rates");
|
||||
} else {
|
||||
navigate(`/resources/currency-rates/${initialData!.id}`);
|
||||
navigate(`/currency-rates/${initialData!.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -121,7 +131,7 @@ export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) {
|
||||
label={t("currencyRates.fields.currencyFrom", "Currency from")}
|
||||
value={form.currencyFrom}
|
||||
onChange={setField("currencyFrom")}
|
||||
options={CURRENCY_OPTIONS}
|
||||
options={currencyOptions}
|
||||
placeholder={t("common.selectPlaceholder", "Saýlamak üçin basyň")}
|
||||
error={errors.currencyFrom}
|
||||
disabled={isPending}
|
||||
@@ -135,7 +145,7 @@ export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) {
|
||||
label={t("currencyRates.fields.currencyTo", "Currency to")}
|
||||
value={form.currencyTo}
|
||||
onChange={setField("currencyTo")}
|
||||
options={CURRENCY_OPTIONS}
|
||||
options={currencyOptions}
|
||||
placeholder={t("common.selectPlaceholder", "Saýlamak üçin basyň")}
|
||||
error={errors.currencyTo}
|
||||
disabled={isPending}
|
||||
|
||||
@@ -1,91 +1,85 @@
|
||||
// features/currencyRates/hooks/useCurrencyRates.ts
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
fetchCurrencyRates,
|
||||
fetchCurrencyRateById,
|
||||
createCurrencyRate,
|
||||
updateCurrencyRate,
|
||||
deleteCurrencyRate,
|
||||
currencyRatesApi,
|
||||
type CurrencyRateListParams,
|
||||
type CreateCurrencyRatePayload,
|
||||
type UpdateCurrencyRatePayload,
|
||||
} from '../api/currencyRatesApi'
|
||||
} 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,
|
||||
}
|
||||
all: ["currencyRates"] as const,
|
||||
lists: () => [...currencyRateKeys.all, "list"] as const,
|
||||
list: (params: CurrencyRateListParams) => [...currencyRateKeys.lists(), params] as const,
|
||||
details: () => [...currencyRateKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...currencyRateKeys.details(), id] as const,
|
||||
};
|
||||
|
||||
// ─── useGetCurrencyRates ──────────────────────────────────────────────────────
|
||||
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useGetCurrencyRates(params: CurrencyRateListParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: currencyRateKeys.list(params),
|
||||
queryFn: () => fetchCurrencyRates(params),
|
||||
})
|
||||
queryFn: ({ signal }) => currencyRatesApi.getList(params, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useGetCurrencyRateById ───────────────────────────────────────────────────
|
||||
// ─── Single ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useGetCurrencyRateById(id: number) {
|
||||
return useQuery({
|
||||
queryKey: currencyRateKeys.detail(id),
|
||||
queryFn: () => fetchCurrencyRateById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
queryFn: () => currencyRatesApi.getById(id),
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCreateCurrencyRate ────────────────────────────────────────────────────
|
||||
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCurrencyRate() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateCurrencyRatePayload) => createCurrencyRate(payload),
|
||||
mutationFn: (payload: CreateCurrencyRatePayload) => currencyRatesApi.create(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() })
|
||||
toast.success(t('currencyRates.toast.created', 'Walýuta kursy döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() });
|
||||
toast.success(t("currencyRates.toast.created", "Walýuta kursy döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useUpdateCurrencyRate ────────────────────────────────────────────────────
|
||||
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCurrencyRate(id: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
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'))
|
||||
mutationFn: (payload: UpdateCurrencyRatePayload) => currencyRatesApi.update(id, payload),
|
||||
onSuccess: (updated) => {
|
||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() });
|
||||
queryClient.setQueryData(currencyRateKeys.detail(id), updated);
|
||||
toast.success(t("currencyRates.toast.updated", "Walýuta kursy üýtgedildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useDeleteCurrencyRate ────────────────────────────────────────────────────
|
||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCurrencyRate() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteCurrencyRate(id),
|
||||
mutationFn: (id: number) => currencyRatesApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() })
|
||||
toast.success(t('currencyRates.toast.deleted', 'Walýuta kursy pozuldy'))
|
||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() });
|
||||
toast.success(t("currencyRates.toast.deleted", "Walýuta kursy pozuldy"));
|
||||
},
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,29 +1,29 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateCurrencyRatePayload, CurrencyCode } from '../api/currencyRatesApi'
|
||||
import { z } from "zod";
|
||||
import type { CreateCurrencyRatePayload } from "../api/currencyRatesApi";
|
||||
|
||||
export function createCurrencyRateFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
currencyFrom: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
currencyTo: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
currencyFrom: z.string().min(1, t("validation.required", "validation.required")),
|
||||
currencyTo: z.string().min(1, t("validation.required", "validation.required")),
|
||||
value: z
|
||||
.string()
|
||||
.min(1, t('validation.required', 'validation.required'))
|
||||
.refine((v) => !isNaN(Number(v)) && Number(v) > 0, t('validation.valuePositive', 'validation.valuePositive')),
|
||||
})
|
||||
.min(1, t("validation.required", "validation.required"))
|
||||
.refine((v) => !isNaN(Number(v)) && Number(v) > 0, t("validation.valuePositive", "validation.valuePositive")),
|
||||
});
|
||||
}
|
||||
|
||||
export type CurrencyRateFormData = z.infer<ReturnType<typeof createCurrencyRateFormSchema>>
|
||||
export type CurrencyRateFormData = z.infer<ReturnType<typeof createCurrencyRateFormSchema>>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CurrencyRateFormData = {
|
||||
currencyFrom: '',
|
||||
currencyTo: '',
|
||||
value: '',
|
||||
}
|
||||
currencyFrom: "",
|
||||
currencyTo: "",
|
||||
value: "",
|
||||
};
|
||||
|
||||
export function buildPayload(data: CurrencyRateFormData): CreateCurrencyRatePayload {
|
||||
return {
|
||||
currencyFrom: data.currencyFrom as CurrencyCode,
|
||||
currencyTo: data.currencyTo as CurrencyCode,
|
||||
currencyFrom: data.currencyFrom,
|
||||
currencyTo: data.currencyTo,
|
||||
value: Number(data.value),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user