changed payment history api in visa/master payments
This commit is contained in:
@@ -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") },
|
||||
|
||||
@@ -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
|
||||
<PaginationItem>
|
||||
<PaginationPrevious
|
||||
href="#"
|
||||
text={t("pagination.previous", t("Previous", "Öňki"))}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
if (currentPage > 1) onPageChange(currentPage - 1);
|
||||
@@ -93,6 +96,7 @@ function DataTablePagination({ currentPage, totalPages, onPageChange }: DataTabl
|
||||
<PaginationItem>
|
||||
<PaginationNext
|
||||
href="#"
|
||||
text={t("pagination.next", t("Next", "Indiki"))}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
if (currentPage < totalPages) onPageChange(currentPage + 1);
|
||||
@@ -223,6 +227,11 @@ interface DataTableProps<TData> {
|
||||
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<TData>({
|
||||
enableRowSelection = false,
|
||||
onRowSelectionChange,
|
||||
getRowId,
|
||||
sorting,
|
||||
onSortingChange,
|
||||
manualSorting,
|
||||
currentPage = 1,
|
||||
totalPages = 1,
|
||||
totalCount,
|
||||
@@ -252,7 +264,10 @@ export function DataTable<TData>({
|
||||
headerContent,
|
||||
toolbar,
|
||||
}: DataTableProps<TData>) {
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [internalSorting, setInternalSorting] = useState<SortingState>([]);
|
||||
const effectiveSorting = sorting !== undefined ? sorting : internalSorting;
|
||||
const effectiveOnSortingChange = onSortingChange !== undefined ? onSortingChange : setInternalSorting;
|
||||
|
||||
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
|
||||
// Tracks whether ALL records (across pages) are logically selected
|
||||
const [allTotalSelected, setAllTotalSelected] = useState(false);
|
||||
@@ -338,11 +353,12 @@ export function DataTable<TData>({
|
||||
data,
|
||||
columns: allColumns,
|
||||
state: {
|
||||
sorting,
|
||||
sorting: effectiveSorting,
|
||||
rowSelection,
|
||||
columnVisibility: columnVisibility ?? {},
|
||||
columnOrder: effectiveColumnOrder,
|
||||
},
|
||||
manualSorting,
|
||||
getRowId,
|
||||
enableRowSelection,
|
||||
onRowSelectionChange: (updater) => {
|
||||
@@ -357,7 +373,7 @@ export function DataTable<TData>({
|
||||
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<TData>({
|
||||
onColumnOrderChange(next);
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getSortedRowModel: manualSorting ? undefined : getSortedRowModel(),
|
||||
});
|
||||
|
||||
// ── Selection banner ────────────────────────────────────────────────────────
|
||||
@@ -409,21 +425,38 @@ export function DataTable<TData>({
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id} className="bg-muted/40 hover:bg-muted/40">
|
||||
{headerGroup.headers.map((header) => (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
style={{
|
||||
width: header.getSize() !== 150 ? header.getSize() : undefined,
|
||||
}}
|
||||
className={cn(
|
||||
"text-xs font-semibold text-muted-foreground uppercase tracking-wider whitespace-nowrap",
|
||||
header.column.getCanSort() && "cursor-pointer select-none",
|
||||
)}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
))}
|
||||
{headerGroup.headers.map((header) => {
|
||||
const canSort = header.column.getCanSort();
|
||||
const sortDir = header.column.getIsSorted();
|
||||
return (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
style={{
|
||||
width: header.getSize() !== 150 ? header.getSize() : undefined,
|
||||
}}
|
||||
className={cn(
|
||||
"text-xs font-semibold text-muted-foreground uppercase tracking-wider whitespace-nowrap",
|
||||
canSort && "cursor-pointer select-none hover:text-foreground",
|
||||
)}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
>
|
||||
<div className="flex items-center gap-1.5">
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
{canSort && (
|
||||
<span className="inline-flex shrink-0">
|
||||
{sortDir === "asc" ? (
|
||||
<ArrowUp className="size-3 text-primary" />
|
||||
) : sortDir === "desc" ? (
|
||||
<ArrowDown className="size-3 text-primary" />
|
||||
) : (
|
||||
<ArrowUpDown className="size-3 text-muted-foreground/30" />
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</TableHead>
|
||||
);
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
|
||||
@@ -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<GatewayStatusValue, string> = {
|
||||
paid: "Paid",
|
||||
unpaid: "Unpaid",
|
||||
failed: "Failed",
|
||||
success: "Success",
|
||||
completed: "Completed",
|
||||
};
|
||||
|
||||
const GATEWAY_STATUS_ENUM: EnumConfig<GatewayStatusValue> = {
|
||||
@@ -28,6 +30,8 @@ export const GATEWAY_STATUS_BADGE_VARIANTS: Record<GatewayStatusValue, StatusBad
|
||||
paid: "success",
|
||||
unpaid: "default",
|
||||
failed: "error",
|
||||
success: "success",
|
||||
completed: "info",
|
||||
};
|
||||
|
||||
export const GATEWAY_STATUS_ICONS: Record<GatewayStatusValue, ComponentType> = {
|
||||
@@ -35,6 +39,8 @@ export const GATEWAY_STATUS_ICONS: Record<GatewayStatusValue, ComponentType> = {
|
||||
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";
|
||||
}
|
||||
|
||||
@@ -22,13 +22,21 @@ export function StatusCell({ status, prefix = "status", fallbackLabels, fallback
|
||||
return <StatusBadge label={label} variant={variant} />;
|
||||
}
|
||||
|
||||
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 (
|
||||
<StatusBadge
|
||||
label={active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
|
||||
variant={active ? "success" : "default"}
|
||||
icon={active ? CheckCircle2 : XCircle}
|
||||
label={isActive ? (labelActive ?? t("common.active", "Işjeň")) : (labelInactive ?? t("common.inactive", "Işjeň däl"))}
|
||||
variant={isActive ? "success" : "default"}
|
||||
icon={isActive ? CheckCircle2 : XCircle}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<OnlinePaymentListResponse> {
|
||||
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<OnlinePaymentListResponse>("/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<PaymentHistory
|
||||
const { data } = await apiClient.get<PaymentHistoryStep[]>(`/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<OnlinePaymentDetail> {
|
||||
const { data } = await apiClient.get<OnlinePaymentDetail>(`/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<OnlinePaymentListResponse> {
|
||||
const { page, limit } = params;
|
||||
const { data } = await apiClient.get<any>(`/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<PaymentGatewayData> {
|
||||
const { data } = await apiClient.get<any>(`/payment-history/payments/${id}/gateway`);
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -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<string, unknown>) =>
|
||||
[...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),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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 (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[85vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center justify-between gap-3 pr-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Database className="size-5 text-primary" />
|
||||
<DialogTitle className="text-base font-semibold">
|
||||
{t("onlinePayments.paymentViewTitle", "Töleg maglumaty")}: #{paymentId}
|
||||
</DialogTitle>
|
||||
</div>
|
||||
{data && (
|
||||
<div className="flex items-center gap-2">
|
||||
<GatewayStatusBadge status={data.gatewayStatus} />
|
||||
<PaidBadge paid={data.paid} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{data?.orderNumber && (
|
||||
<DialogDescription className="text-xs">
|
||||
{t("onlinePayments.columns.orderNumber", "Sargyt belgisi")}: {data.orderNumber}
|
||||
</DialogDescription>
|
||||
)}
|
||||
</DialogHeader>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-4 py-2">
|
||||
<Skeleton className="h-6 w-1/2" />
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Skeleton className="h-24 w-full rounded-lg" />
|
||||
<Skeleton className="h-24 w-full rounded-lg" />
|
||||
</div>
|
||||
<Skeleton className="h-28 w-full rounded-lg" />
|
||||
</div>
|
||||
) : isError || !data ? (
|
||||
<div className="py-8 text-center text-sm text-destructive">{t("common.error", "Maglumat ýüklenende ýalňyşlyk ýüze çykdy")}</div>
|
||||
) : (
|
||||
<div className="space-y-4 text-xs">
|
||||
{/* Gateway Response Alert if Error */}
|
||||
{data.gatewayResponse && (data.gatewayResponse.errorCode || data.gatewayResponse.errorMessage) && (
|
||||
<div className="flex items-start gap-2.5 p-3 rounded-lg border border-destructive/30 bg-destructive/10 text-destructive text-xs">
|
||||
<AlertTriangle className="size-4 shrink-0 mt-0.5" />
|
||||
<div className="space-y-0.5">
|
||||
<div className="font-semibold">
|
||||
Gateway ýalňyşlygy {data.gatewayResponse.errorCode ? `(${data.gatewayResponse.errorCode})` : ""}
|
||||
</div>
|
||||
{data.gatewayResponse.errorMessage && <div>{data.gatewayResponse.errorMessage}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Grid 1: General Info */}
|
||||
<div className="rounded-lg border border-border p-3 space-y-2 bg-muted/10">
|
||||
<p className="font-semibold text-muted-foreground uppercase text-[11px] tracking-wide">
|
||||
{t("onlinePayments.sectionGeneral", "Esasy maglumatlar")}
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-2">
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("common.id", "ID")}</span>
|
||||
<span className="font-mono font-medium text-foreground">{data.id}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.orderId", "Sargyt ID")}</span>
|
||||
<Link to={`/visa-master/${data.orderId}`} className="font-mono text-primary hover:underline">
|
||||
#{data.orderId}
|
||||
</Link>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.orderNumber", "Sargyt belgisi")}</span>
|
||||
<span className="font-mono text-foreground">{data.orderNumber || "—"}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.type", "Görnüşi")}</span>
|
||||
<span className="uppercase font-medium text-foreground">{data.type}</span>
|
||||
</div>
|
||||
{data.description && (
|
||||
<div className="col-span-2">
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.description", "Düşündiriş")}</span>
|
||||
<span className="text-foreground">{data.description}</span>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.createdAt", "Döredilen wagty")}</span>
|
||||
<span className="text-foreground">{formatFromApiDate(data.createdAt)}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.updatedAt", "Täzelenen wagty")}</span>
|
||||
<span className="text-foreground">{formatFromApiDate(data.updatedAt)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Grid 2: Financial Info */}
|
||||
<div className="rounded-lg border border-border p-3 space-y-2 bg-muted/10">
|
||||
<p className="font-semibold text-muted-foreground uppercase text-[11px] tracking-wide">
|
||||
{t("onlinePayments.sectionFinancial", "Maliýe maglumatlary")}
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-2">
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.amountTmt", "Töleg möçberi")}</span>
|
||||
<span className="font-medium text-foreground">{data.amountTmt?.toLocaleString?.() ?? data.amountTmt} TMT</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.totalAmount", "Jemi töleg möçberi")}</span>
|
||||
<span className="font-semibold text-primary">{data.totalAmountTmt?.toLocaleString?.() ?? data.totalAmountTmt} TMT</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.bankFeeTmt", "Bank komissiýasy")}</span>
|
||||
<span className="text-foreground">{data.bankFeeTmt?.toLocaleString?.() ?? data.bankFeeTmt} TMT</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.gbusFeeTmt", "GBUS komissiýasy")}</span>
|
||||
<span className="text-foreground">{data.gbusFeeTmt?.toLocaleString?.() ?? data.gbusFeeTmt} TMT</span>
|
||||
</div>
|
||||
{data.amountUsd != null && (
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.amountUsd", "Möçber (USD)")}</span>
|
||||
<span className="text-foreground">{data.amountUsd} $</span>
|
||||
</div>
|
||||
)}
|
||||
{data.exchangeRateUsd != null && (
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.exchangeRateUsd", "Hümmet (USD)")}</span>
|
||||
<span className="text-foreground">{data.exchangeRateUsd} TMT</span>
|
||||
</div>
|
||||
)}
|
||||
{data.paymentPeriod && (
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.paymentPeriod", "Töleg döwri")}</span>
|
||||
<span className="text-foreground">{formatFromApiDate(data.paymentPeriod)}</span>
|
||||
</div>
|
||||
)}
|
||||
{data.apiClient && (
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.apiClient", "API Client")}</span>
|
||||
<span className="font-mono text-foreground">{data.apiClient}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Grid 3: Customer & Branch */}
|
||||
<div className="rounded-lg border border-border p-3 space-y-2 bg-muted/10">
|
||||
<p className="font-semibold text-muted-foreground uppercase text-[11px] tracking-wide">
|
||||
{t("onlinePayments.sectionCustomer", "Müşderi we Şahamça")}
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-2">
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.passport", "Müşderi")}</span>
|
||||
<span className="font-medium text-foreground">
|
||||
{[data.passportName, data.passportSurname].filter(Boolean).join(" ") || "—"}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.userId", "Ulanyjy ID")}</span>
|
||||
<Link to={`/all-users/${data.userId}`} className="font-mono text-primary hover:underline">
|
||||
#{data.userId}
|
||||
</Link>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.branch", "Şahamça")}</span>
|
||||
<span className="text-foreground">{data.branchName?.[lang] || data.branchName?.tm || data.branchName?.en || "—"}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground block">{t("onlinePayments.columns.createdByName", "Döreden işgär")}</span>
|
||||
<span className="text-foreground">{data.createdByName || "—"}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "Шаги",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<FilterField[]>(
|
||||
() => [
|
||||
@@ -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,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -338,7 +338,10 @@ export default function IntlPaymentViewPage() {
|
||||
</div>
|
||||
|
||||
{/* Single history table */}
|
||||
<PaymentHistoryTable orderId={id} />
|
||||
<PaymentHistoryTable
|
||||
orderId={data.id}
|
||||
paymentId={(data as any).paymentId ?? (data as any).payment_id ?? (data as any).payment?.id}
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -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<VisibilityState>(DEFAULT_VISIBILITY);
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([...DEFAULT_ORDER]);
|
||||
const [sorting, setSorting] = useState<SortingState>([{ id: "createdAt", desc: true }]);
|
||||
|
||||
// ─── Filters — fieldId matches query param name for easy mapping
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
@@ -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<string, PaymentSortField> = 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 }) => <span className="tabular-nums text-foreground font-medium">{row.original.id}</span>,
|
||||
size: 50,
|
||||
cell: ({ row }) => (
|
||||
<Link
|
||||
to={`/online-payments-history/payments/${row.original.id}`}
|
||||
className="font-mono text-xs font-medium text-primary hover:underline"
|
||||
>
|
||||
{row.original.id}
|
||||
</Link>
|
||||
),
|
||||
size: 60,
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
id: "orderId",
|
||||
@@ -199,6 +231,7 @@ export default function OnlinePaymentHistoryPage() {
|
||||
header: t(COLUMN_LABEL_KEYS.orderId, "ORDER ID"),
|
||||
cell: ({ row }) => <span className="tabular-nums text-foreground font-medium">{row.original.orderId}</span>,
|
||||
size: 90,
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "type",
|
||||
@@ -206,6 +239,7 @@ export default function OnlinePaymentHistoryPage() {
|
||||
header: t(COLUMN_LABEL_KEYS.type, "TYPE"),
|
||||
cell: ({ row }) => <span className="text-xs font-semibold uppercase tracking-wide text-foreground">{row.original.type}</span>,
|
||||
size: 80,
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "branchName",
|
||||
@@ -217,6 +251,7 @@ export default function OnlinePaymentHistoryPage() {
|
||||
</span>
|
||||
),
|
||||
size: 200,
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "passport",
|
||||
@@ -228,6 +263,7 @@ export default function OnlinePaymentHistoryPage() {
|
||||
</span>
|
||||
),
|
||||
size: 150,
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "totalAmountTmt",
|
||||
@@ -235,6 +271,7 @@ export default function OnlinePaymentHistoryPage() {
|
||||
header: t(COLUMN_LABEL_KEYS.totalAmountTmt, "TOTAL (TMT)"),
|
||||
cell: ({ row }) => <span className="tabular-nums text-foreground font-medium">{row.original.totalAmountTmt.toLocaleString()}</span>,
|
||||
size: 110,
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
id: "gatewayStatus",
|
||||
@@ -242,6 +279,7 @@ export default function OnlinePaymentHistoryPage() {
|
||||
header: t(COLUMN_LABEL_KEYS.gatewayStatus, "GATEWAY STATUS"),
|
||||
cell: ({ row }) => <GatewayStatusBadge status={row.original.gatewayStatus} />,
|
||||
size: 140,
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
id: "paid",
|
||||
@@ -249,6 +287,7 @@ export default function OnlinePaymentHistoryPage() {
|
||||
header: t(COLUMN_LABEL_KEYS.paid, "PAID"),
|
||||
cell: ({ row }) => <PaidBadge paid={row.original.paid} />,
|
||||
size: 90,
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
@@ -258,6 +297,7 @@ export default function OnlinePaymentHistoryPage() {
|
||||
<span className="text-muted-foreground text-xs whitespace-nowrap">{formatDateTime(row.original.createdAt)}</span>
|
||||
),
|
||||
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")}
|
||||
>
|
||||
<Eye size={15} />
|
||||
@@ -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}
|
||||
|
||||
241
src/pages/onlinePaymentsHistory/onlinePaymentDetailView.tsx
Normal file
241
src/pages/onlinePaymentsHistory/onlinePaymentDetailView.tsx
Normal file
@@ -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 (
|
||||
<div className="flex gap-4 relative">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-3 h-3 rounded-full bg-primary mt-1 shrink-0 z-10" />
|
||||
<div className="w-px flex-1 bg-border mt-1" />
|
||||
</div>
|
||||
|
||||
<div className="pb-6 flex-1 min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-3 mb-1">
|
||||
<GatewayStatusBadge status={step.step} />
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">{formatDateTime(step.createdAt)}</span>
|
||||
<span className="text-xs text-muted-foreground">{step.createdByName}</span>
|
||||
</div>
|
||||
|
||||
{detailEntries.length > 0 && (
|
||||
<div className="mt-2 rounded-md border bg-muted/30 px-3 py-2 space-y-1">
|
||||
{detailEntries.map(([key, value]) => (
|
||||
<div key={key} className="flex gap-2 text-xs">
|
||||
<span className="text-muted-foreground font-medium min-w-[120px]">{detailKeyLabel(key, t)}</span>
|
||||
<span className="text-foreground break-all">{String(value)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="space-y-6">
|
||||
<Skeleton className="h-8 w-64" />
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<Skeleton className="h-56 w-full rounded-xl" />
|
||||
<Skeleton className="h-56 w-full rounded-xl" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError || !data) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-16 gap-4">
|
||||
<p className="text-muted-foreground">{t("common.notFound", "Maglumat tapylmady")}</p>
|
||||
<Button variant="outline" size="sm" onClick={() => navigate(-1)}>
|
||||
<ArrowLeft className="size-4 mr-2" />
|
||||
{t("common.back", "Yza")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const branchName = data.branchName?.[lang] || data.branchName?.tm || data.branchName?.en || "—";
|
||||
const fullName = [data.passportName, data.passportSurname].filter(Boolean).join(" ");
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* ── Page Header ──────────────────────────────────────────────────────── */}
|
||||
<div className="flex items-center justify-between flex-wrap gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="outline" size="icon" onClick={() => navigate(-1)} className="h-9 w-9">
|
||||
<ArrowLeft className="size-4" />
|
||||
</Button>
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<h1 className="text-xl font-semibold text-foreground tracking-tight">
|
||||
{t("onlinePayments.paymentViewTitle", "Töleg maglumaty")}: #{data.id}
|
||||
</h1>
|
||||
<GatewayStatusBadge status={data.gatewayStatus} />
|
||||
<PaidBadge paid={data.paid} />
|
||||
</div>
|
||||
{data.orderNumber && (
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{t("onlinePayments.columns.orderNumber", "Sargyt belgisi")}: {data.orderNumber}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{data.orderId && (
|
||||
<Button variant="secondary" size="sm" asChild>
|
||||
<Link to={`/visa-master/${data.orderId}`}>
|
||||
{t("onlinePayments.goToOrder", "Sargyda geç")} (#{data.orderId})
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Error / Alert (if gateway response error exists) ─────────────────── */}
|
||||
{data.gatewayResponse && (data.gatewayResponse.errorCode || data.gatewayResponse.errorMessage) && (
|
||||
<div className="flex items-start gap-3 p-4 rounded-xl border border-destructive/30 bg-destructive/5 text-destructive">
|
||||
<AlertTriangle className="size-5 shrink-0 mt-0.5" />
|
||||
<div className="space-y-1 text-sm">
|
||||
<div className="font-semibold">
|
||||
Gateway Ýalňyşlygy {data.gatewayResponse.errorCode ? `(Kod: ${data.gatewayResponse.errorCode})` : ""}
|
||||
</div>
|
||||
{data.gatewayResponse.errorMessage && <div className="text-foreground/90">{data.gatewayResponse.errorMessage}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Row 1: General & Financial Information ───────────────────────────── */}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("onlinePayments.sectionGeneral", "Esasy maglumatlar")}>
|
||||
<InfoRow label={t("common.id", "ID")} value={data.id} />
|
||||
<InfoRow
|
||||
label={t("onlinePayments.columns.orderId", "Sargyt ID")}
|
||||
value={data.orderId}
|
||||
isLink={Boolean(data.orderId)}
|
||||
href={`/visa-master/${data.orderId}`}
|
||||
/>
|
||||
<InfoRow label={t("onlinePayments.columns.orderNumber", "Sargyt belgisi")} value={data.orderNumber || "—"} />
|
||||
<InfoRow label={t("onlinePayments.columns.orderUniqueId", "Sargyt unikal ID")} value={data.orderUniqueId || "—"} />
|
||||
<InfoRow label={t("onlinePayments.columns.type", "Görnüşi")}>
|
||||
<span className="text-xs font-semibold uppercase tracking-wide text-foreground">{data.type}</span>
|
||||
</InfoRow>
|
||||
<InfoRow label={t("onlinePayments.columns.description", "Düşündiriş")} value={data.description || "—"} />
|
||||
<InfoRow label={t("onlinePayments.columns.gatewayStatus", "Gateway statusy")}>
|
||||
<GatewayStatusBadge status={data.gatewayStatus} />
|
||||
</InfoRow>
|
||||
<InfoRow label={t("onlinePayments.columns.paid", "Töleg ýagdaýy")}>
|
||||
<PaidBadge paid={data.paid} />
|
||||
</InfoRow>
|
||||
<InfoRow label={t("onlinePayments.columns.createdAt", "Döredilen wagty")} value={formatDateTime(data.createdAt)} />
|
||||
<InfoRow label={t("onlinePayments.columns.updatedAt", "Täzelenen wagty")} value={formatDateTime(data.updatedAt)} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("onlinePayments.sectionFinancial", "Maliýe maglumatlary")}>
|
||||
<InfoRow
|
||||
label={t("onlinePayments.columns.amountTmt", "Töleg möçberi (TMT)")}
|
||||
value={`${data.amountTmt?.toLocaleString?.() ?? data.amountTmt} TMT`}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("onlinePayments.columns.bankFeeTmt", "Bank komissiýasy")}
|
||||
value={`${data.bankFeeTmt?.toLocaleString?.() ?? data.bankFeeTmt} TMT`}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("onlinePayments.columns.gbusFeeTmt", "GBUS komissiýasy")}
|
||||
value={`${data.gbusFeeTmt?.toLocaleString?.() ?? data.gbusFeeTmt} TMT`}
|
||||
/>
|
||||
<InfoRow label={t("onlinePayments.columns.totalAmount", "Jemi töleg möçberi")}>
|
||||
<span className="font-semibold text-primary">{data.totalAmountTmt?.toLocaleString?.() ?? data.totalAmountTmt} TMT</span>
|
||||
</InfoRow>
|
||||
<InfoRow
|
||||
label={t("onlinePayments.columns.amountUsd", "Möçber (USD)")}
|
||||
value={data.amountUsd != null ? `${data.amountUsd} $` : "—"}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("onlinePayments.columns.exchangeRateUsd", "Hümmet (USD)")}
|
||||
value={data.exchangeRateUsd != null ? `${data.exchangeRateUsd} TMT` : "—"}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("onlinePayments.columns.paymentPeriod", "Töleg döwri")}
|
||||
value={data.paymentPeriod ? formatDateTime(data.paymentPeriod) : "—"}
|
||||
/>
|
||||
<InfoRow label={t("onlinePayments.columns.apiClient", "API Client")} value={data.apiClient || "—"} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 2: Customer & Branch Information ─────────────────────────────── */}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("onlinePayments.sectionCustomer", "Müşderi we Ulanyjy")}>
|
||||
<InfoRow label={t("onlinePayments.columns.passport", "Müşderi")} value={fullName || "—"} />
|
||||
<InfoRow
|
||||
label={t("onlinePayments.columns.userId", "Ulanyjy ID")}
|
||||
value={data.userId}
|
||||
isLink={Boolean(data.userId)}
|
||||
href={`/all-users/${data.userId}`}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("onlinePayments.columns.createdByName", "Döreden işgär")}
|
||||
value={data.createdByName ? `${data.createdByName} (ID: ${data.createdById})` : "—"}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("onlinePayments.sectionBranch", "Şahamça maglumaty")}>
|
||||
<InfoRow
|
||||
label={t("onlinePayments.columns.branch", "Şahamça")}
|
||||
value={branchName}
|
||||
isLink={Boolean(data.branchId)}
|
||||
href={`/settings/location/branches/${data.branchId}`}
|
||||
/>
|
||||
<InfoRow label={t("onlinePayments.columns.branchId", "Şahamça ID")} value={data.branchId} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 3: Step-by-Step History Log (Timeline) ───────────────────────── */}
|
||||
{steps && steps.length > 0 && (
|
||||
<BentoCard title={t("onlinePayments.detail.stepsCount", "Ädimler taryhy")}>
|
||||
<div className="p-4">
|
||||
{steps.map((step) => (
|
||||
<StepTimelineRow key={step.id} step={step} />
|
||||
))}
|
||||
</div>
|
||||
</BentoCard>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user