375 lines
13 KiB
TypeScript
375 lines
13 KiB
TypeScript
import { useState, useCallback, useMemo } from "react";
|
|
import { useNavigate, Link } from "react-router-dom";
|
|
import { useTranslation } from "react-i18next";
|
|
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
|
|
|
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
|
|
|
import { DataTable } from "@/components/dataTable";
|
|
import { DataTableToolbar, type ColumnMeta, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
|
import { TableSearchInput } from "@/components/tableSearch";
|
|
import { CreateButton } from "@/components/createButton";
|
|
import { TableActions } from "@/components/tableActions";
|
|
import { DeleteDialog } from "@/components/deleteDialog";
|
|
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
|
import { useCards, useDeleteCard } from "@/features/orderNewCard/hooks/useOrderNewCard";
|
|
import type { CardOrder } from "@/features/orderNewCard/api/orderNewCardApi";
|
|
import { useBranches } from "@/features/branches/hooks/useBranches";
|
|
import { useDistricts } from "@/features/districts/hooks/useDistricts";
|
|
import { useCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
|
|
|
const PER_PAGE = 25;
|
|
|
|
// ─── Status badge ─────────────────────────────────────────────────────────────
|
|
|
|
const PENDING_STATUSES = [
|
|
"pending",
|
|
"garaşylýar",
|
|
"garaşilyar",
|
|
"garasylýar",
|
|
"garasilyar",
|
|
"garasylyar",
|
|
"kutilyor",
|
|
"kutiliyor",
|
|
"waiting",
|
|
"beklemede",
|
|
];
|
|
const APPROVED_STATUSES = [
|
|
"approved",
|
|
"tassyklandy",
|
|
"tassyklanan",
|
|
"tassyklandy",
|
|
"tassyklanyldy",
|
|
"accepted",
|
|
"confirmed",
|
|
"success",
|
|
"completed",
|
|
"approve",
|
|
];
|
|
const REJECTED_STATUSES = [
|
|
"rejected",
|
|
"reject",
|
|
"ret",
|
|
"ýatyryldy",
|
|
"yatyryldy",
|
|
"canceled",
|
|
"cancelled",
|
|
"cancelled",
|
|
"declined",
|
|
"failed",
|
|
"error",
|
|
"reject",
|
|
"red edildi",
|
|
];
|
|
|
|
function CardOrderStatusBadge({ status }: { status: string }) {
|
|
const { t } = useTranslation();
|
|
const key = (status || "").trim().toLowerCase();
|
|
|
|
let variant: StatusBadgeVariant = "default";
|
|
let icon: React.ElementType | undefined;
|
|
let label = status;
|
|
|
|
if (PENDING_STATUSES.includes(key)) {
|
|
variant = "warning";
|
|
icon = AlertCircle;
|
|
label = t("cardOrder.status.pending", "Garaşylýar");
|
|
} else if (APPROVED_STATUSES.includes(key)) {
|
|
variant = "success";
|
|
icon = CheckCircle2;
|
|
label = t("cardOrder.status.approved", "Tassyklandy");
|
|
} else if (REJECTED_STATUSES.includes(key)) {
|
|
variant = "error";
|
|
icon = XCircle;
|
|
label = t("cardOrder.status.rejected", "Ýatyryldy");
|
|
} else {
|
|
label = t(`cardOrder.status.${status}`, status);
|
|
}
|
|
|
|
return <StatusBadge label={label} variant={variant} icon={icon} />;
|
|
}
|
|
|
|
// ─── Filter field IDs ──────────────────────────────────────────────────────────
|
|
|
|
const FILTER_IDS = ["status", "branch_id", "user_id", "card_state_id", "card_type_id", "region"] as const;
|
|
type FilterId = (typeof FILTER_IDS)[number];
|
|
|
|
const INITIAL_FILTERS: ActiveFilter[] = FILTER_IDS.map((fieldId) => ({ fieldId, value: "" }));
|
|
|
|
export default function CardOrdersPage() {
|
|
const { t, i18n } = useTranslation();
|
|
const navigate = useNavigate();
|
|
const deleteMutation = useDeleteCard();
|
|
|
|
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
|
|
|
const [page, setPage] = useState(1);
|
|
const [perPage, setPerPage] = useState(PER_PAGE);
|
|
const [search, setSearch] = useState("");
|
|
const [deleteId, setDeleteId] = useState<number | null>(null);
|
|
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
|
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
|
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>(INITIAL_FILTERS);
|
|
|
|
// ── Dropdown data ──────────────────────────────────────────────────────────
|
|
const { data: branchesData } = useBranches({ page, limit: 25 });
|
|
const { data: districtsData } = useDistricts({ page, limit: 25 });
|
|
const { data: cardTypesData } = useCardTypes({ page, limit: 25 });
|
|
|
|
// ── Query ──────────────────────────────────────────────────────────────────
|
|
const getFilter = useCallback((id: FilterId) => activeFilters.find((f) => f.fieldId === id)?.value ?? "", [activeFilters]);
|
|
|
|
const queryParams = useMemo(
|
|
() => ({
|
|
search: search || undefined,
|
|
page,
|
|
limit: perPage,
|
|
status: getFilter("status") || undefined,
|
|
branch_id: getFilter("branch_id") || undefined,
|
|
user_id: getFilter("user_id") || undefined,
|
|
card_state_id: getFilter("card_state_id") || undefined,
|
|
card_type_id: getFilter("card_type_id") || undefined,
|
|
region: getFilter("region") || undefined,
|
|
}),
|
|
[search, page, perPage, getFilter],
|
|
);
|
|
|
|
const { data, isLoading } = useCards(queryParams);
|
|
|
|
const columns: ColumnDef<CardOrder>[] = [
|
|
{
|
|
id: "id",
|
|
accessorKey: "id",
|
|
header: t("cardOrder.col.id", "ID"),
|
|
cell: ({ row }) => (
|
|
<Link to={`/order-new-card/${row.original.id}`} className="font-mono text-xs text-primary hover:underline">
|
|
{row.original.id}
|
|
</Link>
|
|
),
|
|
size: 80,
|
|
},
|
|
{
|
|
id: "uniqueId",
|
|
accessorKey: "uniqueId",
|
|
header: t("cardOrder.col.uniqueId", "Sargyt belgisi"),
|
|
cell: ({ row }) => <span className="text-sm text-foreground font-mono">{row.original.uniqueId}</span>,
|
|
},
|
|
{
|
|
id: "customerName",
|
|
accessorKey: "customerName",
|
|
header: t("cardOrder.col.customer", "Müşderi"),
|
|
cell: ({ row }) => (
|
|
<span className="text-sm text-foreground">
|
|
{row.original.customerName} {row.original.customerSurname}
|
|
</span>
|
|
),
|
|
},
|
|
{
|
|
id: "phone",
|
|
accessorKey: "phone",
|
|
header: t("cardOrder.col.phone", "Telefon"),
|
|
cell: ({ row }) => <span className="font-mono text-sm">{row.original.phone}</span>,
|
|
},
|
|
{
|
|
id: "region",
|
|
accessorKey: "region",
|
|
header: t("cardOrder.col.region", "Sebit"),
|
|
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.region}</span>,
|
|
},
|
|
{
|
|
id: "status",
|
|
accessorKey: "status",
|
|
header: t("cardOrder.col.status", "Statusy"),
|
|
cell: ({ row }) => <CardOrderStatusBadge status={row.original.status} />,
|
|
},
|
|
{
|
|
id: "paid",
|
|
accessorKey: "paid",
|
|
header: t("cardOrder.col.paid", "Tölegli"),
|
|
cell: ({ row }) => (
|
|
<StatusBadge
|
|
label={row.original.paid ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
|
|
variant={row.original.paid ? "success" : "error"}
|
|
/>
|
|
),
|
|
size: 90,
|
|
},
|
|
{
|
|
id: "createdAt",
|
|
accessorKey: "createdAt",
|
|
header: t("cardOrder.col.createdAt", "Döredilen wagty"),
|
|
cell: ({ row }) => (
|
|
<span className="text-sm text-muted-foreground whitespace-nowrap">
|
|
{row.original.createdAt ? new Date(row.original.createdAt).toLocaleString() : "—"}
|
|
</span>
|
|
),
|
|
size: 180,
|
|
},
|
|
{
|
|
id: "actions",
|
|
header: "",
|
|
enableHiding: false,
|
|
cell: ({ row }) => (
|
|
<TableActions
|
|
onView={() => navigate(`/order-new-card/${row.original.id}`)}
|
|
onEdit={() => navigate(`/order-new-card/${row.original.id}/edit`)}
|
|
onDelete={() => setDeleteId(row.original.id)}
|
|
isDeleting={deleteMutation.isPending}
|
|
/>
|
|
),
|
|
size: 100,
|
|
},
|
|
];
|
|
|
|
const columnMeta: ColumnMeta[] = columns
|
|
.filter((c) => c.id !== "actions")
|
|
.map((c) => ({
|
|
id: c.id!,
|
|
label: typeof c.header === "string" ? c.header : c.id!,
|
|
}));
|
|
|
|
const total = data?.count ?? 0;
|
|
const totalPages = Math.ceil(total / perPage);
|
|
|
|
// ── Filter fields ──────────────────────────────────────────────────────────
|
|
const filterFields = useMemo<FilterField[]>(
|
|
() => [
|
|
{
|
|
id: "status",
|
|
label: t("cardOrder.filter.status", "Status"),
|
|
options: [
|
|
{ value: "pending", label: t("cardOrder.status.pending", "Garaşylýar") },
|
|
{ value: "approved", label: t("cardOrder.status.approved", "Tassyklandy") },
|
|
{ value: "rejected", label: t("cardOrder.status.rejected", "Ýatyryldy") },
|
|
],
|
|
},
|
|
{
|
|
id: "branch_id",
|
|
label: t("cardOrder.filter.branch", "Şahamça"),
|
|
options: (branchesData?.branches ?? []).map((b) => ({
|
|
value: String(b.id),
|
|
label: b.name[lang] || b.name.tm,
|
|
})),
|
|
},
|
|
{
|
|
id: "region",
|
|
label: t("cardOrder.filter.region", "Sebit"),
|
|
options: (districtsData?.provinces ?? []).map((d) => ({
|
|
value: d.region?.tm || d.name.tm,
|
|
label: d.name[lang] || d.name.tm,
|
|
})),
|
|
},
|
|
{
|
|
id: "user_id",
|
|
label: t("cardOrder.filter.userId", "Ulanyjy ID"),
|
|
type: "text",
|
|
},
|
|
{
|
|
id: "card_state_id",
|
|
label: t("cardOrder.filter.cardStateId", "Kart ýagdaýy ID"),
|
|
type: "text",
|
|
},
|
|
{
|
|
id: "card_type_id",
|
|
label: t("cardOrder.filter.cardTypeId", "Kart görnüşi"),
|
|
options: (cardTypesData?.paymentCards ?? []).map((ct) => ({
|
|
value: String(ct.id),
|
|
label: ct.title[lang] || ct.title.tm,
|
|
})),
|
|
},
|
|
],
|
|
[t, lang, branchesData, districtsData, cardTypesData],
|
|
);
|
|
|
|
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
|
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
|
setPage(1);
|
|
}, []);
|
|
|
|
const handleFilterReset = useCallback(() => {
|
|
setActiveFilters(INITIAL_FILTERS);
|
|
setPage(1);
|
|
}, []);
|
|
|
|
const handleDelete = useCallback(() => {
|
|
if (deleteId === null) return;
|
|
deleteMutation.mutate(deleteId);
|
|
setDeleteId(null);
|
|
}, [deleteId, deleteMutation]);
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
<div className="flex items-center justify-between">
|
|
<h1 className="text-xl font-semibold text-foreground tracking-tight">{t("cardOrder.title", "Kart sargytlary")}</h1>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-3 justify-between">
|
|
<TableSearchInput
|
|
value={search}
|
|
onChange={(v) => {
|
|
setSearch(v);
|
|
setPage(1);
|
|
}}
|
|
placeholder={t("common.search", "Gözlemek")}
|
|
/>
|
|
<CreateButton label={t("cardOrder.create", "Kart dörediň")} onClick={() => navigate("/order-new-card/create")} />
|
|
</div>
|
|
|
|
<div className="bg-card border border-border rounded-xl p-4">
|
|
<DataTableToolbar
|
|
searchValue={search}
|
|
onSearchChange={(v) => {
|
|
setSearch(v);
|
|
setPage(1);
|
|
}}
|
|
searchPlaceholder={t("common.search", "Gözlemek")}
|
|
columns={columnMeta}
|
|
columnVisibility={columnVisibility}
|
|
onColumnVisibilityChange={setColumnVisibility}
|
|
columnOrder={columnOrder}
|
|
onColumnOrderChange={setColumnOrder}
|
|
hideSearch
|
|
hideAction
|
|
perPageOptions={[10, 25, 50, 100]}
|
|
perPage={perPage}
|
|
onPerPageChange={(v) => {
|
|
setPerPage(v);
|
|
setPage(1);
|
|
}}
|
|
filterFields={filterFields}
|
|
activeFilters={activeFilters}
|
|
onFilterChange={handleFilterChange}
|
|
onFilterReset={handleFilterReset}
|
|
/>
|
|
|
|
<DataTable
|
|
columns={columns}
|
|
data={data?.cardOrders ?? []}
|
|
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>
|
|
|
|
<DeleteDialog
|
|
open={deleteId !== null}
|
|
onOpenChange={(o) => {
|
|
if (!o) setDeleteId(null);
|
|
}}
|
|
title={t("cardOrder.deleteConfirm", "Bu kart pozulsynmy?")}
|
|
description={t("cardOrder.deleteDescription", "Bu kart hemişelik pozular. Bu işi yzyna gaýtaryp bolmaz.")}
|
|
onConfirm={handleDelete}
|
|
isLoading={deleteMutation.isPending}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|