connected with backups and currency rates
This commit is contained in:
@@ -105,6 +105,7 @@ const DistrictsViewPage = lazy(() => import("@/pages/settings/location/districts
|
||||
const DistrictEditPage = lazy(() => import("@/pages/settings/location/districtsEdit"));
|
||||
const BranchesPage = lazy(() => import("@/pages/settings/location/branches"));
|
||||
const BackupsPage = lazy(() => import("@/pages/backups"));
|
||||
const BackupViewPage = lazy(() => import("@/pages/backupsView"));
|
||||
const ActivityLogsPage = lazy(() => import("@/pages/logs"));
|
||||
const ActivityLogViewPage = lazy(() => import("@/pages/logs/view"));
|
||||
const BranchCreatePage = lazy(() => import("@/pages/settings/location/branchesCreate"));
|
||||
@@ -584,9 +585,15 @@ const routes: AppRoute[] = [
|
||||
|
||||
// ── BEKAPLAR ──────────────────────────────────────────────────────
|
||||
{
|
||||
path: "/backups",
|
||||
handle: { title: (t) => t("backups.title", "Bekaplar") },
|
||||
element: page(BackupsPage),
|
||||
...bc((t) => t("backups.title", "Bekaplar"), "/backups"),
|
||||
children: [
|
||||
{ path: "/backups", element: page(BackupsPage) },
|
||||
{
|
||||
path: "/backups/:id",
|
||||
handle: { title: (t) => t("backups.viewTitle", "Backup giňişleýin") },
|
||||
element: page(BackupViewPage),
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
// ── LOGLAR ──────────────────────────────────────────────────────
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -52,10 +52,19 @@ apiClient.interceptors.request.use(
|
||||
);
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
// Başarılı response'larda envelope'u soyup direkt `data`yı döndürüyoruz.
|
||||
// Böylece feature API fonksiyonları `response.data.data` yerine `response.data` yazar.
|
||||
(response) => {
|
||||
response.data = (response.data as ApiSuccessResponse<unknown>)?.data;
|
||||
if (
|
||||
response.config.responseType === "blob" ||
|
||||
response.config.responseType === "arraybuffer" ||
|
||||
response.data instanceof Blob ||
|
||||
response.data instanceof ArrayBuffer
|
||||
) {
|
||||
return response;
|
||||
}
|
||||
|
||||
if (response.data && typeof response.data === "object" && "data" in response.data) {
|
||||
response.data = (response.data as ApiSuccessResponse<unknown>)?.data;
|
||||
}
|
||||
return response;
|
||||
},
|
||||
async (error: AxiosError<ApiErrorResponse>) => {
|
||||
@@ -102,11 +111,6 @@ apiClient.interceptors.response.use(
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Backend'in standart hata mesajını çıkarır.
|
||||
* QueryCache.onError / MutationCache.onError içinde toast.error() için kullanılacak.
|
||||
*/
|
||||
export function extractErrorMessage(error: unknown, fallback = "Bir hata oluştu"): string {
|
||||
if (axios.isAxiosError<ApiErrorResponse>(error)) {
|
||||
return error.response?.data?.message || fallback;
|
||||
|
||||
@@ -1,108 +1,91 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Download, Database, CheckCircle2, XCircle, Clock } from "lucide-react";
|
||||
import { Download, Database, CheckCircle2, XCircle, Clock, AlertCircle } from "lucide-react";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ColumnMeta } from "@/components/dataTableToolbar";
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import type { VisibilityState } from "@tanstack/react-table";
|
||||
import { useBackups, useCreateBackup, useDeleteBackup, useDownloadBackup } from "@/features/backups/hooks/useBackups";
|
||||
import type { Backup, BackupStatus } from "@/features/backups/api/backupsApi";
|
||||
|
||||
const PER_PAGE = 25;
|
||||
// ─── Status Badge ─────────────────────────────────────────────────────────────
|
||||
|
||||
function BackupStatusBadge({ status }: { status: BackupStatus }) {
|
||||
const STATUS_CONFIG: Record<BackupStatus, { labelKey: string; fallback: string; variant: StatusBadgeVariant; icon: React.ElementType }> = {
|
||||
pending: { labelKey: "backups.status.pending", fallback: "Garaşylýar", variant: "warning", icon: AlertCircle },
|
||||
in_progress: { labelKey: "backups.status.inProgress", fallback: "Dowam edýär", variant: "warning", icon: Clock },
|
||||
completed: { labelKey: "backups.status.completed", fallback: "Tamamlandy", variant: "success", icon: CheckCircle2 },
|
||||
failed: { labelKey: "backups.status.failed", fallback: "Şowsuz", variant: "error", icon: XCircle },
|
||||
};
|
||||
|
||||
function BackupStatusBadge({ status }: { status: string }) {
|
||||
const { t } = useTranslation();
|
||||
const cfg: Record<BackupStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }> = {
|
||||
completed: { label: t("backups.status.completed", "Tamamlandy"), variant: "success", icon: CheckCircle2 },
|
||||
failed: { label: t("backups.status.failed", "Şowsuz"), variant: "error", icon: XCircle },
|
||||
in_progress: { label: t("backups.status.inProgress", "Dowam edýär"), variant: "warning", icon: Clock },
|
||||
};
|
||||
const currentCfg = cfg[status];
|
||||
return <StatusBadge label={currentCfg.label} variant={currentCfg.variant} icon={currentCfg.icon} />;
|
||||
const cfg = STATUS_CONFIG[status as BackupStatus];
|
||||
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} />;
|
||||
}
|
||||
|
||||
// ─── Column meta for toggle dropdown ─────────────────────────────────────────
|
||||
|
||||
const COLUMN_IDS = ["id", "fileName", "size", "status", "createdBy", "createdAt"] as const;
|
||||
|
||||
export default function BackupsPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(PER_PAGE);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [search, setSearch] = useState("");
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([...COLUMN_IDS]);
|
||||
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([{ fieldId: "status", value: "" }]);
|
||||
|
||||
const { data, isLoading } = useBackups({ page, per_page: perPage, search });
|
||||
const createBackup = useCreateBackup();
|
||||
const downloadBackup = useDownloadBackup();
|
||||
const deleteBackup = useDeleteBackup();
|
||||
|
||||
const columns: ColumnDef<Backup>[] = [
|
||||
{
|
||||
id: "fileName",
|
||||
accessorKey: "fileName",
|
||||
header: t("backups.col.fileName", "Faýl ady"),
|
||||
cell: ({ row }) => <span className="font-mono text-sm">{row.original.fileName}</span>,
|
||||
},
|
||||
{
|
||||
id: "fileSize",
|
||||
accessorKey: "fileSize",
|
||||
header: t("backups.col.fileSize", "Ölçegi"),
|
||||
cell: ({ row }) => <span>{row.original.fileSize}</span>,
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("backups.col.status", "Status"),
|
||||
cell: ({ row }) => <BackupStatusBadge status={row.original.status} />,
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: t("backups.col.createdAt", "Döredilen wagty"),
|
||||
cell: ({ row }) => <span className="text-sm text-muted-foreground">{row.original.createdAt}</span>,
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
id: "createdBy",
|
||||
accessorKey: "createdBy",
|
||||
header: t("backups.col.createdBy", "Döreden"),
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
extraActions={[
|
||||
{
|
||||
icon: Download,
|
||||
title: t("common.download", "Ýükle"),
|
||||
onClick: () => downloadBackup.mutate(row.original.id),
|
||||
disabled: row.original.status === "in_progress",
|
||||
},
|
||||
]}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
// ── Query params & data ─────────────────────────────────────────────────────
|
||||
|
||||
const columnMeta: ColumnMeta[] = columns
|
||||
.filter((c) => c.id !== "actions")
|
||||
.map((c) => ({
|
||||
id: c.id!,
|
||||
label: typeof c.header === "string" ? c.header : c.id!,
|
||||
}));
|
||||
const queryParams = useMemo(() => {
|
||||
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
|
||||
return {
|
||||
page,
|
||||
limit: perPage,
|
||||
search: search || undefined,
|
||||
status: filterMap.status || undefined,
|
||||
};
|
||||
}, [search, activeFilters, page, perPage]);
|
||||
|
||||
const total = data?.total ?? 0;
|
||||
const totalPages = Math.ceil(total / perPage);
|
||||
const { data, isLoading } = useBackups(queryParams);
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
||||
|
||||
const statusOptions = useMemo(
|
||||
() => [
|
||||
{ value: "pending", label: t("backups.status.pending", "Garaşylýar") },
|
||||
{ value: "in_progress", label: t("backups.status.inProgress", "Dowam edýär") },
|
||||
{ value: "completed", label: t("backups.status.completed", "Tamamlandy") },
|
||||
{ value: "failed", label: t("backups.status.failed", "Şowsuz") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setActiveFilters((prev) => prev.map((f) => ({ ...f, value: "" })));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (deleteId === null) return;
|
||||
@@ -110,14 +93,109 @@ export default function BackupsPage() {
|
||||
setDeleteId(null);
|
||||
};
|
||||
|
||||
// ── Columns ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const columns = useMemo<ColumnDef<Backup>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<button
|
||||
className="text-primary font-medium hover:underline text-left cursor-pointer"
|
||||
onClick={() => navigate(`/backups/${row.original.id}`)}
|
||||
>
|
||||
{row.original.id}
|
||||
</button>
|
||||
),
|
||||
size: 70,
|
||||
},
|
||||
{
|
||||
id: "fileName",
|
||||
accessorKey: "fileName",
|
||||
header: t("backups.col.fileName", "Faýl ady"),
|
||||
cell: ({ row }) => <span className="font-mono text-sm">{row.original.fileName}</span>,
|
||||
},
|
||||
{
|
||||
id: "size",
|
||||
accessorKey: "size",
|
||||
header: t("backups.col.fileSize", "Ölçegi"),
|
||||
cell: ({ row }) => <span>{row.original.size}</span>,
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("backups.col.status", "Status"),
|
||||
cell: ({ row }) => <BackupStatusBadge status={row.original.status} />,
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
id: "createdBy",
|
||||
accessorKey: "createdBy",
|
||||
header: t("backups.col.createdBy", "Döreden"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground">{row.original.createdBy?.name || row.original.createdBy?.username || "—"}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: t("backups.col.createdAt", "Döredilen wagty"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground whitespace-nowrap">{new Date(row.original.createdAt).toLocaleString()}</span>
|
||||
),
|
||||
size: 180,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
extraActions={[
|
||||
{
|
||||
icon: Download,
|
||||
title: t("common.download", "Ýükle"),
|
||||
onClick: () => downloadBackup.mutate({ id: row.original.id, fileName: row.original.fileName }),
|
||||
disabled: row.original.status === "in_progress",
|
||||
},
|
||||
]}
|
||||
onView={() => navigate(`/backups/${row.original.id}`)}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
isDeleting={deleteBackup.isPending}
|
||||
/>
|
||||
),
|
||||
size: 130,
|
||||
},
|
||||
],
|
||||
[t, navigate, downloadBackup, deleteBackup.isPending],
|
||||
);
|
||||
|
||||
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`backups.columns.${id}`, id) })), [t]);
|
||||
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "status",
|
||||
label: t("backups.col.status", "STATUS"),
|
||||
options: statusOptions,
|
||||
},
|
||||
],
|
||||
[t, statusOptions],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground flex items-center gap-2">
|
||||
<Database className="size-5 text-muted-foreground" />
|
||||
{t("backups.title", "Bekaplar")}
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 justify-between">
|
||||
<TableSearchInput
|
||||
value={search}
|
||||
@@ -135,30 +213,34 @@ export default function BackupsPage() {
|
||||
|
||||
<div className="bg-card border border-border rounded-xl p-4">
|
||||
<DataTableToolbar
|
||||
hideSearch
|
||||
hideAction
|
||||
searchValue={search}
|
||||
onSearchChange={(v) => {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={columnMeta}
|
||||
columns={toggleableColumns}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
filterFields={filterFields}
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
perPageOptions={[10, 25, 50, 100]}
|
||||
perPage={perPage}
|
||||
onPerPageChange={(v) => {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
hideSearch
|
||||
hideAction
|
||||
/>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.backups ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
|
||||
142
src/pages/backupsView/index.tsx
Normal file
142
src/pages/backupsView/index.tsx
Normal file
@@ -0,0 +1,142 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Download, Trash2, Database, CheckCircle2, XCircle, Clock, AlertCircle } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { useBackup, useDeleteBackup, useDownloadBackup } from "@/features/backups/hooks/useBackups";
|
||||
import { InfoRow } from "@/components/viewPageComponents";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import type { BackupStatus } from "@/features/backups/api/backupsApi";
|
||||
|
||||
// ─── Status Badge ─────────────────────────────────────────────────────────────
|
||||
|
||||
const STATUS_CONFIG: Record<BackupStatus, { labelKey: string; fallback: string; variant: StatusBadgeVariant; icon: React.ElementType }> = {
|
||||
pending: { labelKey: "backups.status.pending", fallback: "Garaşylýar", variant: "warning", icon: AlertCircle },
|
||||
in_progress: { labelKey: "backups.status.inProgress", fallback: "Dowam edýär", variant: "warning", icon: Clock },
|
||||
completed: { labelKey: "backups.status.completed", fallback: "Tamamlandy", variant: "success", icon: CheckCircle2 },
|
||||
failed: { labelKey: "backups.status.failed", fallback: "Şowsuz", variant: "error", icon: XCircle },
|
||||
};
|
||||
|
||||
function BackupStatusBadge({ status }: { status: string }) {
|
||||
const { t } = useTranslation();
|
||||
const cfg = STATUS_CONFIG[status as BackupStatus];
|
||||
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} />;
|
||||
}
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export default function BackupViewPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
const numericId = Number(id);
|
||||
const { data, isLoading } = useBackup(numericId);
|
||||
const deleteMutation = useDeleteBackup();
|
||||
const downloadMutation = useDownloadBackup();
|
||||
|
||||
const handleDelete = async () => {
|
||||
await deleteMutation.mutateAsync(numericId);
|
||||
navigate("/backups");
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-7 w-64" />
|
||||
<div className="rounded-lg border border-border bg-card overflow-hidden">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<div key={i} className="grid grid-cols-[220px_1fr] items-center py-2.5 px-4 border-b border-border last:border-0">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-4 w-40" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return <div className="text-center py-24 text-muted-foreground">{t("Not found", "Tapylmady")}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground flex items-center gap-2">
|
||||
<Database className="size-5 text-muted-foreground" />
|
||||
{t("Backup detail", "Backup giňişleýin")}: #{data.id}
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => downloadMutation.mutate({ id: numericId, fileName: data.fileName })}
|
||||
disabled={downloadMutation.isPending || data.status === "in_progress"}
|
||||
>
|
||||
<Download size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-destructive border-destructive/30 hover:bg-destructive/10"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Detail card */}
|
||||
<div className="rounded-lg border border-border bg-card overflow-hidden">
|
||||
<InfoRow label={t("ID", "ID")} value={data.id} />
|
||||
<InfoRow label={t("backups.col.fileName", "Faýl ady")} value={data.fileName} />
|
||||
<InfoRow label={t("backups.col.fileSize", "Ölçegi")} value={`${data.size} (${data.sizeBytes} bytes)`} />
|
||||
<InfoRow label={t("backups.col.status", "Status")}>
|
||||
<BackupStatusBadge status={data.status} />
|
||||
</InfoRow>
|
||||
<InfoRow
|
||||
label={t("backups.col.createdBy", "Döreden")}
|
||||
value={data.createdBy?.name || data.createdBy?.username || undefined}
|
||||
isLink
|
||||
href={data.createdBy?.id != null ? `/all-users/${data.createdBy.id}` : undefined}
|
||||
/>
|
||||
<InfoRow label={t("backups.col.createdAt", "Döredilen wagty")} value={new Date(data.createdAt).toLocaleString()} />
|
||||
<InfoRow label={t("Updated at", "Täzelenen wagty")} value={new Date(data.updatedAt).toLocaleString()} />
|
||||
</div>
|
||||
|
||||
{/* Delete dialog */}
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t("Are you sure?", "Eminsiňizmi?")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t("backups.deleteConfirm.description", "Bu backup pozulsynmy? Bu amal yzyna gaýtarylmaz.")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t("Cancel", "Ýatyr")}</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
|
||||
{deleteMutation.isPending ? t("Deleting...", "Öçürilýär...") : t("Delete", "Öçür")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
@@ -8,12 +9,30 @@ import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/compone
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { useCardBalances, useDeleteCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
||||
import type { CardBalance } from "@/features/cardBalance/api/cardBalanceApi";
|
||||
import { CardBalanceStatusBadge } from "@/features/cardBalance/components/cardBalanceStatusBadge";
|
||||
import type { CardBalance, CardBalanceStatus } from "@/features/cardBalance/api/cardBalanceApi";
|
||||
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||
|
||||
// ─── Status Badge ─────────────────────────────────────────────────────────────
|
||||
|
||||
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 },
|
||||
};
|
||||
|
||||
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} />;
|
||||
}
|
||||
|
||||
// ─── Column meta for toggle dropdown ─────────────────────────────────────────
|
||||
|
||||
const COLUMN_IDS = ["id", "passportNumber", "cardLast4", "expiry", "balance", "status", "createdBy", "createdAt"] as const;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate, Link } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Trash2, Pencil } from "lucide-react";
|
||||
import { Trash2, Pencil, AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import {
|
||||
@@ -16,7 +16,26 @@ import {
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { useCardBalance, useDeleteCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
||||
import { InfoRow } from "@/components/viewPageComponents";
|
||||
import { CardBalanceStatusBadge } from "@/features/cardBalance/components/cardBalanceStatusBadge";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import type { CardBalanceStatus } from "@/features/cardBalance/api/cardBalanceApi";
|
||||
|
||||
// ─── Status Badge ─────────────────────────────────────────────────────────────
|
||||
|
||||
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 },
|
||||
};
|
||||
|
||||
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} />;
|
||||
}
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ import type { Card } from "@/features/cardTransactions/api/cardTransactionsApi";
|
||||
const PER_PAGE = 25;
|
||||
|
||||
export default function CardTransactionsPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
@@ -44,7 +44,7 @@ export default function CardTransactionsPage() {
|
||||
{row.original.id}
|
||||
</button>
|
||||
),
|
||||
size: 80,
|
||||
size: 70,
|
||||
},
|
||||
{
|
||||
id: "name",
|
||||
@@ -62,7 +62,14 @@ export default function CardTransactionsPage() {
|
||||
id: "type",
|
||||
accessorKey: "type",
|
||||
header: t("cardTransaction.col.type", "Görnüşi"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.type}</span>,
|
||||
cell: ({ row }) => {
|
||||
const ct = row.original.cardType;
|
||||
const val =
|
||||
typeof ct?.name === "object"
|
||||
? ct.name[i18n.language as "tm" | "ru" | "en"] || ct.name.tm || ct.name.en
|
||||
: ct?.name || row.original.type || "—";
|
||||
return <span className="text-sm text-foreground">{val}</span>;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "expiry",
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { useCardTransaction, useDeleteCardTransaction } from "@/features/cardTransactions/hooks/useCardTransactions";
|
||||
import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents";
|
||||
import i18n from "@/lib/i18n";
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -84,7 +85,14 @@ export default function CardTransactionViewPage() {
|
||||
<BentoCard title={t("cardTransaction.section.card", "Kart")}>
|
||||
<InfoRow label={t("cardTransaction.col.id", "ID")} value={data.id} />
|
||||
<InfoRow label={t("cardTransaction.col.name", "Ady")} value={data.name} />
|
||||
<InfoRow label={t("cardTransaction.col.type", "Görnüşi")} value={data.type} />
|
||||
<InfoRow
|
||||
label={t("cardTransaction.col.type", "Görnüşi")}
|
||||
value={
|
||||
typeof data.cardType?.name === "object"
|
||||
? data.cardType.name[i18n.language as "tm" | "ru" | "en"] || data.cardType.name.tm || data.cardType.name.en || "—"
|
||||
: data.cardType?.name || data.type || "—"
|
||||
}
|
||||
/>
|
||||
<InfoRow label={t("cardTransaction.col.number", "Kart belgisi")} value={data.number} />
|
||||
<InfoRow label={t("cardTransaction.col.expiry", "Möhleti")} value={`${data.month}/${data.year}`} />
|
||||
</BentoCard>
|
||||
|
||||
@@ -1,26 +1,20 @@
|
||||
// pages/CurrencyRatesPage.tsx
|
||||
|
||||
import { useState } from "react";
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
||||
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import { useGetCurrencyRates, useDeleteCurrencyRate } from "@/features/currencyRates/hooks/useCurrencyRates";
|
||||
import type { CurrencyRate } from "@/features/currencyRates/api/currencyRatesApi";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { useGetCurrencyRates, useDeleteCurrencyRate } from "@/features/currencyRates/hooks/useCurrencyRates";
|
||||
import { CURRENCY_OPTIONS, type CurrencyRate } from "@/features/currencyRates/api/currencyRatesApi";
|
||||
|
||||
// ─── Column visibility defaults ───────────────────────────────────────────────
|
||||
// ─── Column meta for toggle dropdown ─────────────────────────────────────────
|
||||
|
||||
const DEFAULT_VISIBILITY = {
|
||||
id: true,
|
||||
currencyFrom: true,
|
||||
currencyTo: true,
|
||||
value: true,
|
||||
};
|
||||
const DEFAULT_ORDER = ["id", "currencyFrom", "currencyTo", "value", "actions"];
|
||||
const COLUMN_IDS = ["id", "currencyFrom", "currencyTo", "value", "createdBy", "createdAt"] as const;
|
||||
|
||||
// ─── CurrencyRatesPage ────────────────────────────────────────────────────────
|
||||
|
||||
@@ -29,86 +23,154 @@ export default function CurrencyRatesPage() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage] = useState(25);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [search, setSearch] = useState("");
|
||||
const [columnVisibility, setColumnVisibility] = useState<Record<string, boolean>>(DEFAULT_VISIBILITY);
|
||||
const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([...COLUMN_IDS]);
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
|
||||
const { data, isLoading } = useGetCurrencyRates({ page, perPage, search });
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
{ fieldId: "currency_from", value: "" },
|
||||
{ fieldId: "currency_to", value: "" },
|
||||
]);
|
||||
|
||||
const deleteMutation = useDeleteCurrencyRate();
|
||||
|
||||
// ── Query params & data ─────────────────────────────────────────────────────
|
||||
|
||||
const queryParams = useMemo(() => {
|
||||
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
|
||||
return {
|
||||
page,
|
||||
limit: perPage,
|
||||
search: search || undefined,
|
||||
currency_from: filterMap.currency_from || undefined,
|
||||
currency_to: filterMap.currency_to || undefined,
|
||||
};
|
||||
}, [search, activeFilters, page, perPage]);
|
||||
|
||||
const { data, isLoading } = useGetCurrencyRates(queryParams);
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
||||
|
||||
const currencyOptions = useMemo(() => CURRENCY_OPTIONS.map((c) => ({ value: c.value, label: c.value })), []);
|
||||
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setActiveFilters((prev) => prev.map((f) => ({ ...f, value: "" })));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleSearchChange = useCallback((val: string) => {
|
||||
setSearch(val);
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (deleteId === null) return;
|
||||
await deleteMutation.mutateAsync(deleteId);
|
||||
setDeleteId(null);
|
||||
};
|
||||
|
||||
const handleSearchChange = (val: string) => {
|
||||
setSearch(val);
|
||||
setPage(1);
|
||||
};
|
||||
// ── Columns ─────────────────────────────────────────────────────────────────
|
||||
|
||||
// ─── Columns ──────────────────────────────────────────────────────────────
|
||||
const columns = useMemo<ColumnDef<CurrencyRate>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<button
|
||||
className="text-primary font-medium hover:underline text-left cursor-pointer"
|
||||
onClick={() => navigate(`/currency-rates/${row.original.id}`)}
|
||||
>
|
||||
{row.original.id}
|
||||
</button>
|
||||
),
|
||||
size: 70,
|
||||
},
|
||||
{
|
||||
id: "currencyFrom",
|
||||
accessorKey: "currencyFrom",
|
||||
header: t("currencyRates.columns.currencyFrom", "CURRENCY FROM"),
|
||||
cell: ({ row }) => <span className="font-medium text-foreground">{row.original.currencyFrom}</span>,
|
||||
},
|
||||
{
|
||||
id: "currencyTo",
|
||||
accessorKey: "currencyTo",
|
||||
header: t("currencyRates.columns.currencyTo", "CURRENCY TO"),
|
||||
cell: ({ row }) => <span className="font-medium text-foreground">{row.original.currencyTo}</span>,
|
||||
},
|
||||
{
|
||||
id: "value",
|
||||
accessorKey: "value",
|
||||
header: t("currencyRates.columns.value", "VALUE"),
|
||||
cell: ({ row }) => <span className="text-foreground tabular-nums">{row.original.value}</span>,
|
||||
},
|
||||
{
|
||||
id: "createdBy",
|
||||
accessorKey: "createdBy",
|
||||
header: t("Created by", "DÖREDEN"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground">{row.original.createdBy?.name || row.original.createdBy?.username || "—"}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: t("Created at", "DÖREDILEN WAGTY"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground whitespace-nowrap">{new Date(row.original.createdAt).toLocaleString()}</span>
|
||||
),
|
||||
size: 180,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
onView={() => navigate(`/currency-rates/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/currency-rates/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
],
|
||||
[t, navigate, deleteMutation.isPending],
|
||||
);
|
||||
|
||||
const columns: ColumnDef<CurrencyRate>[] = [
|
||||
{
|
||||
accessorKey: "id",
|
||||
header: "ID",
|
||||
cell: ({ row }) => (
|
||||
<button
|
||||
className="text-primary font-semibold hover:underline"
|
||||
onClick={() => navigate(`/resources/currency-rates/${row.original.id}`)}
|
||||
>
|
||||
{row.original.id}
|
||||
</button>
|
||||
),
|
||||
size: 80,
|
||||
},
|
||||
{
|
||||
accessorKey: "currencyFrom",
|
||||
header: t("currencyRates.columns.currencyFrom", "CURRENCY FROM"),
|
||||
cell: ({ row }) => <span className="font-medium text-foreground">{row.original.currencyFrom}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "currencyTo",
|
||||
header: t("currencyRates.columns.currencyTo", "CURRENCY TO"),
|
||||
cell: ({ row }) => <span className="font-medium text-foreground">{row.original.currencyTo}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "value",
|
||||
header: t("currencyRates.columns.value", "VALUE"),
|
||||
cell: ({ row }) => <span className="text-foreground tabular-nums">{row.original.value}</span>,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
onView={() => navigate(`/currency-rates/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/currency-rates/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
),
|
||||
size: 120,
|
||||
},
|
||||
];
|
||||
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`currencyRates.columns.${id}`, id) })), [t]);
|
||||
|
||||
const columnMeta = columns
|
||||
.filter((c) => "accessorKey" in c && c.accessorKey)
|
||||
.map((c) => ({
|
||||
id: String(("accessorKey" in c ? c.accessorKey : c.id) ?? ""),
|
||||
label: typeof c.header === "string" ? c.header : String(("accessorKey" in c ? c.accessorKey : "") ?? ""),
|
||||
}));
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "currency_from",
|
||||
label: t("currencyRates.fields.currencyFrom", "CURRENCY FROM"),
|
||||
options: currencyOptions,
|
||||
},
|
||||
{
|
||||
id: "currency_to",
|
||||
label: t("currencyRates.fields.currencyTo", "CURRENCY TO"),
|
||||
options: currencyOptions,
|
||||
},
|
||||
],
|
||||
[t, currencyOptions],
|
||||
);
|
||||
|
||||
// ─── Render ───────────────────────────────────────────────────────────────
|
||||
// ─── Render ─────────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-2xl font-semibold text-foreground mb-5">{t("currencyRates.title", "Walýuta kursy")}</h1>
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("currencyRates.title", "Walýuta kurslary")}</h1>
|
||||
|
||||
<div className="flex items-center gap-3 justify-between">
|
||||
<TableSearchInput value={search} onChange={handleSearchChange} placeholder={t("common.search", "Gözlemek")} />
|
||||
<CreateButton
|
||||
@@ -116,23 +178,34 @@ export default function CurrencyRatesPage() {
|
||||
onClick={() => navigate("/currency-rates/create")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-xl p-4">
|
||||
<DataTableToolbar
|
||||
hideSearch
|
||||
hideAction
|
||||
searchValue={search}
|
||||
onSearchChange={handleSearchChange}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={columnMeta}
|
||||
columns={toggleableColumns}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
hideSearch
|
||||
hideAction
|
||||
filterFields={filterFields}
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
perPageOptions={[10, 25, 50, 100]}
|
||||
perPage={perPage}
|
||||
onPerPageChange={(v) => {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.currencies ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
@@ -141,8 +214,8 @@ export default function CurrencyRatesPage() {
|
||||
enableRowSelection
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={data?.totalPages ?? 1}
|
||||
totalCount={data?.total ?? 0}
|
||||
totalPages={totalPages}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
// pages/CurrencyRateDetailPage.tsx
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Pencil, Trash2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Section, InfoRow } from '@/components/viewPageComponents'
|
||||
import { useGetCurrencyRateById, useDeleteCurrencyRate } from '@/features/currencyRates/hooks/useCurrencyRates'
|
||||
import { ConfirmDialog } from '@/components/confirmDialog'
|
||||
import { useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Pencil, Trash2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Section, InfoRow } from "@/components/viewPageComponents";
|
||||
import { useGetCurrencyRateById, useDeleteCurrencyRate } from "@/features/currencyRates/hooks/useCurrencyRates";
|
||||
import { ConfirmDialog } from "@/components/confirmDialog";
|
||||
|
||||
// ─── CurrencyRateDetailPage ───────────────────────────────────────────────────
|
||||
|
||||
export default function CurrencyRateDetailPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const numericId = Number(id)
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const numericId = Number(id);
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [deleteOpen, setDeleteOpen] = useState(false)
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
const { data: rate, isLoading } = useGetCurrencyRateById(numericId)
|
||||
const deleteMutation = useDeleteCurrencyRate()
|
||||
const { data: rate, isLoading } = useGetCurrencyRateById(numericId);
|
||||
const deleteMutation = useDeleteCurrencyRate();
|
||||
|
||||
const handleDeleteConfirm = async () => {
|
||||
await deleteMutation.mutateAsync(numericId)
|
||||
navigate('/resources/currency-rates')
|
||||
}
|
||||
await deleteMutation.mutateAsync(numericId);
|
||||
navigate("/currency-rates");
|
||||
};
|
||||
|
||||
// ─── Loading skeleton ──────────────────────────────────────────────────────
|
||||
|
||||
@@ -36,29 +36,25 @@ export default function CurrencyRateDetailPage() {
|
||||
<Skeleton className="h-6 w-64" />
|
||||
<Skeleton className="h-48 rounded-xl" />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!rate) {
|
||||
return (
|
||||
<div>
|
||||
<p className="text-muted-foreground">
|
||||
{t('currencyRates.notFound', 'Walýuta kursy tapylmady')}
|
||||
</p>
|
||||
<p className="text-muted-foreground">{t("currencyRates.notFound", "Walýuta kursy tapylmady")}</p>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Render ───────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div >
|
||||
|
||||
|
||||
<div>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-semibold text-foreground">
|
||||
{t('currencyRates.detail.title', 'Walýuta kursy giňişleýin')}: {rate.id}
|
||||
{t("currencyRates.detail.title", "Walýuta kursy giňişleýin")}: {rate.id}
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
@@ -66,7 +62,7 @@ export default function CurrencyRateDetailPage() {
|
||||
size="icon"
|
||||
className="text-muted-foreground hover:text-destructive"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
title={t('common.delete', 'Pozmak')}
|
||||
title={t("common.delete", "Pozmak")}
|
||||
>
|
||||
<Trash2 size={18} />
|
||||
</Button>
|
||||
@@ -74,8 +70,8 @@ export default function CurrencyRateDetailPage() {
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
onClick={() => navigate(`/resources/currency-rates/${rate.id}/edit`)}
|
||||
title={t('common.edit', 'Üýtgetmek')}
|
||||
onClick={() => navigate(`/currency-rates/${rate.id}/edit`)}
|
||||
title={t("common.edit", "Üýtgetmek")}
|
||||
>
|
||||
<Pencil size={18} />
|
||||
</Button>
|
||||
@@ -84,27 +80,35 @@ export default function CurrencyRateDetailPage() {
|
||||
|
||||
{/* Detail Card */}
|
||||
<Section>
|
||||
<InfoRow label={t('common.id', 'ID')} value={rate.id} />
|
||||
<InfoRow label={t('currencyRates.fields.currencyFrom', 'Currency from')} value={rate.currencyFrom} />
|
||||
<InfoRow label={t('currencyRates.fields.currencyTo', 'Currency to')} value={rate.currencyTo} />
|
||||
<InfoRow label={t('currencyRates.fields.value', 'Value')} value={rate.value} />
|
||||
<InfoRow label={t('common.createdAt', 'Döredilen senesi')}
|
||||
value={new Date(rate.createdAt).toLocaleString()}
|
||||
<InfoRow label={t("common.id", "ID")} value={rate.id} />
|
||||
<InfoRow label={t("currencyRates.fields.currencyFrom", "Currency from")} value={rate.currencyFrom} />
|
||||
<InfoRow label={t("currencyRates.fields.currencyTo", "Currency to")} value={rate.currencyTo} />
|
||||
<InfoRow label={t("currencyRates.fields.value", "Value")} value={rate.value} />
|
||||
<InfoRow
|
||||
label={t("currencyRates.fields.createdBy", "Döreden")}
|
||||
value={rate.createdBy?.name || rate.createdBy?.username || undefined}
|
||||
isLink
|
||||
href={rate.createdBy?.id != null ? `/all-users/${rate.createdBy.id}` : undefined}
|
||||
/>
|
||||
<InfoRow label={t('common.updatedAt', 'Üýtgedilen senesi')}
|
||||
value={new Date(rate.updatedAt).toLocaleString()}
|
||||
<InfoRow
|
||||
label={t("currencyRates.fields.updatedBy", "Üýtgeden")}
|
||||
value={rate.updatedBy?.name || rate.updatedBy?.username || undefined}
|
||||
isLink
|
||||
href={rate.updatedBy?.id != null ? `/all-users/${rate.updatedBy.id}` : undefined}
|
||||
/>
|
||||
<InfoRow label={t("common.createdAt", "Döredilen senesi")} value={new Date(rate.createdAt).toLocaleString()} />
|
||||
<InfoRow label={t("common.updatedAt", "Üýtgedilen senesi")} value={new Date(rate.updatedAt).toLocaleString()} />
|
||||
</Section>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleteOpen}
|
||||
onOpenChange={setDeleteOpen}
|
||||
title={t('currencyRates.deleteDialog.title', 'Pozmak isleýärsiňizmi?')}
|
||||
description={t('currencyRates.deleteDialog.description', 'Bu amal yzyna gaýtarylyp bilinmez. Walýuta kursy hemişelik pozular.')}
|
||||
confirmLabel={deleteMutation.isPending ? t('common.deleting', 'Pozulýar...') : t('common.delete', 'Pozmak')}
|
||||
title={t("currencyRates.deleteDialog.title", "Pozmak isleýärsiňizmi?")}
|
||||
description={t("currencyRates.deleteDialog.description", "Bu amal yzyna gaýtarylyp bilinmez. Walýuta kursy hemişelik pozular.")}
|
||||
confirmLabel={deleteMutation.isPending ? t("common.deleting", "Pozulýar...") : t("common.delete", "Pozmak")}
|
||||
onConfirm={handleDeleteConfirm}
|
||||
isLoading={deleteMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user