diff --git a/src/app/router/index.tsx b/src/app/router/index.tsx index daaff5c..3260ce9 100644 --- a/src/app/router/index.tsx +++ b/src/app/router/index.tsx @@ -77,6 +77,7 @@ const VisaMasterSberSettingCreatePage = lazy(() => import("@/pages/currencies/vi const VisaMasterSberSettingEditPage = lazy(() => import("@/pages/currencies/visaMasterSberSettingsEdit")); const OnlinePaymentsHistoryPage = lazy(() => import("@/pages/onlinePaymentsHistory")); const OnlinePaymentsHistoryViewPage = lazy(() => import("@/pages/onlinePaymentsHistory/onlinePaymenHistoryView")); +const OnlinePaymentDetailViewPage = lazy(() => import("@/pages/onlinePaymentsHistory/onlinePaymentDetailView")); const RolesPage = lazy(() => import("@/pages/settings/users/roles")); const RoleCreatePage = lazy(() => import("@/pages/settings/users/createRole")); const RoleViewPage = lazy(() => import("@/pages/settings/users/rolesView")); @@ -579,6 +580,11 @@ const routes: AppRoute[] = [ ...bc((t) => t("onlinePayments.title", "Onlaýn töleg taryhy"), "/online-payments-history"), children: [ { path: "/online-payments-history", element: page(OnlinePaymentsHistoryPage) }, + { + path: "/online-payments-history/payments/:id", + handle: { title: (t) => t("onlinePayments.paymentViewTitle", "Töleg maglumaty") }, + element: page(OnlinePaymentDetailViewPage), + }, { path: "/online-payments-history/:id", handle: { title: (t) => t("onlinePayments.viewTitle", "Töleg giňišleýin") }, diff --git a/src/components/dataTable.tsx b/src/components/dataTable.tsx index 5b44526..45dd6ff 100644 --- a/src/components/dataTable.tsx +++ b/src/components/dataTable.tsx @@ -1,4 +1,5 @@ import { useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; import { flexRender, getCoreRowModel, @@ -22,9 +23,9 @@ import { } from "@/components/ui/pagination"; import { cn } from "@/lib/utils"; import { useOutsideClick } from "@/lib/hooks/useOutsideClick"; -import { ChevronDown } from "lucide-react"; +import { ChevronDown, ArrowUp, ArrowDown, ArrowUpDown } from "lucide-react"; -export type { ColumnDef }; +export type { ColumnDef, SortingState }; // ─── Pagination ─────────────────────────────────────────────────────────────── @@ -35,6 +36,7 @@ interface DataTablePaginationProps { } function DataTablePagination({ currentPage, totalPages, onPageChange }: DataTablePaginationProps) { + const { t } = useTranslation(); if (totalPages <= 1) return null; const getPages = (): (number | "ellipsis")[] => { @@ -61,6 +63,7 @@ function DataTablePagination({ currentPage, totalPages, onPageChange }: DataTabl { e.preventDefault(); if (currentPage > 1) onPageChange(currentPage - 1); @@ -93,6 +96,7 @@ function DataTablePagination({ currentPage, totalPages, onPageChange }: DataTabl { e.preventDefault(); if (currentPage < totalPages) onPageChange(currentPage + 1); @@ -223,6 +227,11 @@ interface DataTableProps { onRowSelectionChange?: (rows: TData[]) => void; getRowId?: (row: TData) => string; + // Sorting — manual / server-side + sorting?: SortingState; + onSortingChange?: (updater: SortingState | ((prev: SortingState) => SortingState)) => void; + manualSorting?: boolean; + // Pagination — server-side currentPage?: number; totalPages?: number; @@ -245,6 +254,9 @@ export function DataTable({ enableRowSelection = false, onRowSelectionChange, getRowId, + sorting, + onSortingChange, + manualSorting, currentPage = 1, totalPages = 1, totalCount, @@ -252,7 +264,10 @@ export function DataTable({ headerContent, toolbar, }: DataTableProps) { - const [sorting, setSorting] = useState([]); + const [internalSorting, setInternalSorting] = useState([]); + const effectiveSorting = sorting !== undefined ? sorting : internalSorting; + const effectiveOnSortingChange = onSortingChange !== undefined ? onSortingChange : setInternalSorting; + const [rowSelection, setRowSelection] = useState({}); // Tracks whether ALL records (across pages) are logically selected const [allTotalSelected, setAllTotalSelected] = useState(false); @@ -338,11 +353,12 @@ export function DataTable({ data, columns: allColumns, state: { - sorting, + sorting: effectiveSorting, rowSelection, columnVisibility: columnVisibility ?? {}, columnOrder: effectiveColumnOrder, }, + manualSorting, getRowId, enableRowSelection, onRowSelectionChange: (updater) => { @@ -357,7 +373,7 @@ export function DataTable({ onRowSelectionChange(selectedRows); } }, - onSortingChange: setSorting, + onSortingChange: effectiveOnSortingChange, onColumnVisibilityChange: (updater) => { if (!onColumnVisibilityChange) return; const next = typeof updater === "function" ? updater(columnVisibility ?? {}) : updater; @@ -369,7 +385,7 @@ export function DataTable({ onColumnOrderChange(next); }, getCoreRowModel: getCoreRowModel(), - getSortedRowModel: getSortedRowModel(), + getSortedRowModel: manualSorting ? undefined : getSortedRowModel(), }); // ── Selection banner ──────────────────────────────────────────────────────── @@ -409,21 +425,38 @@ export function DataTable({ {table.getHeaderGroups().map((headerGroup) => ( - {headerGroup.headers.map((header) => ( - - {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())} - - ))} + {headerGroup.headers.map((header) => { + const canSort = header.column.getCanSort(); + const sortDir = header.column.getIsSorted(); + return ( + +
+ {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())} + {canSort && ( + + {sortDir === "asc" ? ( + + ) : sortDir === "desc" ? ( + + ) : ( + + )} + + )} +
+
+ ); + })}
))}
diff --git a/src/constants/paymentStatus.ts b/src/constants/paymentStatus.ts index 7f935d9..69a3171 100644 --- a/src/constants/paymentStatus.ts +++ b/src/constants/paymentStatus.ts @@ -6,7 +6,7 @@ import { buildEnumOptions, getEnumLabel, isEnumValue, type EnumConfig, type Tran // ─── Gateway status ─────────────────────────────────────────────────────────── -export const GATEWAY_STATUS_VALUES = ["pending", "paid", "unpaid", "failed"] as const; +export const GATEWAY_STATUS_VALUES = ["pending", "paid", "unpaid", "failed", "success", "completed"] as const; export type GatewayStatusValue = (typeof GATEWAY_STATUS_VALUES)[number]; @@ -15,6 +15,8 @@ export const GATEWAY_STATUS_LABELS: Record = { paid: "Paid", unpaid: "Unpaid", failed: "Failed", + success: "Success", + completed: "Completed", }; const GATEWAY_STATUS_ENUM: EnumConfig = { @@ -28,6 +30,8 @@ export const GATEWAY_STATUS_BADGE_VARIANTS: Record = { @@ -35,6 +39,8 @@ export const GATEWAY_STATUS_ICONS: Record = { paid: CheckCircle2, unpaid: Clock, failed: XCircle, + success: CheckCircle2, + completed: CheckCircle2, }; // ─── Paid flag ──────────────────────────────────────────────────────────────── @@ -82,6 +88,22 @@ export function getGatewayStatusOptions(t?: TranslateFn, prefix?: string): Selec return buildEnumOptions(withPrefix(GATEWAY_STATUS_ENUM, prefix), t); } +export const PAYMENT_HISTORY_STATUS_VALUES = ["failed", "pending", "success", "completed"] as const; + +export function getPaymentHistoryStatusOptions(t?: TranslateFn, prefix?: string): SelectOption[] { + return buildEnumOptions( + withPrefix( + { + values: PAYMENT_HISTORY_STATUS_VALUES, + labels: GATEWAY_STATUS_LABELS, + prefix: "onlinePayments.gatewayStatus", + }, + prefix, + ), + t, + ); +} + export function toPaidValue(paid: boolean): PaidValue { return paid ? "paid" : "unpaid"; } diff --git a/src/constants/statusCells.tsx b/src/constants/statusCells.tsx index a39bbf1..e826dc4 100644 --- a/src/constants/statusCells.tsx +++ b/src/constants/statusCells.tsx @@ -22,13 +22,21 @@ export function StatusCell({ status, prefix = "status", fallbackLabels, fallback return ; } -export function ActiveStatusCell({ active }: { active: boolean }) { +interface ActiveStatusCellProps { + active?: boolean; + status?: boolean; + labelActive?: string; + labelInactive?: string; +} + +export function ActiveStatusCell({ active, status, labelActive, labelInactive }: ActiveStatusCellProps) { const { t } = useTranslation(); + const isActive = Boolean(active ?? status); return ( ); } diff --git a/src/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi.ts b/src/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi.ts index d828fb3..facc0bf 100644 --- a/src/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi.ts +++ b/src/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi.ts @@ -40,11 +40,17 @@ export interface OnlinePayment { updatedAt: string; } +export type PaymentSortField = "created_at" | "id" | "status" | "amount"; +export type PaymentSortOrder = "asc" | "desc"; + export interface OnlinePaymentListParams { - orderId?: number; - branchId?: number; - userId?: number; + orderId?: number | string; + branchId?: number | string; + userId?: number | string; status?: string; + amount?: number | string; + sort?: PaymentSortField; + order?: PaymentSortOrder; search?: string; page?: number; limit?: number; @@ -56,6 +62,44 @@ export interface OnlinePaymentListResponse { items: OnlinePayment[]; } +// ─── Payment Detail Types ─────────────────────────────────────────────────── + +export interface GatewayResponse { + errorCode?: string; + errorMessage?: string; + [key: string]: unknown; +} + +export interface OnlinePaymentDetail { + id: number; + orderId: number; + orderNumber?: string; + orderUniqueId?: string; + type: string; + branchId: number; + branchName: LocalizedText; + passportName: string; + passportSurname: string; + userId: number; + paid: boolean; + amountTmt: number; + bankFeeTmt: number; + gbusFeeTmt: number; + totalAmountTmt: number; + amountMinor?: number; + amountUsd?: number; + exchangeRateUsd?: number; + paymentPeriod?: string; + gatewayStatus: string; + apiClient?: string; + description?: string; + createdById?: number; + createdByName?: string; + createdAt: string; + updatedAt: string; + gatewayResponse?: GatewayResponse; +} + // ─── Detail / History Step Types ───────────────────────────────────────────── export interface PaymentHistoryStep { @@ -73,16 +117,19 @@ export interface PaymentHistoryStep { /** * GET /payment-history * Returns paginated list of online payment records. - * Query params: order_id, branch_id, user_id, status, search, page, limit + * Query params: order_id, branch_id, user_id, status, amount, sort, order, search, page, limit */ export async function fetchOnlinePayments(params: OnlinePaymentListParams = {}): Promise { - const { orderId, branchId, userId, status, search, page, limit } = params; + const { orderId, branchId, userId, status, amount, sort, order, search, page, limit } = params; const { data } = await apiClient.get("/payment-history", { params: { order_id: orderId || undefined, branch_id: branchId || undefined, user_id: userId || undefined, status: status || undefined, + amount: amount || undefined, + sort: sort || undefined, + order: order || undefined, search: search || undefined, page: page ?? 1, limit: limit ?? 25, @@ -99,3 +146,64 @@ export async function fetchOnlinePaymentById(id: number): Promise(`/payment-history/${id}`); return data; } + +/** + * GET /payment-history/payments/:id + * Returns a single payment's detailed information. + */ +export async function fetchOnlinePaymentDetail(id: number | string): Promise { + const { data } = await apiClient.get(`/payment-history/payments/${id}`); + return data; +} + +/** + * GET /payment-history/:id + * Returns paginated payment history for a specific order. + * Query params: page, limit + */ +export async function fetchOrderPaymentHistory( + orderId: number | string, + params: { page?: number; limit?: number } = {}, +): Promise { + const { page, limit } = params; + const { data } = await apiClient.get(`/payment-history/${orderId}`, { + params: { + page: page ?? 1, + limit: limit ?? 25, + }, + }); + + if (Array.isArray(data)) { + return { count: data.length, items: data }; + } + if (data && Array.isArray(data.items)) { + return { count: data.count ?? data.items.length, items: data.items }; + } + return { count: 0, items: [] }; +} + +export interface PaymentGatewayData { + id: number; + orderId: number; + cardholderName: string | null; + maskedPan: string | null; + paymentYear: number | null; + paymentMonth: number | null; + createdAt: string; + amountUsd: number | null; + amountTmt: number | null; + orderNumber: string | null; + paid: boolean; + gatewayStatus: string; + gatewayResponse?: GatewayResponse; + [key: string]: unknown; +} + +/** + * GET /payment-history/payments/:id/gateway + * Returns payment gateway details for a specific payment. + */ +export async function fetchPaymentGateway(id: number | string): Promise { + const { data } = await apiClient.get(`/payment-history/payments/${id}/gateway`); + return data; +} diff --git a/src/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory.ts b/src/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory.ts index f28ace8..e4fae64 100644 --- a/src/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory.ts +++ b/src/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory.ts @@ -1,7 +1,14 @@ // features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory.ts import { useQuery } from "@tanstack/react-query"; -import { fetchOnlinePayments, fetchOnlinePaymentById, type OnlinePaymentListParams } from "../api/onlinePaymentsHistoryApi"; +import { + fetchOnlinePayments, + fetchOnlinePaymentById, + fetchOnlinePaymentDetail, + fetchOrderPaymentHistory, + fetchPaymentGateway, + type OnlinePaymentListParams, +} from "../api/onlinePaymentsHistoryApi"; // ─── Query Keys ─────────────────────────────────────────────────────────────── @@ -9,15 +16,20 @@ export const onlinePaymentKeys = { all: ["onlinePayments"] as const, lists: () => [...onlinePaymentKeys.all, "list"] as const, list: (params: OnlinePaymentListParams) => [...onlinePaymentKeys.lists(), params] as const, - detail: (id: number) => [...onlinePaymentKeys.all, "detail", id] as const, + detail: (id: number | string) => [...onlinePaymentKeys.all, "detail", String(id)] as const, + paymentDetail: (id: number | string) => [...onlinePaymentKeys.all, "paymentDetail", String(id)] as const, + paymentGateway: (id: number | string) => [...onlinePaymentKeys.all, "paymentGateway", String(id)] as const, + orderHistory: (id: number | string, params: Record) => + [...onlinePaymentKeys.all, "orderHistory", String(id), params] as const, }; // ─── useGetOnlinePayments ───────────────────────────────────────────────────── -export function useGetOnlinePayments(params: OnlinePaymentListParams = {}) { +export function useGetOnlinePayments(params: OnlinePaymentListParams = {}, options?: { enabled?: boolean }) { return useQuery({ queryKey: onlinePaymentKeys.list(params), queryFn: () => fetchOnlinePayments(params), + enabled: options?.enabled ?? true, }); } @@ -27,10 +39,49 @@ export function useGetOnlinePayments(params: OnlinePaymentListParams = {}) { * Fetches the step-by-step history log for a single payment order. * Returns an array of PaymentHistoryStep. */ -export function useGetOnlinePaymentById(id: number) { +export function useGetOnlinePaymentById(id: number | string) { return useQuery({ queryKey: onlinePaymentKeys.detail(id), - queryFn: () => fetchOnlinePaymentById(id), + queryFn: () => fetchOnlinePaymentById(Number(id)), enabled: !!id, }); } + +// ─── useGetOnlinePaymentDetail ──────────────────────────────────────────────── + +/** + * Fetches the detailed payment record from /payment-history/payments/:id + */ +export function useGetOnlinePaymentDetail(id: number | string) { + return useQuery({ + queryKey: onlinePaymentKeys.paymentDetail(id), + queryFn: () => fetchOnlinePaymentDetail(id), + enabled: !!id, + }); +} + +// ─── useGetOrderPaymentHistory ──────────────────────────────────────────────── + +/** + * Fetches the paginated payment history for a specific order /payment-history/:id + */ +export function useGetOrderPaymentHistory(orderId: number | string | undefined, params: { page?: number; limit?: number } = {}) { + return useQuery({ + queryKey: onlinePaymentKeys.orderHistory(orderId ?? "", params), + queryFn: () => fetchOrderPaymentHistory(orderId!, params), + enabled: Boolean(orderId), + }); +} + +// ─── useGetPaymentGateway ───────────────────────────────────────────────────── + +/** + * Fetches payment gateway details from /payment-history/payments/:id/gateway + */ +export function useGetPaymentGateway(id: number | string | undefined) { + return useQuery({ + queryKey: onlinePaymentKeys.paymentGateway(id ?? ""), + queryFn: () => fetchPaymentGateway(id!), + enabled: Boolean(id), + }); +} diff --git a/src/features/visaMasterPayments/components/PaymentDetailDialog.tsx b/src/features/visaMasterPayments/components/PaymentDetailDialog.tsx new file mode 100644 index 0000000..4040af2 --- /dev/null +++ b/src/features/visaMasterPayments/components/PaymentDetailDialog.tsx @@ -0,0 +1,202 @@ +import { Link } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { Database, AlertTriangle } from "lucide-react"; + +import { Skeleton } from "@/components/ui/skeleton"; +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"; +import { useGetOnlinePaymentDetail } from "@/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory"; +import { GatewayStatusBadge, PaidBadge } from "@/features/onlinePaymentHistory/components/PaymentStatusBadge"; +import { formatFromApiDate } from "@/lib/utils/dateUtils"; + +function resolveLang(lang: string): "en" | "ru" | "tm" { + if (lang === "ru") return "ru"; + if (lang === "tk") return "tm"; + return "en"; +} + +interface PaymentDetailDialogProps { + paymentId: number | null; + open: boolean; + onOpenChange: (open: boolean) => void; +} + +export function PaymentDetailDialog({ paymentId, open, onOpenChange }: PaymentDetailDialogProps) { + const { t, i18n } = useTranslation(); + const lang = resolveLang(i18n.language); + const { data, isLoading, isError } = useGetOnlinePaymentDetail(paymentId ?? 0); + + return ( + + + +
+
+ + + {t("onlinePayments.paymentViewTitle", "Töleg maglumaty")}: #{paymentId} + +
+ {data && ( +
+ + +
+ )} +
+ {data?.orderNumber && ( + + {t("onlinePayments.columns.orderNumber", "Sargyt belgisi")}: {data.orderNumber} + + )} +
+ + {isLoading ? ( +
+ +
+ + +
+ +
+ ) : isError || !data ? ( +
{t("common.error", "Maglumat ýüklenende ýalňyşlyk ýüze çykdy")}
+ ) : ( +
+ {/* Gateway Response Alert if Error */} + {data.gatewayResponse && (data.gatewayResponse.errorCode || data.gatewayResponse.errorMessage) && ( +
+ +
+
+ Gateway ýalňyşlygy {data.gatewayResponse.errorCode ? `(${data.gatewayResponse.errorCode})` : ""} +
+ {data.gatewayResponse.errorMessage &&
{data.gatewayResponse.errorMessage}
} +
+
+ )} + + {/* Grid 1: General Info */} +
+

+ {t("onlinePayments.sectionGeneral", "Esasy maglumatlar")} +

+
+
+ {t("common.id", "ID")} + {data.id} +
+
+ {t("onlinePayments.columns.orderId", "Sargyt ID")} + + #{data.orderId} + +
+
+ {t("onlinePayments.columns.orderNumber", "Sargyt belgisi")} + {data.orderNumber || "—"} +
+
+ {t("onlinePayments.columns.type", "Görnüşi")} + {data.type} +
+ {data.description && ( +
+ {t("onlinePayments.columns.description", "Düşündiriş")} + {data.description} +
+ )} +
+ {t("onlinePayments.columns.createdAt", "Döredilen wagty")} + {formatFromApiDate(data.createdAt)} +
+
+ {t("onlinePayments.columns.updatedAt", "Täzelenen wagty")} + {formatFromApiDate(data.updatedAt)} +
+
+
+ + {/* Grid 2: Financial Info */} +
+

+ {t("onlinePayments.sectionFinancial", "Maliýe maglumatlary")} +

+
+
+ {t("onlinePayments.columns.amountTmt", "Töleg möçberi")} + {data.amountTmt?.toLocaleString?.() ?? data.amountTmt} TMT +
+
+ {t("onlinePayments.columns.totalAmount", "Jemi töleg möçberi")} + {data.totalAmountTmt?.toLocaleString?.() ?? data.totalAmountTmt} TMT +
+
+ {t("onlinePayments.columns.bankFeeTmt", "Bank komissiýasy")} + {data.bankFeeTmt?.toLocaleString?.() ?? data.bankFeeTmt} TMT +
+
+ {t("onlinePayments.columns.gbusFeeTmt", "GBUS komissiýasy")} + {data.gbusFeeTmt?.toLocaleString?.() ?? data.gbusFeeTmt} TMT +
+ {data.amountUsd != null && ( +
+ {t("onlinePayments.columns.amountUsd", "Möçber (USD)")} + {data.amountUsd} $ +
+ )} + {data.exchangeRateUsd != null && ( +
+ {t("onlinePayments.columns.exchangeRateUsd", "Hümmet (USD)")} + {data.exchangeRateUsd} TMT +
+ )} + {data.paymentPeriod && ( +
+ {t("onlinePayments.columns.paymentPeriod", "Töleg döwri")} + {formatFromApiDate(data.paymentPeriod)} +
+ )} + {data.apiClient && ( +
+ {t("onlinePayments.columns.apiClient", "API Client")} + {data.apiClient} +
+ )} +
+
+ + {/* Grid 3: Customer & Branch */} +
+

+ {t("onlinePayments.sectionCustomer", "Müşderi we Şahamça")} +

+
+
+ {t("onlinePayments.columns.passport", "Müşderi")} + + {[data.passportName, data.passportSurname].filter(Boolean).join(" ") || "—"} + +
+
+ {t("onlinePayments.columns.userId", "Ulanyjy ID")} + + #{data.userId} + +
+
+ {t("onlinePayments.columns.branch", "Şahamça")} + {data.branchName?.[lang] || data.branchName?.tm || data.branchName?.en || "—"} +
+
+ {t("onlinePayments.columns.createdByName", "Döreden işgär")} + {data.createdByName || "—"} +
+
+
+
+ )} +
+
+ ); +} diff --git a/src/features/visaMasterPayments/components/PaymentHistoryTable.tsx b/src/features/visaMasterPayments/components/PaymentHistoryTable.tsx index b9e6c06..01c8683 100644 --- a/src/features/visaMasterPayments/components/PaymentHistoryTable.tsx +++ b/src/features/visaMasterPayments/components/PaymentHistoryTable.tsx @@ -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(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([{ 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({}); + const [columnOrder, setColumnOrder] = useState([]); - 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[] = 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: navigates to audit/history step timeline */} + +
+ ), + 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 ( -
- {/* Search */} -
- +
+ {/* ── 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); + }} + /> + } + /> - 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 - " - /> -
- - {/* Loading */} - {isLoading ? ( -
- {[...Array(4)].map((_, index) => ( - - ))} -
- ) : isError ? ( - /* Error */ -
- {t("paymentHistory.loadError", "Töleg taryhyny ýüklemek başartmady")} -
- ) : rows.length === 0 ? ( - /* Empty */ -
-
- - - - - -
- -

{t("paymentHistory.empty", "Berlen kriteriýalara Töleg gabat gelmedi.")}

-
- ) : ( - /* Table */ -
- - - - - - - - - - - - - - - - - {rows.map((row) => { - const entries = detailEntries(row.detail); - - return ( - - {/* ID */} - - - {/* Step */} - - - {/* Details */} - - - {/* Created By */} - - - {/* Created At */} - - - ); - })} - -
{t("paymentHistory.col.id", "ID")}{t("paymentHistory.col.step", "Ädim")}{t("paymentHistory.col.detail", "Jikme-jiklik")}{t("paymentHistory.col.createdBy", "Kim tarapyndan")}{t("paymentHistory.col.createdAt", "Wagty")}
{row.id}{t(`paymentHistory.steps.${row.step}`, row.step)} - {entries.length === 0 ? ( - — - ) : ( -
- {entries.map(([key, value]) => ( -
-
{key}
- -
{value}
-
- ))} -
- )} -
{row.createdByName || "—"}{formatDateTime(row.createdAt)}
-
- )} + {/* ── Payment Detail Dialog (Triggered on clicking storage icon) ────────── */} + { + if (!open) setSelectedPaymentId(null); + }} + />
); } diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 298b2c5..f3bbb0f 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -679,6 +679,7 @@ "cardOrder.filter.cardTypeId": "Card type", "cardOrder.filter.region": "Region", "cardOrder.filter.status": "Status", + "cardOrder.filter.user": "User", "cardOrder.filter.userId": "User ID", "cardOrder.field.name": "Card holder name", "cardOrder.field.number": "Card number", @@ -1408,6 +1409,17 @@ "intlPayment.kabulDocsSection": "Receiver student documents", "intlPayment.upgradDocsSection": "Upgrade documents", "intlPayment.paymentHistory": "Payment history", + "intlPayment.historyColumns.id": "ID", + "intlPayment.historyColumns.payerFullName": "Payer Full Name", + "intlPayment.historyColumns.maskedCard": "Payer Card (Mask)", + "intlPayment.historyColumns.paymentYear": "Payment Year", + "intlPayment.historyColumns.paymentMonth": "Payment Month", + "intlPayment.historyColumns.transactionTime": "Transaction Time", + "intlPayment.historyColumns.amount": "Transaction Amount", + "intlPayment.historyColumns.amountTmt": "Amount (TMT)", + "intlPayment.historyColumns.reference": "Transaction Reference", + "intlPayment.historyColumns.isPaid": "Paid", + "intlPayment.historyColumns.isSynced": "Synced with system", "intlPayment.search": "Search", "intlPayment.noHistory": "No payment history matching criteria.", "intlPayment.deleteTitle": "Are you sure you want to delete?", @@ -1596,6 +1608,8 @@ "onlinePayments.gatewayStatus.paid": "Paid", "onlinePayments.gatewayStatus.unpaid": "Unpaid", "onlinePayments.gatewayStatus.failed": "Failed", + "onlinePayments.gatewayStatus.success": "Success", + "onlinePayments.gatewayStatus.completed": "Completed", "onlinePayments.paid.paid": "Paid", "onlinePayments.paid.unpaid": "Unpaid", "onlinePayments.detail.stepsCount": "Steps", diff --git a/src/lib/i18n/locales/ru.json b/src/lib/i18n/locales/ru.json index 599586e..9ae76ce 100644 --- a/src/lib/i18n/locales/ru.json +++ b/src/lib/i18n/locales/ru.json @@ -679,6 +679,7 @@ "cardOrder.filter.cardTypeId": "Тип карты", "cardOrder.filter.region": "Регион", "cardOrder.filter.status": "Статус", + "cardOrder.filter.user": "Пользователь", "cardOrder.filter.userId": "ID пользователя", "cardOrder.field.name": "Имя держателя карты", "cardOrder.field.number": "Номер карты", @@ -1409,6 +1410,17 @@ "intlPayment.kabulDocsSection": "Документы студента-получателя", "intlPayment.upgradDocsSection": "Документы Upgrade", "intlPayment.paymentHistory": "История платежей", + "intlPayment.historyColumns.id": "ID", + "intlPayment.historyColumns.payerFullName": "Ф.И.О. плательщика", + "intlPayment.historyColumns.maskedCard": "Номер карты плательщика (маска)", + "intlPayment.historyColumns.paymentYear": "Год оплаты", + "intlPayment.historyColumns.paymentMonth": "Месяц оплаты", + "intlPayment.historyColumns.transactionTime": "Время операции", + "intlPayment.historyColumns.amount": "Сумма операции", + "intlPayment.historyColumns.amountTmt": "Сумма в манатах", + "intlPayment.historyColumns.reference": "Референс операции", + "intlPayment.historyColumns.isPaid": "Оплачено", + "intlPayment.historyColumns.isSynced": "Синхронизировано с системой", "intlPayment.search": "Поиск", "intlPayment.noHistory": "Платежей по заданным критериям не найдено.", "intlPayment.deleteTitle": "Вы уверены, что хотите удалить?", @@ -1597,6 +1609,8 @@ "onlinePayments.gatewayStatus.paid": "Оплачено", "onlinePayments.gatewayStatus.unpaid": "Не оплачено", "onlinePayments.gatewayStatus.failed": "Ошибка", + "onlinePayments.gatewayStatus.success": "Успешно", + "onlinePayments.gatewayStatus.completed": "Завершено", "onlinePayments.paid.paid": "Оплачено", "onlinePayments.paid.unpaid": "Не оплачено", "onlinePayments.detail.stepsCount": "Шаги", diff --git a/src/lib/i18n/locales/tk.json b/src/lib/i18n/locales/tk.json index 492e99a..54c85c3 100644 --- a/src/lib/i18n/locales/tk.json +++ b/src/lib/i18n/locales/tk.json @@ -678,6 +678,7 @@ "cardOrder.filter.cardTypeId": "Kart görnüşi", "cardOrder.filter.region": "Sebit", "cardOrder.filter.status": "Status", + "cardOrder.filter.user": "Ulanyjy", "cardOrder.filter.userId": "Ulanyjy ID", "cardOrder.field.name": "Kart eýesiniň ady", "cardOrder.field.number": "Kart belgisi", @@ -1407,6 +1408,17 @@ "intlPayment.kabulDocsSection": "Kabul ediji talyp boyunca resminamalar", "intlPayment.upgradDocsSection": "Upgradyý boyunca resminamalar", "intlPayment.paymentHistory": "Töleg taryhy", + "intlPayment.historyColumns.id": "ID", + "intlPayment.historyColumns.payerFullName": "Amaly geçiren raýatyň F.A.A.", + "intlPayment.historyColumns.maskedCard": "Amaly geçiren raýatyň kart belgisi (mask)", + "intlPayment.historyColumns.paymentYear": "Töleg ýyly", + "intlPayment.historyColumns.paymentMonth": "Töleg aýy", + "intlPayment.historyColumns.transactionTime": "Amalyň geçirilen wagty", + "intlPayment.historyColumns.amount": "Amalyň möçberi", + "intlPayment.historyColumns.amountTmt": "Amalyň manat möçberi", + "intlPayment.historyColumns.reference": "Amalyň referensi", + "intlPayment.historyColumns.isPaid": "Tölenen", + "intlPayment.historyColumns.isSynced": "Ulgam bn birikdirilen", "intlPayment.search": "Gözlemek", "intlPayment.noHistory": "Beriilen kriteriýalara Töleg gabat gelmedi", "intlPayment.deleteTitle": "Pozmak isleýärsiňizmi?", @@ -1595,6 +1607,8 @@ "onlinePayments.gatewayStatus.paid": "Tölendi", "onlinePayments.gatewayStatus.unpaid": "Tölenmedi", "onlinePayments.gatewayStatus.failed": "Ýalňyşlyk", + "onlinePayments.gatewayStatus.success": "Şowly", + "onlinePayments.gatewayStatus.completed": "Tamamlandy", "onlinePayments.paid.paid": "Tölendi", "onlinePayments.paid.unpaid": "Tölenmedi", "onlinePayments.detail.stepsCount": "Ädimler", diff --git a/src/pages/cardDepartment/orderNewCard/index.tsx b/src/pages/cardDepartment/orderNewCard/index.tsx index 9b519ec..1d3c649 100644 --- a/src/pages/cardDepartment/orderNewCard/index.tsx +++ b/src/pages/cardDepartment/orderNewCard/index.tsx @@ -13,6 +13,7 @@ import { useCards, useDeleteCard } from "@/features/orderNewCard/hooks/useOrderN import type { CardOrder } from "@/features/orderNewCard/api/orderNewCardApi"; import { useInfiniteBranches } from "@/features/branches/hooks/useBranches"; import { useInfiniteCardTypes } from "@/features/cardTypes/hooks/useCardTypes"; +import { useInfiniteClients } from "@/features/clients/hooks/useClients"; import type { LocalizedText } from "@/features/branches/api/branchesApi"; import { getStatusOptions, getRegionOptions, StatusCell, ActiveStatusCell } from "@/constants"; import { formatFromApiDate } from "@/lib/utils/dateUtils"; @@ -55,9 +56,11 @@ export default function CardOrdersPage() { const [filterEnabled, setFilterEnabled] = useState(false); const [branchSearch, setBranchSearch] = useState(""); const [cardTypeSearch, setCardTypeSearch] = useState(""); + const [userSearch, setUserSearch] = useState(""); const isBranchFilterEnabled = filterEnabled || Boolean(getFilter("branch_id")); const isCardTypeFilterEnabled = filterEnabled || Boolean(getFilter("card_type_id")); + const isUserFilterEnabled = filterEnabled || Boolean(getFilter("user_id")); const { data: branchesInfiniteData, @@ -75,6 +78,14 @@ export default function CardOrdersPage() { isLoading: isCardTypesLoading, } = useInfiniteCardTypes(cardTypeSearch, isCardTypeFilterEnabled); + const { + data: usersData, + fetchNextPage: fetchNextUsers, + hasNextPage: hasNextUsers, + isFetchingNextPage: isFetchingNextUsers, + isLoading: isUsersLoading, + } = useInfiniteClients(userSearch, isUserFilterEnabled); + const queryParams = useMemo( () => ({ search: search || undefined, @@ -251,6 +262,17 @@ export default function CardOrdersPage() { [cardTypesInfiniteData, lang], ); + const userOptions = useMemo( + () => + (usersData?.pages ?? []).flatMap((page) => + (page?.users ?? []).map((u) => ({ + value: String(u.id), + label: u.name || u.username || String(u.id), + })), + ), + [usersData], + ); + // ── Filter fields ────────────────────────────────────────────────────────── const filterFields = useMemo( () => [ @@ -278,8 +300,15 @@ export default function CardOrdersPage() { }, { id: "user_id", - label: t("cardOrder.filter.userId", "Ulanyjy ID"), - type: "text", + label: t("cardOrder.filter.user", "Ulanyjy"), + type: "infinite-select", + options: userOptions, + loading: isUsersLoading, + isLoadingMore: isFetchingNextUsers, + hasNextPage: hasNextUsers, + onLoadMore: fetchNextUsers, + searchValue: userSearch, + onSearchChange: setUserSearch, }, { id: "card_state_id", @@ -312,6 +341,12 @@ export default function CardOrdersPage() { isFetchingNextCardTypes, hasNextCardTypes, cardTypeSearch, + userOptions, + isUsersLoading, + isFetchingNextUsers, + hasNextUsers, + userSearch, + fetchNextUsers, ], ); diff --git a/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx b/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx index 5a073a6..d318406 100644 --- a/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx +++ b/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx @@ -338,7 +338,10 @@ export default function IntlPaymentViewPage() {
{/* Single history table */} - + ); diff --git a/src/pages/onlinePaymentsHistory/index.tsx b/src/pages/onlinePaymentsHistory/index.tsx index 7a9aff9..20e14f5 100644 --- a/src/pages/onlinePaymentsHistory/index.tsx +++ b/src/pages/onlinePaymentsHistory/index.tsx @@ -1,17 +1,17 @@ // pages/OnlinePaymentHistoryPage.tsx import { useState, useMemo, useCallback } from "react"; -import { useNavigate } from "react-router-dom"; +import { useNavigate, Link } from "react-router-dom"; import { useTranslation } from "react-i18next"; import { Eye } from "lucide-react"; import { Button } from "@/components/ui/button"; -import { DataTable, type ColumnDef } from "@/components/dataTable"; +import { DataTable, type ColumnDef, type SortingState } from "@/components/dataTable"; import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar"; import type { VisibilityState } from "@tanstack/react-table"; import { useGetOnlinePayments } from "@/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory"; -import type { OnlinePayment } from "@/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi"; +import type { OnlinePayment, PaymentSortField, PaymentSortOrder } from "@/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi"; import { GatewayStatusBadge, PaidBadge } from "../../features/onlinePaymentHistory/components/PaymentStatusBadge"; -import { getGatewayStatusOptions } from "@/constants/paymentStatus"; +import { getPaymentHistoryStatusOptions } from "@/constants/paymentStatus"; import { useInfiniteBranches } from "@/features/branches/hooks/useBranches"; // ─── Helpers ────────────────────────────────────────────────────────────────── @@ -79,6 +79,7 @@ export default function OnlinePaymentHistoryPage() { // ─── Column state const [columnVisibility, setColumnVisibility] = useState(DEFAULT_VISIBILITY); const [columnOrder, setColumnOrder] = useState([...DEFAULT_ORDER]); + const [sorting, setSorting] = useState([{ id: "createdAt", desc: true }]); // ─── Filters — fieldId matches query param name for easy mapping const [activeFilters, setActiveFilters] = useState([ @@ -86,6 +87,7 @@ export default function OnlinePaymentHistoryPage() { { fieldId: "branchId", value: "" }, { fieldId: "orderId", value: "" }, { fieldId: "userId", value: "" }, + { fieldId: "amount", value: "" }, ]); // ─── Branch infinite-select data @@ -115,7 +117,21 @@ export default function OnlinePaymentHistoryPage() { // ─── Derive query params from active filters const filterMap = useMemo(() => Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value])), [activeFilters]); - const gatewayStatusOptions = useMemo(() => getGatewayStatusOptions(t), [t]); + const gatewayStatusOptions = useMemo(() => getPaymentHistoryStatusOptions(t), [t]); + + const sortMap: Record = useMemo( + () => ({ + id: "id", + createdAt: "created_at", + gatewayStatus: "status", + totalAmountTmt: "amount", + }), + [], + ); + + const activeSort = sorting[0]; + const sortField: PaymentSortField = activeSort ? (sortMap[activeSort.id] ?? "created_at") : "created_at"; + const sortOrder: PaymentSortOrder = activeSort ? (activeSort.desc ? "desc" : "asc") : "desc"; const queryParams = useMemo( () => ({ @@ -126,8 +142,11 @@ export default function OnlinePaymentHistoryPage() { branchId: filterMap.branchId ? Number(filterMap.branchId) : undefined, orderId: filterMap.orderId ? Number(filterMap.orderId) : undefined, userId: filterMap.userId ? Number(filterMap.userId) : undefined, + amount: filterMap.amount || undefined, + sort: sortField, + order: sortOrder, }), - [page, perPage, search, filterMap], + [page, perPage, search, filterMap, sortField, sortOrder], ); const { data, isLoading } = useGetOnlinePayments(queryParams); @@ -179,6 +198,11 @@ export default function OnlinePaymentHistoryPage() { label: t("onlinePayments.filters.userId", "User ID"), type: "text", }, + { + id: "amount", + label: t("onlinePayments.filters.amount", "Möçber"), + type: "text", + }, ], [t, branchOptions, isBranchesLoading, isFetchingNextBranches, hasNextBranches, branchSearch, gatewayStatusOptions], ); @@ -190,8 +214,16 @@ export default function OnlinePaymentHistoryPage() { id: "id", accessorKey: "id", header: t(COLUMN_LABEL_KEYS.id, "ID"), - cell: ({ row }) => {row.original.id}, - size: 50, + cell: ({ row }) => ( + + {row.original.id} + + ), + size: 60, + enableSorting: true, }, { id: "orderId", @@ -199,6 +231,7 @@ export default function OnlinePaymentHistoryPage() { header: t(COLUMN_LABEL_KEYS.orderId, "ORDER ID"), cell: ({ row }) => {row.original.orderId}, size: 90, + enableSorting: false, }, { id: "type", @@ -206,6 +239,7 @@ export default function OnlinePaymentHistoryPage() { header: t(COLUMN_LABEL_KEYS.type, "TYPE"), cell: ({ row }) => {row.original.type}, size: 80, + enableSorting: false, }, { id: "branchName", @@ -217,6 +251,7 @@ export default function OnlinePaymentHistoryPage() { ), size: 200, + enableSorting: false, }, { id: "passport", @@ -228,6 +263,7 @@ export default function OnlinePaymentHistoryPage() { ), size: 150, + enableSorting: false, }, { id: "totalAmountTmt", @@ -235,6 +271,7 @@ export default function OnlinePaymentHistoryPage() { header: t(COLUMN_LABEL_KEYS.totalAmountTmt, "TOTAL (TMT)"), cell: ({ row }) => {row.original.totalAmountTmt.toLocaleString()}, size: 110, + enableSorting: true, }, { id: "gatewayStatus", @@ -242,6 +279,7 @@ export default function OnlinePaymentHistoryPage() { header: t(COLUMN_LABEL_KEYS.gatewayStatus, "GATEWAY STATUS"), cell: ({ row }) => , size: 140, + enableSorting: true, }, { id: "paid", @@ -249,6 +287,7 @@ export default function OnlinePaymentHistoryPage() { header: t(COLUMN_LABEL_KEYS.paid, "PAID"), cell: ({ row }) => , size: 90, + enableSorting: false, }, { id: "createdAt", @@ -258,6 +297,7 @@ export default function OnlinePaymentHistoryPage() { {formatDateTime(row.original.createdAt)} ), size: 140, + enableSorting: true, }, { id: "actions", @@ -270,7 +310,7 @@ export default function OnlinePaymentHistoryPage() { variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-foreground" - onClick={() => navigate(`/online-payments-history/${row.original.orderId}`)} + onClick={() => navigate(`/online-payments-history/payments/${row.original.id}`)} title={t("common.view", "Görmek")} > @@ -331,6 +371,9 @@ export default function OnlinePaymentHistoryPage() { onColumnOrderChange={setColumnOrder} enableRowSelection getRowId={(row) => String(row.id)} + sorting={sorting} + onSortingChange={setSorting} + manualSorting currentPage={page} totalPages={totalPages} totalCount={totalCount} diff --git a/src/pages/onlinePaymentsHistory/onlinePaymentDetailView.tsx b/src/pages/onlinePaymentsHistory/onlinePaymentDetailView.tsx new file mode 100644 index 0000000..f01c78b --- /dev/null +++ b/src/pages/onlinePaymentsHistory/onlinePaymentDetailView.tsx @@ -0,0 +1,241 @@ +import { useParams, useNavigate, Link } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { ArrowLeft, AlertTriangle } from "lucide-react"; + +import { Button } from "@/components/ui/button"; +import { Skeleton } from "@/components/ui/skeleton"; +import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents"; +import { GatewayStatusBadge, PaidBadge } from "@/features/onlinePaymentHistory/components/PaymentStatusBadge"; +import { useGetOnlinePaymentDetail, useGetOnlinePaymentById } from "@/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory"; +import { formatFromApiDate } from "@/lib/utils/dateUtils"; +import type { PaymentHistoryStep } from "@/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi"; +import { rawEnumKey, type TranslateFn } from "@/constants/enumLabels"; + +function formatDateTime(iso: string | null | undefined): string { + if (!iso) return "—"; + return formatFromApiDate(iso); +} + +function resolveLang(lang: string): "en" | "ru" | "tm" { + if (lang === "ru") return "ru"; + if (lang === "tk") return "tm"; + return "en"; +} + +function detailKeyLabel(key: string, t: TranslateFn): string { + return t(`onlinePayments.detailKeys.${key}`, rawEnumKey(key)); +} + +function StepTimelineRow({ step }: { step: PaymentHistoryStep }) { + const { t } = useTranslation(); + const detailEntries = Object.entries(step.detail ?? {}); + + return ( +
+
+
+
+
+ +
+
+ + {formatDateTime(step.createdAt)} + {step.createdByName} +
+ + {detailEntries.length > 0 && ( +
+ {detailEntries.map(([key, value]) => ( +
+ {detailKeyLabel(key, t)} + {String(value)} +
+ ))} +
+ )} +
+
+ ); +} + +export default function OnlinePaymentDetailViewPage() { + const { id } = useParams<{ id: string }>(); + const navigate = useNavigate(); + const { t, i18n } = useTranslation(); + const lang = resolveLang(i18n.language); + + const { data, isLoading, isError } = useGetOnlinePaymentDetail(id!); + const { data: steps } = useGetOnlinePaymentById(data?.orderId ?? (data?.id || 0)); + + if (isLoading) { + return ( +
+ +
+ + +
+
+ ); + } + + if (isError || !data) { + return ( +
+

{t("common.notFound", "Maglumat tapylmady")}

+ +
+ ); + } + + const branchName = data.branchName?.[lang] || data.branchName?.tm || data.branchName?.en || "—"; + const fullName = [data.passportName, data.passportSurname].filter(Boolean).join(" "); + + return ( +
+ {/* ── Page Header ──────────────────────────────────────────────────────── */} +
+
+ +
+
+

+ {t("onlinePayments.paymentViewTitle", "Töleg maglumaty")}: #{data.id} +

+ + +
+ {data.orderNumber && ( +

+ {t("onlinePayments.columns.orderNumber", "Sargyt belgisi")}: {data.orderNumber} +

+ )} +
+
+ + {data.orderId && ( + + )} +
+ + {/* ── Error / Alert (if gateway response error exists) ─────────────────── */} + {data.gatewayResponse && (data.gatewayResponse.errorCode || data.gatewayResponse.errorMessage) && ( +
+ +
+
+ Gateway Ýalňyşlygy {data.gatewayResponse.errorCode ? `(Kod: ${data.gatewayResponse.errorCode})` : ""} +
+ {data.gatewayResponse.errorMessage &&
{data.gatewayResponse.errorMessage}
} +
+
+ )} + + {/* ── Row 1: General & Financial Information ───────────────────────────── */} + + + + + + + + {data.type} + + + + + + + + + + + + + + + + + + {data.totalAmountTmt?.toLocaleString?.() ?? data.totalAmountTmt} TMT + + + + + + + + + {/* ── Row 2: Customer & Branch Information ─────────────────────────────── */} + + + + + + + + + + + + + + {/* ── Row 3: Step-by-Step History Log (Timeline) ───────────────────────── */} + {steps && steps.length > 0 && ( + +
+ {steps.map((step) => ( + + ))} +
+
+ )} +
+ ); +}