320 lines
12 KiB
TypeScript
320 lines
12 KiB
TypeScript
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";
|
|
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 { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
|
import { DeleteDialog } from "@/components/deleteDialog";
|
|
import { useCardBalances, useDeleteCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
|
import type { CardBalance, CardBalanceStatus } from "@/features/cardBalance/api/cardBalanceApi";
|
|
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
|
import { formatFromApiDate } from "@/lib/utils";
|
|
// ─── 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;
|
|
|
|
export default function CardBalancesPage() {
|
|
const { t } = useTranslation();
|
|
const navigate = useNavigate();
|
|
const deleteMutation = useDeleteCardBalance();
|
|
const [deleteId, setDeleteId] = useState<number | null>(null);
|
|
|
|
const [page, setPage] = useState(1);
|
|
const [perPage, setPerPage] = useState(25);
|
|
const [search, setSearch] = useState("");
|
|
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
|
const [columnOrder, setColumnOrder] = useState<string[]>([...COLUMN_IDS]);
|
|
|
|
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
|
{ fieldId: "status", value: "" },
|
|
{ fieldId: "created_by", value: "" },
|
|
]);
|
|
|
|
// ── Infinite user dropdown for created_by filter ────────────────────────────
|
|
|
|
const [userSearch, setUserSearch] = useState("");
|
|
const {
|
|
data: usersInfiniteData,
|
|
fetchNextPage: fetchNextUsers,
|
|
hasNextPage: hasNextUsers,
|
|
isFetchingNextPage: isFetchingNextUsers,
|
|
isLoading: isUsersLoading,
|
|
} = useInfiniteUsers(userSearch);
|
|
|
|
const userOptions = useMemo(
|
|
() =>
|
|
(usersInfiniteData?.pages ?? []).flatMap((page) =>
|
|
(page?.users ?? []).map((u) => ({
|
|
value: String(u.id),
|
|
label: u.name || u.username || String(u.id),
|
|
})),
|
|
),
|
|
[usersInfiniteData],
|
|
);
|
|
|
|
// ── Query params & data ─────────────────────────────────────────────────────
|
|
|
|
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,
|
|
created_by: filterMap.created_by ? Number(filterMap.created_by) : undefined,
|
|
};
|
|
}, [search, activeFilters, page, perPage]);
|
|
|
|
const { data, isLoading } = useCardBalances(queryParams);
|
|
const total = data?.count ?? 0;
|
|
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
|
|
|
const statusOptions = useMemo(
|
|
() => [
|
|
{ value: "pending", label: t("cardBalance.status.pending", "Garaşylýar") },
|
|
{ value: "approved", label: t("cardBalance.status.approved", "Tassyklanan") },
|
|
{ value: "rejected", label: t("cardBalance.status.rejected", "Ret edilen") },
|
|
],
|
|
[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 = useCallback((id: number) => {
|
|
setDeleteId(id);
|
|
}, []);
|
|
|
|
const confirmDelete = useCallback(() => {
|
|
if (deleteId === null) return;
|
|
deleteMutation.mutate(deleteId);
|
|
setDeleteId(null);
|
|
}, [deleteId, deleteMutation]);
|
|
|
|
// ── Columns ─────────────────────────────────────────────────────────────────
|
|
|
|
const columns = useMemo<ColumnDef<CardBalance>[]>(
|
|
() => [
|
|
{
|
|
id: "id",
|
|
accessorKey: "id",
|
|
header: t("ID", "ID"),
|
|
cell: ({ row }) => (
|
|
<button
|
|
className="text-primary font-medium hover:underline text-left cursor-pointer"
|
|
onClick={() => navigate(`/card-balances/${row.original.id}`)}
|
|
>
|
|
{row.original.id}
|
|
</button>
|
|
),
|
|
size: 70,
|
|
},
|
|
{
|
|
id: "passportNumber",
|
|
accessorKey: "passportNumber",
|
|
header: t("Passport number", "PASPORT BELGISI"),
|
|
cell: ({ row }) => <span className="text-foreground">{row.original.passportNumber}</span>,
|
|
},
|
|
{
|
|
id: "cardLast4",
|
|
accessorKey: "cardLast4",
|
|
header: t("Card last 4", "KART BELGISI (SOŇKY 4)"),
|
|
cell: ({ row }) => <span className="font-mono">•••• •••• •••• {row.original.cardLast4}</span>,
|
|
},
|
|
{
|
|
id: "expiry",
|
|
accessorKey: "expiryMonth",
|
|
header: t("Expiry", "KART MÖHLETI"),
|
|
cell: ({ row }) => (
|
|
<span className="text-foreground whitespace-nowrap">
|
|
{String(row.original.expiryMonth).padStart(2, "0")}/{row.original.expiryYear}
|
|
</span>
|
|
),
|
|
},
|
|
{
|
|
id: "balance",
|
|
accessorKey: "balanceAmount",
|
|
header: t("Balance", "GALYNDY"),
|
|
cell: ({ row }) => (
|
|
<span className="text-foreground font-medium whitespace-nowrap">
|
|
{row.original.balanceAmount} {row.original.balanceCurrency}
|
|
</span>
|
|
),
|
|
},
|
|
{
|
|
id: "status",
|
|
accessorKey: "status",
|
|
header: t("Status", "STATUS"),
|
|
cell: ({ row }) => <CardBalanceStatusBadge status={row.original.status} />,
|
|
size: 140,
|
|
},
|
|
{
|
|
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-muted-foreground text-sm whitespace-nowrap">{formatFromApiDate(row.original.createdAt)}</span>
|
|
),
|
|
size: 180,
|
|
},
|
|
{
|
|
id: "actions",
|
|
header: "",
|
|
enableHiding: false,
|
|
cell: ({ row }) => (
|
|
<TableActions
|
|
onView={() => navigate(`/card-balances/${row.original.id}`)}
|
|
onEdit={() => navigate(`/card-balances/${row.original.id}/edit`)}
|
|
onDelete={() => handleDelete(row.original.id)}
|
|
isDeleting={deleteMutation.isPending}
|
|
/>
|
|
),
|
|
size: 100,
|
|
},
|
|
],
|
|
[t, navigate, handleDelete, deleteMutation.isPending],
|
|
);
|
|
|
|
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`cardBalance.columns.${id}`, id) })), [t]);
|
|
|
|
const filterFields = useMemo<FilterField[]>(
|
|
() => [
|
|
{
|
|
id: "status",
|
|
label: t("Status", "STATUS"),
|
|
options: statusOptions,
|
|
},
|
|
{
|
|
id: "created_by",
|
|
label: t("Created by", "DÖREDEN"),
|
|
type: "infinite-select",
|
|
options: userOptions,
|
|
loading: isUsersLoading,
|
|
isLoadingMore: isFetchingNextUsers,
|
|
hasNextPage: hasNextUsers,
|
|
onLoadMore: fetchNextUsers,
|
|
searchValue: userSearch,
|
|
onSearchChange: setUserSearch,
|
|
},
|
|
],
|
|
[t, statusOptions, userOptions, isUsersLoading, isFetchingNextUsers, hasNextUsers, userSearch],
|
|
);
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
{/* Header */}
|
|
<div className="flex items-center justify-between">
|
|
<h1 className="text-xl font-semibold text-foreground">{t("cardBalance.title", "Kart galyndylary")}</h1>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-3 justify-between">
|
|
<TableSearchInput
|
|
value={search}
|
|
onChange={(v) => {
|
|
setSearch(v);
|
|
setPage(1);
|
|
}}
|
|
placeholder={t("cardBalance.searchPlaceholder", "Pasport belgisi boýunça gözle")}
|
|
/>
|
|
<CreateButton label={t("Create card balance", "Kart galyndysy dörediň")} onClick={() => navigate("/card-balances/create")} />
|
|
</div>
|
|
|
|
<div className="bg-card border border-border rounded-xl p-4">
|
|
<DataTableToolbar
|
|
hideSearch
|
|
hideAction
|
|
searchValue={search}
|
|
onSearchChange={(v) => {
|
|
setSearch(v);
|
|
setPage(1);
|
|
}}
|
|
searchPlaceholder={t("cardBalance.searchPlaceholder", "Pasport belgisi boýunça gözle")}
|
|
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);
|
|
}}
|
|
/>
|
|
|
|
{/* Table */}
|
|
<DataTable
|
|
columns={columns}
|
|
data={data?.cardBalances ?? []}
|
|
isLoading={isLoading}
|
|
columnVisibility={columnVisibility}
|
|
onColumnVisibilityChange={setColumnVisibility}
|
|
columnOrder={columnOrder}
|
|
onColumnOrderChange={setColumnOrder}
|
|
enableRowSelection
|
|
getRowId={(row) => String(row.id)}
|
|
currentPage={page}
|
|
totalPages={totalPages}
|
|
totalCount={total}
|
|
onPageChange={setPage}
|
|
/>
|
|
</div>
|
|
|
|
{/* Delete dialog */}
|
|
<DeleteDialog
|
|
open={deleteId !== null}
|
|
onOpenChange={(o) => {
|
|
if (!o) setDeleteId(null);
|
|
}}
|
|
title={t("cardBalance.deleteConfirm", "Bu ýazgy pozulsynmy?")}
|
|
description={t("cardBalance.deleteDescription", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")}
|
|
onConfirm={confirmDelete}
|
|
isLoading={deleteMutation.isPending}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|