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(null); const [selectedOrderId, setSelectedOrderId] = useState(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([{ id: "createdAt", desc: true }]); // ─── Column Visibility & Order ───────────────────────────────────────────── const [columnVisibility, setColumnVisibility] = useState({}); const [columnOrder, setColumnOrder] = useState([]); // ─── 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[] = useMemo( () => [ { id: "id", accessorKey: "id", header: t("common.id", "ID"), cell: ({ row }) => ( ), size: 70, enableSorting: true, }, { id: "payerFullName", header: t("intlPayment.historyColumns.payerFullName", "Amaly geçiren raýatyň F.A.A."), cell: ({ row }) => {getPayerFullName(row.original)}, size: 180, }, { id: "maskedCard", header: t("intlPayment.historyColumns.maskedCard", "Amaly geçiren raýatyň kart belgisi (mask)"), cell: ({ row }) => {getMaskedCard(row.original)}, size: 170, }, { id: "paymentYear", header: t("intlPayment.historyColumns.paymentYear", "Töleg ýyly"), cell: ({ row }) => {getPaymentYear(row.original)}, size: 90, }, { id: "paymentMonth", header: t("intlPayment.historyColumns.paymentMonth", "Töleg aýy"), cell: ({ row }) => {getPaymentMonth(row.original)}, size: 90, }, { id: "createdAt", accessorKey: "createdAt", header: t("intlPayment.historyColumns.transactionTime", "Amalyň geçirilen wagty"), cell: ({ row }) => {getTransactionTime(row.original)}, size: 140, enableSorting: true, }, { id: "amount", header: t("intlPayment.historyColumns.amount", "Amalyň möçberi"), cell: ({ row }) => {getAmount(row.original)}, size: 110, }, { id: "amountTmt", accessorKey: "totalAmountTmt", header: t("intlPayment.historyColumns.amountTmt", "Amalyň manat möçberi"), cell: ({ row }) => {getAmountTmt(row.original)}, size: 130, enableSorting: true, }, { id: "reference", header: t("intlPayment.historyColumns.reference", "Amalyň referensi"), cell: ({ row }) => {getReference(row.original)}, size: 150, }, { id: "isPaid", header: t("intlPayment.historyColumns.isPaid", "Tölenen"), cell: ({ row }) => ( ), size: 110, }, { id: "isSynced", header: t("intlPayment.historyColumns.isSynced", "Ulgam bn birikdirilen"), cell: ({ row }) => ( ), size: 130, }, { id: "actions", header: "", cell: ({ row }) => (
{/* Storage (Database) icon: opens payment detail dialog */} {/* */} {/* Eye icon: opens last-step dialog */}
), 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 (
{/* ── Standard Shared DataTable & Toolbar ─────────────────────────────── */} String(row.id)} sorting={sorting} onSortingChange={setSorting} manualSorting={false} currentPage={page} totalPages={totalPages} totalCount={totalCount} onPageChange={setPage} toolbar={ { 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) ────────── */} { if (!open) setSelectedPaymentId(null); }} /> {/* ── Last Step Dialog (Triggered on clicking eye icon) ─────────────────── */} { if (!open) setSelectedOrderId(null); }} />
); }