changed payment history api in visa/master payments
This commit is contained in:
1 parent
cbfb467651
commit
879ed77121
15 files changed
+1174
-190
No files matched your search
@@ -1,169 +1,359 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Search } from "lucide-react";
|
||||
import { useState, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Database, Eye } from "lucide-react";
|
||||
import type { VisibilityState } from "@tanstack/react-table";
|
||||
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useGetOnlinePaymentById } from "@/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory";
|
||||
import type { PaymentHistoryStep } from "@/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi";
|
||||
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 } from "./PaymentDetailDialog";
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function formatDateTime(value: string | null | undefined): string {
|
||||
if (!value) return "—";
|
||||
|
||||
const d = new Date(value);
|
||||
|
||||
if (Number.isNaN(d.getTime())) return "—";
|
||||
|
||||
const p = (n: number) => String(n).padStart(2, "0");
|
||||
|
||||
return `${p(d.getDate())}/${p(d.getMonth() + 1)}/${d.getFullYear()}, ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||
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 detailEntries(detail: PaymentHistoryStep["detail"] | null | undefined): [string, string][] {
|
||||
if (!detail || typeof detail !== "object") return [];
|
||||
|
||||
return Object.entries(detail).map(([key, value]) => [key, value == null ? "—" : String(value)]);
|
||||
function getMaskedCard(row: any): string {
|
||||
return (
|
||||
row.maskedCard || row.maskedPan || row.cardNumber || row.cardMask || row.card || row.detail?.masked_card || row.detail?.card || "—"
|
||||
);
|
||||
}
|
||||
|
||||
function matches(row: PaymentHistoryStep, query: string): boolean {
|
||||
const haystack = [row.step, row.createdByName, ...detailEntries(row.detail).flat()].join(" ").toLowerCase();
|
||||
|
||||
return haystack.includes(query);
|
||||
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());
|
||||
}
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
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 | undefined;
|
||||
orderId?: string | number;
|
||||
paymentId?: string | number;
|
||||
}
|
||||
|
||||
export function PaymentHistoryTable({ orderId }: PaymentHistoryTableProps) {
|
||||
export function PaymentHistoryTable({ orderId, paymentId }: PaymentHistoryTableProps = {}) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
// ─── Dialog State ──────────────────────────────────────────────────────────
|
||||
const [selectedPaymentId, setSelectedPaymentId] = useState<number | null>(null);
|
||||
|
||||
// ─── Pagination & Search ───────────────────────────────────────────────────
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(PER_PAGE);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const { data, isLoading, isError } = useGetOnlinePaymentById(Number(orderId));
|
||||
// ─── Sorting State (Client-Side via TanStack Table) ─────────────────────────
|
||||
const [sorting, setSorting] = useState<SortingState>([{ id: "createdAt", desc: true }]);
|
||||
|
||||
const rows = useMemo(() => {
|
||||
const sorted = [...(data ?? [])].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||
// ─── Column Visibility & Order ─────────────────────────────────────────────
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
|
||||
const query = search.trim().toLowerCase();
|
||||
// ─── Query: /payment-history/payments/:id/gateway ──────────────────────────
|
||||
const effectiveId = paymentId || orderId;
|
||||
const { data: rawData, isLoading } = useGetPaymentGateway(effectiveId);
|
||||
|
||||
return query ? sorted.filter((row) => matches(row, query)) : sorted;
|
||||
}, [data, search]);
|
||||
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: navigates to audit/history step timeline */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-8 text-muted-foreground hover:text-foreground cursor-pointer"
|
||||
title={t("onlinePayments.auditHistory", "Töleg taryhy")}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
navigate(`/online-payments-history/${row.original.orderId || row.original.id}`);
|
||||
}}
|
||||
>
|
||||
<Eye className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
size: 80,
|
||||
},
|
||||
],
|
||||
[t, navigate],
|
||||
);
|
||||
|
||||
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">
|
||||
{/* Search */}
|
||||
<div className="relative mb-4 max-w-xs">
|
||||
<Search size={13} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
|
||||
<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);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder={t("common.search", "Gözlemek")}
|
||||
className="
|
||||
h-9
|
||||
w-full
|
||||
rounded-md
|
||||
border
|
||||
border-border
|
||||
bg-background
|
||||
pl-9
|
||||
pr-3
|
||||
text-sm
|
||||
focus:outline-none
|
||||
focus:ring-2
|
||||
focus:ring-ring
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Loading */}
|
||||
{isLoading ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
{[...Array(4)].map((_, index) => (
|
||||
<Skeleton key={index} className="h-10 w-full" />
|
||||
))}
|
||||
</div>
|
||||
) : isError ? (
|
||||
/* Error */
|
||||
<div className="py-10 text-center text-sm text-destructive">
|
||||
{t("paymentHistory.loadError", "Töleg taryhyny ýüklemek başartmady")}
|
||||
</div>
|
||||
) : rows.length === 0 ? (
|
||||
/* Empty */
|
||||
<div className="flex flex-col items-center justify-center py-10 text-muted-foreground/50">
|
||||
<div className="mb-3 flex h-12 w-12 items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/20">
|
||||
<svg viewBox="0 0 24 24" className="h-6 w-6" fill="none" stroke="currentColor" strokeWidth={1.5}>
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" />
|
||||
<line x1="3" y1="9" x2="21" y2="9" />
|
||||
<line x1="9" y1="21" x2="9" y2="9" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<p className="text-sm">{t("paymentHistory.empty", "Berlen kriteriýalara Töleg gabat gelmedi.")}</p>
|
||||
</div>
|
||||
) : (
|
||||
/* Table */
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/50 text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-medium">{t("paymentHistory.col.id", "ID")}</th>
|
||||
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-medium">{t("paymentHistory.col.step", "Ädim")}</th>
|
||||
|
||||
<th className="px-4 py-2.5 font-medium">{t("paymentHistory.col.detail", "Jikme-jiklik")}</th>
|
||||
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-medium">{t("paymentHistory.col.createdBy", "Kim tarapyndan")}</th>
|
||||
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-medium">{t("paymentHistory.col.createdAt", "Wagty")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{rows.map((row) => {
|
||||
const entries = detailEntries(row.detail);
|
||||
|
||||
return (
|
||||
<tr key={row.id} className="border-t border-border align-top">
|
||||
{/* ID */}
|
||||
<td className="px-4 py-2.5 font-mono text-xs text-muted-foreground">{row.id}</td>
|
||||
|
||||
{/* Step */}
|
||||
<td className="whitespace-nowrap px-4 py-2.5 font-medium">{t(`paymentHistory.steps.${row.step}`, row.step)}</td>
|
||||
|
||||
{/* Details */}
|
||||
<td className="px-4 py-2.5">
|
||||
{entries.length === 0 ? (
|
||||
<span className="text-muted-foreground/50">—</span>
|
||||
) : (
|
||||
<dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs">
|
||||
{entries.map(([key, value]) => (
|
||||
<div key={key} className="contents">
|
||||
<dt className="text-muted-foreground">{key}</dt>
|
||||
|
||||
<dd className="break-all">{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Created By */}
|
||||
<td className="whitespace-nowrap px-4 py-2.5">{row.createdByName || "—"}</td>
|
||||
|
||||
{/* Created At */}
|
||||
<td className="whitespace-nowrap px-4 py-2.5 text-muted-foreground">{formatDateTime(row.createdAt)}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{/* ── Payment Detail Dialog (Triggered on clicking storage icon) ────────── */}
|
||||
<PaymentDetailDialog
|
||||
paymentId={selectedPaymentId}
|
||||
open={selectedPaymentId !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setSelectedPaymentId(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user