Files
tbbank-frontend/src/features/visaMasterPayments/components/PaymentHistoryTable.tsx
2026-10-24 22:07:16 +05:00

368 lines
14 KiB
TypeScript

import { useState, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Eye } from "lucide-react";
import type { VisibilityState } from "@tanstack/react-table";
import { DataTable, type ColumnDef, type SortingState } from "@/components/dataTable";
import { DataTableToolbar, type ColumnMeta } from "@/components/dataTableToolbar";
import { Button } from "@/components/ui/button";
import { useGetPaymentGateway } from "@/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory";
import { ActiveStatusCell } from "@/constants/statusCells";
import { formatFromApiDate } from "@/lib/utils/dateUtils";
import { PaymentDetailDialog, LastStepDialog } from "./PaymentDetailDialog";
// ─── Helpers ──────────────────────────────────────────────────────────────────
function getPayerFullName(row: any): string {
if (row.cardholderName) return row.cardholderName;
if (row.payerFullName) return row.payerFullName;
if (row.senderFullName) return row.senderFullName;
if (row.customerName) return row.customerName;
if (row.fullName) return row.fullName;
const nameParts = [row.passportName, row.passportSurname].filter(Boolean);
if (nameParts.length > 0) return nameParts.join(" ");
if (row.detail?.payer_full_name) return row.detail.payer_full_name;
if (row.createdByName) return row.createdByName;
return "—";
}
function getMaskedCard(row: any): string {
return (
row.maskedCard || row.maskedPan || row.cardNumber || row.cardMask || row.card || row.detail?.masked_card || row.detail?.card || "—"
);
}
function getPaymentYear(row: any): string {
if (row.paymentYear != null) return String(row.paymentYear);
if (row.year != null) return String(row.year);
const period = row.paymentPeriod || row.createdAt || row.created_at;
if (!period) return "—";
const d = new Date(period);
return Number.isNaN(d.getTime()) ? String(period).split("-")[0] || "—" : String(d.getFullYear());
}
function getPaymentMonth(row: any): string {
if (row.paymentMonth != null) return String(row.paymentMonth).padStart(2, "0");
if (row.month != null) return String(row.month).padStart(2, "0");
const period = row.paymentPeriod || row.createdAt || row.created_at;
if (!period) return "—";
const d = new Date(period);
return Number.isNaN(d.getTime()) ? String(period).split("-")[1] || "—" : String(d.getMonth() + 1).padStart(2, "0");
}
function getTransactionTime(row: any): string {
const t = row.createdAt || row.transactionTime || row.created_at;
return t ? formatFromApiDate(t) : "—";
}
function getAmount(row: any): string {
if (row.amountUsd != null) return `${row.amountUsd} $`;
if (row.amount != null) return `${row.amount}`;
if (row.detail?.amount != null) return `${row.detail.amount}`;
return "—";
}
function getAmountTmt(row: any): string {
if (row.totalAmountTmt != null) return `${row.totalAmountTmt.toLocaleString()} TMT`;
if (row.amountTmt != null) return `${row.amountTmt.toLocaleString()} TMT`;
if (row.detail?.amount_tmt != null) return `${row.detail.amount_tmt} TMT`;
return "—";
}
function getReference(row: any): string {
const mdOrder = row.gatewayResponse?.attributes?.find?.((a: any) => a.name === "mdOrder")?.value;
return mdOrder || row.orderNumber || row.gatewayReference || row.reference || row.transactionId || row.detail?.gateway_reference || "—";
}
function isPaid(row: any): boolean {
return Boolean(row.paid ?? (row.detail?.paid === "true" || row.detail?.paid === true));
}
function isSynced(row: any): boolean {
if (row.gatewayResponse?.orderStatus === 0 || row.gatewayResponse?.errorMessage === "Успешно") return true;
return Boolean(
row.synced ??
row.isSynced ??
row.systemSynced ??
row.syncedWithSystem ??
(row.detail?.synced === "true" || row.detail?.synced === true),
);
}
const PER_PAGE = 25;
// ─── Main Component ───────────────────────────────────────────────────────────
interface PaymentHistoryTableProps {
orderId?: string | number;
paymentId?: string | number;
}
export function PaymentHistoryTable({ orderId, paymentId }: PaymentHistoryTableProps = {}) {
const { t } = useTranslation();
// ─── Dialog State ──────────────────────────────────────────────────────────
const [selectedPaymentId, setSelectedPaymentId] = useState<number | null>(null);
const [selectedOrderId, setSelectedOrderId] = useState<number | null>(null);
// ─── Pagination & Search ───────────────────────────────────────────────────
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(PER_PAGE);
const [search, setSearch] = useState("");
// ─── Sorting State (Client-Side via TanStack Table) ─────────────────────────
const [sorting, setSorting] = useState<SortingState>([{ id: "createdAt", desc: true }]);
// ─── Column Visibility & Order ─────────────────────────────────────────────
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
const [columnOrder, setColumnOrder] = useState<string[]>([]);
// ─── Query: /payment-history/payments/:id/gateway ──────────────────────────
const effectiveId = paymentId || orderId;
const { data: rawData, isLoading } = useGetPaymentGateway(effectiveId);
const items = useMemo(() => {
let list: any[] = [];
if (Array.isArray(rawData)) {
list = rawData;
} else if (rawData && typeof rawData === "object" && (rawData as any).id) {
list = [rawData];
} else if (rawData && Array.isArray((rawData as any).items)) {
list = (rawData as any).items;
}
if (!search.trim()) return list;
const q = search.trim().toLowerCase();
return list.filter((r) => {
const haystack = [r.id, getPayerFullName(r), getMaskedCard(r), getReference(r), r.orderId].join(" ").toLowerCase();
return haystack.includes(q);
});
}, [rawData, search]);
const totalCount = useMemo(() => {
if (Array.isArray(rawData)) return rawData.length;
if (rawData && typeof (rawData as any).count === "number") return (rawData as any).count;
return items.length;
}, [rawData, items]);
const totalPages = Math.ceil(totalCount / perPage) || 1;
// ─── Columns ───────────────────────────────────────────────────────────────
// 1. Selected Resources (handled by DataTable's enableRowSelection)
// 2. ID
// 3. Amaly geçiren raýatyň F.A.A.
// 4. Amaly geçiren raýatyň kart belgisi (mask)
// 5. Töleg ýyly
// 6. Töleg aýy
// 7. Amalyň geçirilen wagty
// 8. Amalyň möçberi
// 9. Amalyň manat möçberi
// 10. Amalyň referensi
// 11. Tölenen
// 12. Ulgam bn birikdirilen
// 13. Actions (Storage icon for modal + Eye icon for history page)
const columns: ColumnDef<any>[] = useMemo(
() => [
{
id: "id",
accessorKey: "id",
header: t("common.id", "ID"),
cell: ({ row }) => (
<button
type="button"
onClick={() => setSelectedPaymentId(row.original.id)}
className="font-mono text-xs font-medium text-primary hover:underline cursor-pointer"
>
{row.original.id}
</button>
),
size: 70,
enableSorting: true,
},
{
id: "payerFullName",
header: t("intlPayment.historyColumns.payerFullName", "Amaly geçiren raýatyň F.A.A."),
cell: ({ row }) => <span className="text-sm text-foreground font-medium whitespace-nowrap">{getPayerFullName(row.original)}</span>,
size: 180,
},
{
id: "maskedCard",
header: t("intlPayment.historyColumns.maskedCard", "Amaly geçiren raýatyň kart belgisi (mask)"),
cell: ({ row }) => <span className="font-mono text-xs text-foreground whitespace-nowrap">{getMaskedCard(row.original)}</span>,
size: 170,
},
{
id: "paymentYear",
header: t("intlPayment.historyColumns.paymentYear", "Töleg ýyly"),
cell: ({ row }) => <span className="text-xs text-muted-foreground whitespace-nowrap">{getPaymentYear(row.original)}</span>,
size: 90,
},
{
id: "paymentMonth",
header: t("intlPayment.historyColumns.paymentMonth", "Töleg aýy"),
cell: ({ row }) => <span className="text-xs text-muted-foreground whitespace-nowrap">{getPaymentMonth(row.original)}</span>,
size: 90,
},
{
id: "createdAt",
accessorKey: "createdAt",
header: t("intlPayment.historyColumns.transactionTime", "Amalyň geçirilen wagty"),
cell: ({ row }) => <span className="text-xs text-muted-foreground whitespace-nowrap">{getTransactionTime(row.original)}</span>,
size: 140,
enableSorting: true,
},
{
id: "amount",
header: t("intlPayment.historyColumns.amount", "Amalyň möçberi"),
cell: ({ row }) => <span className="text-xs font-medium text-foreground whitespace-nowrap">{getAmount(row.original)}</span>,
size: 110,
},
{
id: "amountTmt",
accessorKey: "totalAmountTmt",
header: t("intlPayment.historyColumns.amountTmt", "Amalyň manat möçberi"),
cell: ({ row }) => <span className="text-xs font-semibold text-primary whitespace-nowrap">{getAmountTmt(row.original)}</span>,
size: 130,
enableSorting: true,
},
{
id: "reference",
header: t("intlPayment.historyColumns.reference", "Amalyň referensi"),
cell: ({ row }) => <span className="font-mono text-xs text-muted-foreground whitespace-nowrap">{getReference(row.original)}</span>,
size: 150,
},
{
id: "isPaid",
header: t("intlPayment.historyColumns.isPaid", "Tölenen"),
cell: ({ row }) => (
<ActiveStatusCell
active={isPaid(row.original)}
labelActive={t("onlinePayments.statuses.paid", "Tölendi")}
labelInactive={t("onlinePayments.statuses.unpaid", "Tölenmedi")}
/>
),
size: 110,
},
{
id: "isSynced",
header: t("intlPayment.historyColumns.isSynced", "Ulgam bn birikdirilen"),
cell: ({ row }) => (
<ActiveStatusCell active={isSynced(row.original)} labelActive={t("common.yes", "Hawa")} labelInactive={t("common.no", "Ýok")} />
),
size: 130,
},
{
id: "actions",
header: "",
cell: ({ row }) => (
<div className="flex items-center justify-end gap-1">
{/* Storage (Database) icon: opens payment detail dialog */}
{/* <Button
variant="ghost"
size="icon"
className="size-8 text-muted-foreground hover:text-foreground cursor-pointer"
title={t("onlinePayments.detail", "Giňişleýin maglumat")}
onClick={(e) => {
e.stopPropagation();
setSelectedPaymentId(row.original.id);
}}
>
<Database className="size-4" />
</Button> */}
{/* Eye icon: opens last-step dialog */}
<Button
variant="ghost"
size="icon"
className="size-8 text-muted-foreground hover:text-foreground cursor-pointer"
title={t("onlinePayments.lastStep.title", "Iň soňky işlem")}
onClick={(e) => {
e.stopPropagation();
setSelectedOrderId(row.original.orderId || row.original.id);
}}
>
<Eye className="size-4" />
</Button>
</div>
),
size: 80,
},
],
[t],
);
const columnMeta: ColumnMeta[] = useMemo(
() =>
columns
.filter((c) => c.id !== "actions")
.map((c) => ({
id: c.id!,
label: typeof c.header === "string" ? c.header : c.id!,
})),
[columns],
);
return (
<div className="p-4 space-y-4">
{/* ── Standard Shared DataTable & Toolbar ─────────────────────────────── */}
<DataTable
columns={columns}
data={items}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
getRowId={(row) => String(row.id)}
sorting={sorting}
onSortingChange={setSorting}
manualSorting={false}
currentPage={page}
totalPages={totalPages}
totalCount={totalCount}
onPageChange={setPage}
toolbar={
<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}
perPageOptions={[10, 25, 50, 100]}
perPage={perPage}
onPerPageChange={(v) => {
setPerPage(v);
setPage(1);
}}
/>
}
/>
{/* ── Payment Detail Dialog (Triggered on clicking storage icon) ────────── */}
<PaymentDetailDialog
paymentId={selectedPaymentId}
open={selectedPaymentId !== null}
onOpenChange={(open) => {
if (!open) setSelectedPaymentId(null);
}}
/>
{/* ── Last Step Dialog (Triggered on clicking eye icon) ─────────────────── */}
<LastStepDialog
orderId={selectedOrderId}
open={selectedOrderId !== null}
onOpenChange={(open) => {
if (!open) setSelectedOrderId(null);
}}
/>
</div>
);
}