424 lines
15 KiB
TypeScript
424 lines
15 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 { useCardRequisites, useDeleteCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites";
|
|
import type { CardRequisite, CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi";
|
|
import { resolveLocalizedName } from "@/features/cardRequisites/api/cardRequisitesApi";
|
|
import { useInfiniteBranches } from "@/features/branches/hooks/useBranches";
|
|
import { useInfiniteCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
|
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
|
import { getRegionOptions } from "@/constants";
|
|
|
|
// ─── Status Badge ─────────────────────────────────────────────────────────────
|
|
|
|
const STATUS_CONFIG: Record<
|
|
CardRequisiteStatus,
|
|
{ labelKey: string; fallback: string; variant: StatusBadgeVariant; icon: React.ElementType }
|
|
> = {
|
|
pending: { labelKey: "cardRequisites.status.pending", fallback: "Garaşylýar", variant: "warning", icon: AlertCircle },
|
|
approved: { labelKey: "cardRequisites.status.approved", fallback: "Tassyklanan", variant: "success", icon: CheckCircle2 },
|
|
rejected: { labelKey: "cardRequisites.status.rejected", fallback: "Ret edilen", variant: "error", icon: XCircle },
|
|
};
|
|
|
|
function CardRequisiteStatusBadge({ status }: { status: string }) {
|
|
const { t } = useTranslation();
|
|
const cfg = STATUS_CONFIG[status as CardRequisiteStatus];
|
|
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", "uniqueId", "cardType", "customer", "user", "region", "branch", "status"] as const;
|
|
|
|
// ─── Filter constants ─────────────────────────────────────────────────────────
|
|
|
|
export default function CardRequisitesPage() {
|
|
const { t, i18n } = useTranslation();
|
|
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
|
const navigate = useNavigate();
|
|
const deleteMutation = useDeleteCardRequisite();
|
|
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: "region", value: "" },
|
|
{ fieldId: "branch_id", value: "" },
|
|
{ fieldId: "card_type_id", value: "" },
|
|
{ fieldId: "user_id", value: "" },
|
|
]);
|
|
|
|
// ── Infinite dropdown hooks ─────────────────────────────────────────────────
|
|
|
|
const [branchSearch, setBranchSearch] = useState("");
|
|
const {
|
|
data: branchesInfiniteData,
|
|
fetchNextPage: fetchNextBranches,
|
|
hasNextPage: hasNextBranches,
|
|
isFetchingNextPage: isFetchingNextBranches,
|
|
isLoading: isBranchesLoading,
|
|
} = useInfiniteBranches(branchSearch);
|
|
|
|
const branchOptions = useMemo(
|
|
() =>
|
|
(branchesInfiniteData?.pages ?? []).flatMap((page) =>
|
|
(page?.branches ?? []).map((b) => ({
|
|
value: String(b.id),
|
|
label: b.name[lang] || b.name.tm || String(b.id),
|
|
})),
|
|
),
|
|
[branchesInfiniteData, lang],
|
|
);
|
|
|
|
const [cardTypeSearch, setCardTypeSearch] = useState("");
|
|
const {
|
|
data: cardTypesInfiniteData,
|
|
fetchNextPage: fetchNextCardTypes,
|
|
hasNextPage: hasNextCardTypes,
|
|
isFetchingNextPage: isFetchingNextCardTypes,
|
|
isLoading: isCardTypesLoading,
|
|
} = useInfiniteCardTypes(cardTypeSearch);
|
|
|
|
const cardTypeOptions = useMemo(
|
|
() =>
|
|
(cardTypesInfiniteData?.pages ?? []).flatMap((page) =>
|
|
(page?.paymentCards ?? []).map((ct) => ({
|
|
value: String(ct.id),
|
|
label: ct.title[lang] || ct.title.tm || String(ct.id),
|
|
})),
|
|
),
|
|
[cardTypesInfiniteData, lang],
|
|
);
|
|
|
|
const [userSearch, setUserSearch] = useState("");
|
|
const {
|
|
data: clientsInfiniteData,
|
|
fetchNextPage: fetchNextClients,
|
|
hasNextPage: hasNextClients,
|
|
isFetchingNextPage: isFetchingNextClients,
|
|
isLoading: isClientsLoading,
|
|
} = useInfiniteClients(userSearch);
|
|
|
|
const clientOptions = useMemo(
|
|
() =>
|
|
(clientsInfiniteData?.pages ?? []).flatMap((page) =>
|
|
(page?.users ?? []).map((u) => ({
|
|
value: String(u.id),
|
|
label: u.name || u.username || String(u.id),
|
|
})),
|
|
),
|
|
[clientsInfiniteData],
|
|
);
|
|
|
|
// ── Query params & data ─────────────────────────────────────────────────────
|
|
|
|
const queryParams = useMemo(() => {
|
|
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
|
|
return {
|
|
search: search || undefined,
|
|
status: filterMap.status || undefined,
|
|
region: filterMap.region || undefined,
|
|
branch_id: filterMap.branch_id ? Number(filterMap.branch_id) : undefined,
|
|
card_type_id: filterMap.card_type_id ? Number(filterMap.card_type_id) : undefined,
|
|
user_id: filterMap.user_id ? Number(filterMap.user_id) : undefined,
|
|
page,
|
|
limit: perPage,
|
|
};
|
|
}, [search, activeFilters, page, perPage]);
|
|
|
|
const { data, isLoading } = useCardRequisites(queryParams);
|
|
const total = data?.count ?? 0;
|
|
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
|
|
|
const regionOptions = useMemo(() => getRegionOptions(t), [t]);
|
|
|
|
const statusOptions = useMemo(
|
|
() => [
|
|
{ value: "pending", label: t("cardRequisites.status.pending", "Garaşylýar") },
|
|
{ value: "approved", label: t("cardRequisites.status.approved", "Tassyklanan") },
|
|
{ value: "rejected", label: t("cardRequisites.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<CardRequisite>[]>(
|
|
() => [
|
|
{
|
|
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-requisites/${row.original.id}`)}
|
|
>
|
|
{row.original.id}
|
|
</button>
|
|
),
|
|
size: 70,
|
|
},
|
|
{
|
|
id: "uniqueId",
|
|
accessorKey: "uniqueId",
|
|
header: t("Unique ID", "Unikal ID"),
|
|
cell: ({ row }) => <span className="text-sm font-mono">{row.original.uniqueId || "—"}</span>,
|
|
},
|
|
{
|
|
id: "cardType",
|
|
accessorKey: "cardType",
|
|
header: t("Card type", "GÖRNÜŞI"),
|
|
cell: ({ row }) => (
|
|
<span className="text-primary font-medium">{resolveLocalizedName(row.original.cardType?.name, lang) || "—"}</span>
|
|
),
|
|
},
|
|
{
|
|
id: "customer",
|
|
accessorKey: "customerName",
|
|
header: t("Customer", "MÜŞDERI"),
|
|
cell: ({ row }) => (
|
|
<span className="text-foreground">
|
|
{row.original.customerSurname} {row.original.customerName}
|
|
</span>
|
|
),
|
|
},
|
|
{
|
|
id: "user",
|
|
accessorKey: "user",
|
|
header: t("User", "ULANYJY"),
|
|
cell: ({ row }) => <span className="text-foreground">{row.original.user?.name || row.original.user?.username || "—"}</span>,
|
|
},
|
|
{
|
|
id: "region",
|
|
accessorKey: "region",
|
|
header: t("Region", "WELAÝAT"),
|
|
cell: ({ row }) => (
|
|
<span className="text-foreground">
|
|
{row.original.region ? t(`loanOrders.regions.${row.original.region}`, row.original.region) : "—"}
|
|
</span>
|
|
),
|
|
size: 100,
|
|
},
|
|
{
|
|
id: "branch",
|
|
accessorKey: "branch",
|
|
header: t("Branch", "ŞAHAMÇA"),
|
|
cell: ({ row }) => <span className="text-foreground">{resolveLocalizedName(row.original.branch?.name, lang) || "—"}</span>,
|
|
},
|
|
{
|
|
id: "status",
|
|
accessorKey: "status",
|
|
header: t("Status", "STATUS"),
|
|
cell: ({ row }) => <CardRequisiteStatusBadge status={row.original.status} />,
|
|
size: 140,
|
|
},
|
|
{
|
|
id: "actions",
|
|
header: "",
|
|
enableHiding: false,
|
|
cell: ({ row }) => (
|
|
<TableActions
|
|
onView={() => navigate(`/card-requisites/${row.original.id}`)}
|
|
onEdit={() => navigate(`/card-requisites/${row.original.id}/edit`)}
|
|
onDelete={() => handleDelete(row.original.id)}
|
|
isDeleting={deleteMutation.isPending}
|
|
/>
|
|
),
|
|
size: 100,
|
|
},
|
|
],
|
|
[t, lang, navigate, handleDelete, deleteMutation.isPending],
|
|
);
|
|
|
|
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`cardRequisites.columns.${id}`, id) })), [t]);
|
|
|
|
const filterFields = useMemo<FilterField[]>(
|
|
() => [
|
|
{
|
|
id: "status",
|
|
label: t("Status", "STATUS"),
|
|
options: statusOptions,
|
|
},
|
|
{
|
|
id: "region",
|
|
label: t("Region", "WELAÝAT"),
|
|
options: regionOptions,
|
|
},
|
|
{
|
|
id: "branch_id",
|
|
label: t("Branch", "ŞAHAMÇA"),
|
|
type: "infinite-select",
|
|
options: branchOptions,
|
|
loading: isBranchesLoading,
|
|
isLoadingMore: isFetchingNextBranches,
|
|
hasNextPage: hasNextBranches,
|
|
onLoadMore: fetchNextBranches,
|
|
searchValue: branchSearch,
|
|
onSearchChange: setBranchSearch,
|
|
},
|
|
{
|
|
id: "card_type_id",
|
|
label: t("Card type", "KART GÖRNÜŞI"),
|
|
type: "infinite-select",
|
|
options: cardTypeOptions,
|
|
loading: isCardTypesLoading,
|
|
isLoadingMore: isFetchingNextCardTypes,
|
|
hasNextPage: hasNextCardTypes,
|
|
onLoadMore: fetchNextCardTypes,
|
|
searchValue: cardTypeSearch,
|
|
onSearchChange: setCardTypeSearch,
|
|
},
|
|
{
|
|
id: "user_id",
|
|
label: t("User", "ULANYJY"),
|
|
type: "infinite-select",
|
|
options: clientOptions,
|
|
loading: isClientsLoading,
|
|
isLoadingMore: isFetchingNextClients,
|
|
hasNextPage: hasNextClients,
|
|
onLoadMore: fetchNextClients,
|
|
searchValue: userSearch,
|
|
onSearchChange: setUserSearch,
|
|
},
|
|
],
|
|
[
|
|
t,
|
|
statusOptions,
|
|
regionOptions,
|
|
branchOptions,
|
|
isBranchesLoading,
|
|
isFetchingNextBranches,
|
|
hasNextBranches,
|
|
branchSearch,
|
|
cardTypeOptions,
|
|
isCardTypesLoading,
|
|
isFetchingNextCardTypes,
|
|
hasNextCardTypes,
|
|
cardTypeSearch,
|
|
clientOptions,
|
|
isClientsLoading,
|
|
isFetchingNextClients,
|
|
hasNextClients,
|
|
userSearch,
|
|
],
|
|
);
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
{/* Header */}
|
|
<div className="flex items-center justify-between">
|
|
<h1 className="text-xl font-semibold text-foreground">{t("cardRequisites.title", "Kart rekwizitler")}</h1>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-3 justify-between">
|
|
<TableSearchInput
|
|
value={search}
|
|
onChange={(v) => {
|
|
setSearch(v);
|
|
setPage(1);
|
|
}}
|
|
placeholder={t("cardRequisites.searchPlaceholder", "Gözlemek")}
|
|
/>
|
|
<CreateButton
|
|
label={t("cardRequisites.createTitle", "Kart rekwiziti üçin sargyt dörediň")}
|
|
onClick={() => navigate("/card-requisites/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("cardRequisites.searchPlaceholder", "Gözlemek")}
|
|
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?.cardRekwizitOrders ?? []}
|
|
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("cardRequisites.deleteConfirm", "Bu sargyt pozulsynmy?")}
|
|
description={t("cardRequisites.deleteDescription", "Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.")}
|
|
onConfirm={confirmDelete}
|
|
isLoading={deleteMutation.isPending}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|