changed pay dialog
This commit is contained in:
13
package-lock.json
generated
13
package-lock.json
generated
@@ -20,6 +20,7 @@
|
||||
"axios": "^1.15.2",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cn": "^0.3.2",
|
||||
"date-fns": "^4.1.0",
|
||||
"i18next": "^26.0.8",
|
||||
"lucide-react": "^1.14.0",
|
||||
@@ -4968,6 +4969,18 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/cn": {
|
||||
"version": "0.3.2",
|
||||
"resolved": "https://registry.npmjs.org/cn/-/cn-0.3.2.tgz",
|
||||
"integrity": "sha512-RKzY5Edavc8B2Ka6tjJecKFC4nm0p7lADY72xzICmiJSf4TkaxWXt0fHsib2P2G4FkFyXfSDi9oDtIBuCZvY2g==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"cn": "bin/cn.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/code-block-writer": {
|
||||
"version": "13.0.3",
|
||||
"resolved": "https://registry.npmjs.org/code-block-writer/-/code-block-writer-13.0.3.tgz",
|
||||
|
||||
15
package.json
15
package.json
@@ -24,6 +24,7 @@
|
||||
"axios": "^1.15.2",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cn": "^0.3.2",
|
||||
"date-fns": "^4.1.0",
|
||||
"i18next": "^26.0.8",
|
||||
"lucide-react": "^1.14.0",
|
||||
@@ -54,18 +55,18 @@
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"autoprefixer": "^10.5.0",
|
||||
"eslint": "^10.2.1",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.5.0",
|
||||
"husky": "^9.1.7",
|
||||
"lint-staged": "^16.4.0",
|
||||
"postcss": "^8.5.13",
|
||||
"prettier": "^3.8.3",
|
||||
"tailwindcss": "^4.2.4",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.0.10",
|
||||
"eslint": "^10.2.1",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.5.0",
|
||||
"typescript-eslint": "^8.58.2"
|
||||
"typescript-eslint": "^8.58.2",
|
||||
"vite": "^8.0.10"
|
||||
}
|
||||
}
|
||||
|
||||
54
src/components/ui/alert.tsx
Normal file
54
src/components/ui/alert.tsx
Normal file
@@ -0,0 +1,54 @@
|
||||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { cn } from "cn";
|
||||
|
||||
const alertVariants = cva(
|
||||
"group/alert relative grid w-full gap-0.5 rounded-2xl border px-4 py-3 text-left text-sm has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pr-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2.5 *:[svg]:row-span-2 *:[svg]:translate-y-0.5 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-card text-card-foreground",
|
||||
destructive: "bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 *:[svg]:text-current",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Alert({ className, variant, ...props }: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||
return <div data-slot="alert" role="alert" className={cn(alertVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-title"
|
||||
className={cn(
|
||||
"font-medium group-has-[>svg]/alert:col-start-2 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-description"
|
||||
className={cn(
|
||||
"text-sm text-balance text-muted-foreground md:text-pretty [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return <div data-slot="alert-action" className={cn("absolute top-2.5 right-3", className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription, AlertAction };
|
||||
125
src/components/ui/dialog.tsx
Normal file
125
src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,125 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "cn";
|
||||
import { Dialog as DialogPrimitive } from "radix-ui";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { XIcon } from "lucide-react";
|
||||
|
||||
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
|
||||
}
|
||||
|
||||
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
|
||||
}
|
||||
|
||||
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
||||
}
|
||||
|
||||
function DialogOverlay({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 isolate z-50 bg-black/30 duration-100 supports-backdrop-filter:backdrop-blur-sm data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-6 rounded-md bg-popover p-6 text-sm text-popover-foreground shadow-xl ring-1 ring-foreground/5 duration-100 outline-none sm:max-w-md dark:ring-foreground/10 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close data-slot="dialog-close" asChild>
|
||||
<Button variant="ghost" className="absolute top-4 right-4 bg-secondary" size="icon-sm">
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</Button>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return <div data-slot="dialog-header" className={cn("flex flex-col gap-1.5", className)} {...props} />;
|
||||
}
|
||||
|
||||
function DialogFooter({
|
||||
className,
|
||||
showCloseButton = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showCloseButton?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div data-slot="dialog-footer" className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)} {...props}>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close asChild>
|
||||
<Button variant="outline">Close</Button>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("font-heading text-base leading-none font-medium", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
};
|
||||
@@ -32,9 +32,11 @@ interface StepDef {
|
||||
id: string;
|
||||
titleKey: string;
|
||||
titleFallback: string;
|
||||
shortLabelKey: string;
|
||||
shortLabel: string;
|
||||
icon: LucideIcon;
|
||||
subtitle: string;
|
||||
subtitleKey: string;
|
||||
subtitleFallback: string;
|
||||
validate: (form: BranchFormData, mode: "create" | "edit", t: (key: string, fallback?: string) => string) => FlatErrors;
|
||||
}
|
||||
|
||||
@@ -43,27 +45,33 @@ const STEPS: StepDef[] = [
|
||||
id: "basic",
|
||||
titleKey: "branches.steps.basic",
|
||||
titleFallback: "Esasy maglumatlar",
|
||||
shortLabelKey: "branches.steps.basic.shortLabel",
|
||||
shortLabel: "Esasy",
|
||||
icon: Building2,
|
||||
subtitle: "Ady, unikal belgisi, welayaty",
|
||||
subtitleKey: "branches.steps.basic.subtitle",
|
||||
subtitleFallback: "Ady, unikal belgisi, welaýaty",
|
||||
validate: (form, mode, t) => validateStep(0, form, mode, t),
|
||||
},
|
||||
{
|
||||
id: "address",
|
||||
titleKey: "branches.steps.address",
|
||||
titleFallback: "Salgy we habarlaşmak",
|
||||
shortLabelKey: "branches.steps.address.shortLabel",
|
||||
shortLabel: "Salgy",
|
||||
icon: MapPin,
|
||||
subtitle: "Salgy, telefonlar",
|
||||
subtitleKey: "branches.steps.address.subtitle",
|
||||
subtitleFallback: "Salgy, telefonlar",
|
||||
validate: (form, mode, t) => validateStep(1, form, mode, t),
|
||||
},
|
||||
{
|
||||
id: "billing",
|
||||
titleKey: "branches.steps.billing",
|
||||
titleFallback: "Billing maglumatlary",
|
||||
shortLabelKey: "branches.steps.billing.shortLabel",
|
||||
shortLabel: "Billing",
|
||||
icon: CreditCard,
|
||||
subtitle: "Ulanyjy ady we parollar",
|
||||
subtitleKey: "branches.steps.billing.subtitle",
|
||||
subtitleFallback: "Ulanyjy ady we parollar",
|
||||
validate: (form, mode, t) => validateStep(2, form, mode, t),
|
||||
},
|
||||
];
|
||||
@@ -110,7 +118,7 @@ function StepBasic({ form, errors, set, t, provinceSelect }: StepContentProps) {
|
||||
required
|
||||
value={form.uniqueCode}
|
||||
onChange={(v) => set("uniqueCode", v)}
|
||||
placeholder="ORG-XXX-XXXX"
|
||||
placeholder={t("branches.fields.uniqueCodePlaceholder", "ORG-XXX-XXXX")}
|
||||
error={errors.uniqueCode}
|
||||
/>
|
||||
<FormInput
|
||||
@@ -119,7 +127,7 @@ function StepBasic({ form, errors, set, t, provinceSelect }: StepContentProps) {
|
||||
required
|
||||
value={form.region}
|
||||
onChange={(v) => set("region", v)}
|
||||
placeholder="Aşgabat şäheri"
|
||||
placeholder={t("branches.fields.regionPlaceholder", "Aşgabat şäheri")}
|
||||
error={errors.region}
|
||||
/>
|
||||
</div>
|
||||
@@ -128,7 +136,7 @@ function StepBasic({ form, errors, set, t, provinceSelect }: StepContentProps) {
|
||||
<InfiniteSelect
|
||||
label={t("branches.fields.district", "Etrap")}
|
||||
required
|
||||
placeholder={t("branches.fields.district", "Etrap saýlaň")}
|
||||
placeholder={t("branches.fields.districtPlaceholder", "Etrap saýlaň")}
|
||||
{...provinceSelect}
|
||||
error={provinceSelect.error ?? errors.provinceId}
|
||||
value={form.provinceId}
|
||||
@@ -165,7 +173,7 @@ function StepAddress({ form, errors, set, t }: StepContentProps) {
|
||||
required
|
||||
value={form.phoneNumbers}
|
||||
onChange={(v) => set("phoneNumbers", v)}
|
||||
placeholder="+99312998877, +99365123456"
|
||||
placeholder={t("branches.fields.phoneNumbersPlaceholder", "+99312998877, +99365123456")}
|
||||
error={errors.phoneNumbers}
|
||||
/>
|
||||
</div>
|
||||
@@ -445,8 +453,8 @@ export function BranchForm({ mode, initialData }: BranchFormProps) {
|
||||
|
||||
return {
|
||||
id: s.id,
|
||||
title: t(s.titleKey) || s.titleFallback,
|
||||
subtitle: s.subtitle,
|
||||
title: t(s.titleKey, s.titleFallback),
|
||||
subtitle: t(s.subtitleKey, s.subtitleFallback),
|
||||
icon: s.icon,
|
||||
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||
};
|
||||
|
||||
@@ -1,151 +1,101 @@
|
||||
// features/onlinePaymentHistory/api/onlinePaymentHistoryApi.ts
|
||||
// features/onlinePaymentHistory/api/onlinePaymentsHistoryApi.ts
|
||||
|
||||
export type PaymentStatus = 'GARAŞYLÝAR' | 'TÖLENEN' | 'YATYRYLAN'
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Shared ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface LocalizedText {
|
||||
en: string;
|
||||
ru: string;
|
||||
tm: string;
|
||||
}
|
||||
|
||||
// ─── List Types ───────────────────────────────────────────────────────────────
|
||||
|
||||
/** Gateway status values returned by the backend. */
|
||||
export type GatewayStatus = "success" | "failed" | "pending" | "processing";
|
||||
|
||||
export interface OnlinePayment {
|
||||
id: number
|
||||
orderId: string
|
||||
amount: number
|
||||
orderNumber: string
|
||||
apiClient: string
|
||||
description: string
|
||||
formUrl: string
|
||||
successUrl: string
|
||||
status: PaymentStatus
|
||||
callbackStatus: string | null
|
||||
username: string
|
||||
onlinePaymantableId: number
|
||||
onlinePaymantableType: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
id: number;
|
||||
orderId: number;
|
||||
orderUniqueId: string;
|
||||
type: string; // "visa" | "sber" | "kart" | ...
|
||||
branchId: number;
|
||||
branchName: LocalizedText;
|
||||
passportName: string;
|
||||
passportSurname: string;
|
||||
userId: number;
|
||||
paid: boolean;
|
||||
amountTmt: number;
|
||||
bankFeeTmt: number;
|
||||
gbusFeeTmt: number;
|
||||
totalAmountTmt: number;
|
||||
exchangeRateUsd: number;
|
||||
paymentPeriod: string;
|
||||
gatewayStatus: string;
|
||||
gatewayReference: string;
|
||||
createdById: number;
|
||||
createdByName: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface OnlinePaymentListParams {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
orderId?: number;
|
||||
branchId?: number;
|
||||
userId?: number;
|
||||
status?: string;
|
||||
search?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/** Shape returned by the backend after the axios envelope is unwrapped. */
|
||||
export interface OnlinePaymentListResponse {
|
||||
data: OnlinePayment[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
totalPages: number
|
||||
count: number;
|
||||
items: OnlinePayment[];
|
||||
}
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
// ─── Detail / History Step Types ─────────────────────────────────────────────
|
||||
|
||||
const buildPayment = (
|
||||
id: number,
|
||||
orderId: string,
|
||||
amount: number,
|
||||
orderNumber: string,
|
||||
apiClient: string,
|
||||
description: string,
|
||||
status: PaymentStatus,
|
||||
username: string,
|
||||
paymantableId: number,
|
||||
paymantableType: string,
|
||||
createdAt: string,
|
||||
callbackStatus: string | null = null
|
||||
): OnlinePayment => ({
|
||||
id,
|
||||
orderId,
|
||||
amount,
|
||||
orderNumber,
|
||||
apiClient,
|
||||
description,
|
||||
formUrl: `https://mpi.gov.tm/payment/merchants/online/payment_ru.html?mdOrder=${orderId}`,
|
||||
successUrl: 'https://online.tbbank.gov.tm/online-payment-store-visa-master',
|
||||
status,
|
||||
callbackStatus,
|
||||
username,
|
||||
onlinePaymantableId: paymantableId,
|
||||
onlinePaymantableType: paymantableType,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
})
|
||||
|
||||
const VM_TYPE = 'App\\Modules\\VisaMasterPaymentOrder\\Models\\VisaMasterPaymentOrder'
|
||||
const SBER_TYPE = 'App\\Modules\\SberPaymentOrder\\Models\\SberPaymentOrder'
|
||||
const KART_TYPE = 'App\\Modules\\KartPaymentOrder\\Models\\KartPaymentOrder'
|
||||
|
||||
const MOCK_PAYMENTS: OnlinePayment[] = [
|
||||
buildPayment(1667, 'ed99d307-65fd-40ed-98ec-898019000af4', 99438, '110526160855', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040830', 5280, VM_TYPE, '2026-05-11T16:08:00Z'),
|
||||
buildPayment(1666, 'ab12c456-11aa-22bb-33cc-111111000001', 99438, '110526160800', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5279, VM_TYPE, '2026-05-11T16:06:00Z', 'SUCCESS'),
|
||||
buildPayment(1665, 'bc23d567-22bb-33cc-44dd-222222000002', 99438, '110526160745', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5278, VM_TYPE, '2026-05-11T16:04:00Z', 'SUCCESS'),
|
||||
buildPayment(1664, 'cd34e678-33cc-44dd-55ee-333333000003', 99438, '110526160730', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5277, VM_TYPE, '2026-05-11T16:03:00Z', 'SUCCESS'),
|
||||
buildPayment(1663, 'de45f789-44dd-55ee-66ff-444444000004', 99438, '110526160715', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5276, VM_TYPE, '2026-05-11T16:01:00Z', 'SUCCESS'),
|
||||
buildPayment(1662, 'ef56a890-55ee-66ff-77aa-555555000005', 99438, '110526155900', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5275, VM_TYPE, '2026-05-11T15:40:00Z', 'SUCCESS'),
|
||||
buildPayment(1661, 'fa67b901-66ff-77aa-88bb-666666000006', 99438, '110526155830', 'billing_visa_master_username', 'Visa/Master tölegi', 'YATYRYLAN', '10130100040844', 5274, VM_TYPE, '2026-05-11T15:39:00Z'),
|
||||
buildPayment(1660, 'ab78c012-77aa-88bb-99cc-777777000007', 99438, '110526155800', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5273, VM_TYPE, '2026-05-11T15:38:00Z', 'SUCCESS'),
|
||||
buildPayment(1659, 'bc89d123-88bb-99cc-00dd-888888000008', 99438, '110526155730', 'billing_visa_master_username', 'Visa/Master tölegi', 'YATYRYLAN', '10130100040844', 5272, VM_TYPE, '2026-05-11T15:35:00Z'),
|
||||
buildPayment(1658, 'cd90e234-99cc-00dd-11ee-999999000009', 99438, '110526152900', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5271, VM_TYPE, '2026-05-11T15:29:00Z', 'SUCCESS'),
|
||||
buildPayment(1657, 'de01f345-00dd-11ee-22ff-000000000010', 99438, '110526103900', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040862', 5270, VM_TYPE, '2026-05-11T10:39:00Z'),
|
||||
buildPayment(1656, 'ef12a456-11ee-22ff-33aa-111111000011', 99438, '110526103800', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040862', 5269, VM_TYPE, '2026-05-11T10:39:00Z'),
|
||||
buildPayment(1655, 'fa23b567-22ff-33aa-44bb-222222000012', 99438, '110526103700', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040862', 5268, VM_TYPE, '2026-05-11T10:38:00Z'),
|
||||
buildPayment(1654, 'ab34c678-33aa-44bb-55cc-333333000013', 99438, '110526103600', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040862', 5267, VM_TYPE, '2026-05-11T10:38:00Z'),
|
||||
buildPayment(1653, 'bc45d789-44bb-55cc-66dd-444444000014', 99438, '110526085200', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040828', 5266, VM_TYPE, '2026-05-11T08:52:00Z'),
|
||||
buildPayment(1652, 'cd56e890-55cc-66dd-77ee-555555000015', 99438, '060526142300', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040826', 5265, VM_TYPE, '2026-05-06T14:23:00Z'),
|
||||
buildPayment(1651, 'de67f901-66dd-77ee-88ff-666666000016', 106345,'280426161300', 'billing_sber_username', 'Sber tölegi', 'GARAŞYLÝAR', '10130100040827', 5264, SBER_TYPE, '2026-04-28T16:13:00Z'),
|
||||
buildPayment(1650, 'ef78a012-77ee-88ff-99aa-777777000017', 32, '250426130100', 'billing_username', 'Kart tölegi', 'GARAŞYLÝAR', '10130100004083', 5263, KART_TYPE, '2026-04-25T13:01:00Z'),
|
||||
buildPayment(1649, 'fa89b123-88ff-99aa-00bb-888888000018', 32, '240426101900', 'billing_username', 'Kart tölegi', 'GARAŞYLÝAR', '10130100004083', 5262, KART_TYPE, '2026-04-24T10:19:00Z'),
|
||||
buildPayment(1648, 'ab90c234-99aa-00bb-11cc-999999000019', 106344,'210426105900', 'billing_sber_username', 'Sber tölegi', 'TÖLENEN', '10130100040827', 5261, SBER_TYPE, '2026-04-21T10:59:00Z', 'SUCCESS'),
|
||||
buildPayment(1647, 'bc01d345-00bb-11cc-22dd-000000000020', 106243,'200426153100', 'billing_sber_username', 'Sber tölegi', 'GARAŞYLÝAR', '10130100040833', 5260, SBER_TYPE, '2026-04-20T15:31:00Z'),
|
||||
buildPayment(1646, 'cd12e456-11cc-22dd-33ee-111111000021', 99438, '170426111400', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040832', 5259, VM_TYPE, '2026-04-17T11:14:00Z', 'SUCCESS'),
|
||||
buildPayment(1645, 'de23f567-22dd-33ee-44ff-222222000022', 99438, '170426103400', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040832', 5258, VM_TYPE, '2026-04-17T10:34:00Z'),
|
||||
buildPayment(1644, 'ef34a678-33ee-44ff-55aa-333333000023', 99438, '160426175600', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040830', 5257, VM_TYPE, '2026-04-16T17:56:00Z'),
|
||||
buildPayment(1643, 'fa45b789-44ff-55aa-66bb-444444000024', 99438, '150426155000', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040826', 5256, VM_TYPE, '2026-04-15T15:50:00Z', 'SUCCESS'),
|
||||
]
|
||||
|
||||
// Total mock count is 1664 per screenshot — we serve paginated slices of the 25 above
|
||||
const TOTAL_MOCK = 1664
|
||||
|
||||
const delay = (ms = 400) => new Promise<void>((res) => setTimeout(res, ms))
|
||||
export interface PaymentHistoryStep {
|
||||
id: number;
|
||||
orderId: number;
|
||||
step: string;
|
||||
detail: Record<string, string>;
|
||||
createdById: number;
|
||||
createdByName: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchOnlinePayments(
|
||||
params: OnlinePaymentListParams = {}
|
||||
): Promise<OnlinePaymentListResponse> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 25, search = '' } = params
|
||||
|
||||
let filtered = [...MOCK_PAYMENTS]
|
||||
|
||||
if (search.trim()) {
|
||||
const q = search.toLowerCase()
|
||||
filtered = filtered.filter(
|
||||
(r) =>
|
||||
String(r.amount).includes(q) ||
|
||||
r.apiClient.toLowerCase().includes(q) ||
|
||||
r.description.toLowerCase().includes(q)||
|
||||
r.username.toLowerCase().includes(q) ||
|
||||
r.status.toLowerCase().includes(q) ||
|
||||
r.orderId.toLowerCase().includes(q)
|
||||
)
|
||||
}
|
||||
|
||||
const total = search.trim() ? filtered.length : TOTAL_MOCK
|
||||
const totalPages = Math.ceil(total / perPage)
|
||||
const start = (page - 1) * perPage
|
||||
const data = filtered.slice(start, start + perPage)
|
||||
|
||||
return { data, total, page, perPage, totalPages }
|
||||
/**
|
||||
* GET /payment-history
|
||||
* Returns paginated list of online payment records.
|
||||
* Query params: order_id, branch_id, user_id, status, search, page, limit
|
||||
*/
|
||||
export async function fetchOnlinePayments(params: OnlinePaymentListParams = {}): Promise<OnlinePaymentListResponse> {
|
||||
const { orderId, branchId, userId, status, 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,
|
||||
search: search || undefined,
|
||||
page: page ?? 1,
|
||||
limit: limit ?? 25,
|
||||
},
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function fetchOnlinePaymentById(id: number): Promise<OnlinePayment> {
|
||||
await delay()
|
||||
const item = MOCK_PAYMENTS.find((r) => r.id === id)
|
||||
if (!item) throw new Error(`OnlinePayment with id ${id} not found`)
|
||||
return { ...item }
|
||||
/**
|
||||
* GET /payment-history/:id
|
||||
* Returns the step-by-step history log for a single payment order.
|
||||
*/
|
||||
export async function fetchOnlinePaymentById(id: number): Promise<PaymentHistoryStep[]> {
|
||||
const { data } = await apiClient.get<PaymentHistoryStep[]>(`/payment-history/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
// Callback trigger — mock only logs; in real impl would POST to backend
|
||||
export async function triggerPaymentCallback(id: number): Promise<void> {
|
||||
await delay(600)
|
||||
const item = MOCK_PAYMENTS.find((r) => r.id === id)
|
||||
if (!item) throw new Error(`OnlinePayment with id ${id} not found`)
|
||||
// no-op in mock
|
||||
}
|
||||
@@ -1,33 +1,63 @@
|
||||
import {
|
||||
StatusBadge,
|
||||
type StatusBadgeVariant,
|
||||
} from '@/components/ui/statusBadge'
|
||||
import { AlertCircle, CheckCircle2, XCircle } from 'lucide-react'
|
||||
import type { PaymentStatus } from '@/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi'
|
||||
// features/onlinePaymentHistory/components/PaymentStatusBadge.tsx
|
||||
|
||||
const STATUS_CONFIG = {
|
||||
GARAŞYLÝAR: {
|
||||
label: 'Garaşylýar',
|
||||
variant: 'warning' as StatusBadgeVariant,
|
||||
icon: AlertCircle,
|
||||
},
|
||||
TÖLENEN: {
|
||||
label: 'Tölenen',
|
||||
variant: 'success' as StatusBadgeVariant,
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { AlertCircle, CheckCircle2, Clock, Loader2, XCircle } from "lucide-react";
|
||||
|
||||
// ─── Status config ────────────────────────────────────────────────────────────
|
||||
|
||||
interface StatusConfig {
|
||||
label: string;
|
||||
variant: StatusBadgeVariant;
|
||||
icon: React.ElementType;
|
||||
}
|
||||
|
||||
const STATUS_CONFIG: Record<string, StatusConfig> = {
|
||||
success: {
|
||||
label: "Success",
|
||||
variant: "success",
|
||||
icon: CheckCircle2,
|
||||
},
|
||||
YATYRYLAN: {
|
||||
label: 'Ýatyrylan',
|
||||
variant: 'error' as StatusBadgeVariant,
|
||||
failed: {
|
||||
label: "Failed",
|
||||
variant: "error",
|
||||
icon: XCircle,
|
||||
},
|
||||
} satisfies Record<
|
||||
PaymentStatus,
|
||||
{ label: string; variant: StatusBadgeVariant; icon: React.ElementType }
|
||||
>
|
||||
pending: {
|
||||
label: "Pending",
|
||||
variant: "warning",
|
||||
icon: AlertCircle,
|
||||
},
|
||||
processing: {
|
||||
label: "Processing",
|
||||
variant: "warning",
|
||||
icon: Loader2,
|
||||
},
|
||||
// paid boolean fallback rendered as separate PaidBadge below
|
||||
};
|
||||
|
||||
export function PaymentStatusBadge({ status }: { status: PaymentStatus }) {
|
||||
const cfg = STATUS_CONFIG[status]
|
||||
if (!cfg) return <span className="text-xs text-muted-foreground">{String(status)}</span>
|
||||
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />
|
||||
// ─── GatewayStatusBadge ───────────────────────────────────────────────────────
|
||||
|
||||
export function GatewayStatusBadge({ status }: { status: string }) {
|
||||
const cfg = STATUS_CONFIG[status?.toLowerCase()];
|
||||
if (!cfg) {
|
||||
return <StatusBadge label={status ?? "—"} variant="default" icon={Clock} />;
|
||||
}
|
||||
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />;
|
||||
}
|
||||
|
||||
// ─── PaidBadge ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function PaidBadge({ paid }: { paid: boolean }) {
|
||||
return paid ? (
|
||||
<StatusBadge label="Paid" variant="success" icon={CheckCircle2} />
|
||||
) : (
|
||||
<StatusBadge label="Unpaid" variant="error" icon={XCircle} />
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Legacy alias — kept so the detail page import doesn't break ──────────────
|
||||
|
||||
/** @deprecated Use GatewayStatusBadge instead */
|
||||
export function PaymentStatusBadge({ status }: { status: string }) {
|
||||
return <GatewayStatusBadge status={status} />;
|
||||
}
|
||||
|
||||
@@ -1,57 +1,36 @@
|
||||
// features/onlinePaymentHistory/hooks/useOnlinePaymentHistory.ts
|
||||
// features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory.ts
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
fetchOnlinePayments,
|
||||
fetchOnlinePaymentById,
|
||||
triggerPaymentCallback,
|
||||
type OnlinePaymentListParams,
|
||||
} from '../api/onlinePaymentsHistoryApi'
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { fetchOnlinePayments, fetchOnlinePaymentById, type OnlinePaymentListParams } from "../api/onlinePaymentsHistoryApi";
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
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,
|
||||
}
|
||||
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,
|
||||
};
|
||||
|
||||
// ─── useGetOnlinePayments ─────────────────────────────────────────────────────
|
||||
|
||||
export function useGetOnlinePayments(params: OnlinePaymentListParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: onlinePaymentKeys.list(params),
|
||||
queryFn: () => fetchOnlinePayments(params),
|
||||
})
|
||||
queryFn: () => fetchOnlinePayments(params),
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useGetOnlinePaymentById ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Fetches the step-by-step history log for a single payment order.
|
||||
* Returns an array of PaymentHistoryStep.
|
||||
*/
|
||||
export function useGetOnlinePaymentById(id: number) {
|
||||
return useQuery({
|
||||
queryKey: onlinePaymentKeys.detail(id),
|
||||
queryFn: () => fetchOnlinePaymentById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
queryFn: () => fetchOnlinePaymentById(id),
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useTriggerPaymentCallback ────────────────────────────────────────────────
|
||||
|
||||
export function useTriggerPaymentCallback() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => triggerPaymentCallback(id),
|
||||
onSuccess: (_data, id) => {
|
||||
queryClient.invalidateQueries({ queryKey: onlinePaymentKeys.detail(id) })
|
||||
queryClient.invalidateQueries({ queryKey: onlinePaymentKeys.lists() })
|
||||
toast.success(t('onlinePayments.toast.callbackTriggered', 'Callback ugradyldy'))
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,12 +1,16 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { useId, useMemo, useState } from "react";
|
||||
import type { ChangeEvent, FormEvent, ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AlertCircle, Loader2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { useQuoteIntlPayment, usePayIntlPayment } from "../hooks/useVisaMasterPayments";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
|
||||
// ─── Months ───────────────────────────────────────────────────────────────────
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MONTHS = [
|
||||
{ value: "01", label: "Ýanwar" },
|
||||
@@ -21,27 +25,226 @@ const MONTHS = [
|
||||
{ value: "10", label: "Oktýabr" },
|
||||
{ value: "11", label: "Noýabr" },
|
||||
{ value: "12", label: "Dekabr" },
|
||||
];
|
||||
] as const;
|
||||
|
||||
/** Digits with optional decimal part (max 2 digits). Accepts "." or ",". */
|
||||
const AMOUNT_PATTERN = /^\d*([.,]\d{0,2})?$/;
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function currentMonthValue(): string {
|
||||
const d = new Date();
|
||||
return String(d.getMonth() + 1).padStart(2, "0");
|
||||
return String(new Date().getMonth() + 1).padStart(2, "0");
|
||||
}
|
||||
|
||||
function currentYear(): number {
|
||||
return new Date().getFullYear();
|
||||
}
|
||||
|
||||
/** Build last-day-of-month date string YYYY-MM-DD */
|
||||
/** Last day of the selected month in the current year, as YYYY-MM-DD */
|
||||
function buildPaymentPeriod(monthValue: string): string {
|
||||
const year = currentYear();
|
||||
const year = new Date().getFullYear();
|
||||
const month = parseInt(monthValue, 10);
|
||||
const lastDay = new Date(year, month, 0).getDate();
|
||||
return `${year}-${monthValue}-${String(lastDay).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
// Money math in minor units (tyn) to avoid floating point drift (0.1 + 0.2 problem)
|
||||
const toMinor = (value: number): number => Math.round(value * 100);
|
||||
const fromMinor = (minor: number): string => (minor / 100).toFixed(2);
|
||||
|
||||
// ─── Layout helper ────────────────────────────────────────────────────────────
|
||||
|
||||
interface FieldRowProps {
|
||||
label: string;
|
||||
htmlFor: string;
|
||||
required?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
function FieldRow({ label, htmlFor, required, children }: FieldRowProps) {
|
||||
return (
|
||||
<div className="grid grid-cols-1 items-start gap-2 sm:grid-cols-[140px_1fr] sm:gap-6">
|
||||
<Label htmlFor={htmlFor} className="sm:pt-2.5">
|
||||
{required && (
|
||||
<span aria-hidden="true" className="mr-1 text-destructive">
|
||||
*
|
||||
</span>
|
||||
)}
|
||||
{label}
|
||||
</Label>
|
||||
<div className="space-y-1">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Form (mounted only while the dialog is open → state resets automatically) ─
|
||||
|
||||
interface PayPayload {
|
||||
amountTmt: number;
|
||||
paymentPeriod: string;
|
||||
}
|
||||
|
||||
interface PayFormProps {
|
||||
id: string;
|
||||
isPaying: boolean;
|
||||
onSubmit: (payload: PayPayload) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
function PayForm({ id, isPaying, onSubmit, onCancel }: PayFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const uid = useId();
|
||||
const monthId = `${uid}-month`;
|
||||
const amountId = `${uid}-amount`;
|
||||
const amountErrorId = `${uid}-amount-error`;
|
||||
const usdId = `${uid}-usd`;
|
||||
const totalId = `${uid}-total`;
|
||||
|
||||
const [currentMonth] = useState(currentMonthValue);
|
||||
const [selectedMonth, setSelectedMonth] = useState<string>(currentMonth);
|
||||
const [amountStr, setAmountStr] = useState("");
|
||||
|
||||
const { data: quote, isLoading: quoteLoading, isFetching: quoteFetching, isError: quoteError, refetch } = useQuoteIntlPayment(id);
|
||||
|
||||
const amountTmt = Number(amountStr.replace(",", ".")) || 0;
|
||||
|
||||
const { usdEquivalent, totalTmt } = useMemo(() => {
|
||||
if (!quote || amountTmt <= 0) return { usdEquivalent: "", totalTmt: "" };
|
||||
return {
|
||||
usdEquivalent: quote.exchangeRateUsd > 0 ? (amountTmt / quote.exchangeRateUsd).toFixed(2) : "",
|
||||
totalTmt: fromMinor(toMinor(amountTmt) + toMinor(quote.bankFeeTmt) + toMinor(quote.gbusFeeTmt)),
|
||||
};
|
||||
}, [amountTmt, quote]);
|
||||
|
||||
const isMonthCorrect = selectedMonth === currentMonth;
|
||||
|
||||
const amountError =
|
||||
quote && amountTmt > quote.maxAmountTmt ? t("intlPayment.pay.amountExceedsMax", "Möçber iň ýokary möçberden geçýär") : null;
|
||||
|
||||
// Never allow paying without a fresh quote: the max-amount check depends on it.
|
||||
const canSubmit = !!quote && !quoteFetching && !isPaying && amountTmt > 0 && !amountError;
|
||||
|
||||
function handleAmountChange(e: ChangeEvent<HTMLInputElement>) {
|
||||
const next = e.target.value;
|
||||
if (AMOUNT_PATTERN.test(next)) setAmountStr(next);
|
||||
}
|
||||
|
||||
function handleSubmit(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
if (!canSubmit) return;
|
||||
onSubmit({ amountTmt, paymentPeriod: buildPaymentPeriod(selectedMonth) });
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} noValidate className="space-y-5">
|
||||
{/* Quote info */}
|
||||
{quoteLoading ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
{t("common.loading", "Ýüklenýär...")}
|
||||
</div>
|
||||
) : quoteError ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="flex items-center justify-between gap-3">
|
||||
<span>{t("intlPayment.pay.quoteError", "Kurs maglumatlary ýüklenmedi")}</span>
|
||||
<Button type="button" size="sm" variant="outline" onClick={() => refetch()}>
|
||||
{t("common.retry", "Täzeden synanyşyň")}
|
||||
</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : quote ? (
|
||||
<dl className="space-y-0.5 rounded-md bg-muted px-4 py-3 text-xs font-semibold uppercase tracking-wide">
|
||||
<div className="flex justify-between gap-4">
|
||||
<dt className="text-muted-foreground">1 USD</dt>
|
||||
<dd>{quote.exchangeRateUsd} TMT</dd>
|
||||
</div>
|
||||
<div className="flex justify-between gap-4">
|
||||
<dt className="text-muted-foreground">{t("intlPayment.pay.bankFee", "BANKYŇ TUTUMY")}</dt>
|
||||
<dd>{quote.bankFeeTmt} TMT</dd>
|
||||
</div>
|
||||
<div className="flex justify-between gap-4">
|
||||
<dt className="text-muted-foreground">{t("intlPayment.pay.gbusFee", "GBÜS TUTUMY")}</dt>
|
||||
<dd>{quote.gbusFeeTmt} TMT</dd>
|
||||
</div>
|
||||
</dl>
|
||||
) : null}
|
||||
|
||||
{/* Töleg aý */}
|
||||
<FieldRow label={t("intlPayment.pay.month", "Töleg aý")} htmlFor={monthId}>
|
||||
<Select value={selectedMonth} onValueChange={setSelectedMonth}>
|
||||
<SelectTrigger id={monthId} className="w-full">
|
||||
<SelectValue placeholder={t("intlPayment.pay.selectMonth", "Aý saýlaň")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{MONTHS.map((m) => (
|
||||
<SelectItem key={m.value} value={m.value}>
|
||||
{t(`intlPayment.pay.months.${m.value}`, m.label)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FieldRow>
|
||||
|
||||
{/* Töleg möçberi */}
|
||||
<FieldRow label={t("intlPayment.pay.amount", "Töleg möçberi (TMT)")} htmlFor={amountId} required>
|
||||
<Input
|
||||
id={amountId}
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
autoComplete="off"
|
||||
placeholder="0"
|
||||
value={amountStr}
|
||||
onChange={handleAmountChange}
|
||||
aria-invalid={!!amountError}
|
||||
aria-describedby={amountError ? amountErrorId : undefined}
|
||||
/>
|
||||
{amountError ? (
|
||||
<p id={amountErrorId} role="alert" className="text-xs text-destructive">
|
||||
{amountError}
|
||||
</p>
|
||||
) : (
|
||||
quote && (
|
||||
<p className="text-xs italic text-muted-foreground">
|
||||
{t("intlPayment.pay.maxAmount", "Iň ýokary möçberi")}: {quote.maxAmountTmt} TMT
|
||||
</p>
|
||||
)
|
||||
)}
|
||||
</FieldRow>
|
||||
|
||||
{/* USD ekwalendi */}
|
||||
<FieldRow label={t("intlPayment.pay.usdEquiv", "USD ekwalendi")} htmlFor={usdId}>
|
||||
<Input id={usdId} readOnly tabIndex={-1} value={usdEquivalent} placeholder="0" className="bg-muted text-muted-foreground" />
|
||||
</FieldRow>
|
||||
|
||||
{/* Jemi */}
|
||||
<FieldRow label={t("intlPayment.pay.total", "Jemi (TMT)")} htmlFor={totalId}>
|
||||
<Input id={totalId} readOnly tabIndex={-1} value={totalTmt} placeholder="0" className="bg-muted text-muted-foreground" />
|
||||
</FieldRow>
|
||||
|
||||
{/* Wrong month warning */}
|
||||
{!isMonthCorrect && (
|
||||
<Alert className="border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-400 [&>svg]:text-amber-600 dark:[&>svg]:text-amber-400">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{t("intlPayment.pay.wrongMonth", "Dogry töleg aýyny saýlamagyňyzy haýyş edýäris!")}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<DialogFooter className="gap-2 ">
|
||||
<Button type="button" variant="outline" onClick={onCancel} disabled={isPaying}>
|
||||
{t("intlPayment.pay.cancel", "Ýatyr")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={!canSubmit}>
|
||||
{isPaying ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
{t("common.saving", "Saklanýar...")}
|
||||
</span>
|
||||
) : (
|
||||
t("intlPayment.pay.confirm", "Dowam et")
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Dialog ───────────────────────────────────────────────────────────────────
|
||||
|
||||
interface PayDialogProps {
|
||||
@@ -52,189 +255,33 @@ interface PayDialogProps {
|
||||
|
||||
export function PayDialog({ id, open, onOpenChange }: PayDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [selectedMonth, setSelectedMonth] = useState<string>(currentMonthValue());
|
||||
const [amountStr, setAmountStr] = useState<string>("");
|
||||
|
||||
// Reset when dialog opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setSelectedMonth(currentMonthValue());
|
||||
setAmountStr("");
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const { data: quote, isLoading: quoteLoading } = useQuoteIntlPayment(open ? id : "");
|
||||
const { mutate: pay, isPending: isPaying } = usePayIntlPayment();
|
||||
|
||||
// Live-calculated fields
|
||||
const amountTmt = parseFloat(amountStr) || 0;
|
||||
// The parent passes id="" as soon as it closes the dialog. Keep the last real id
|
||||
// so the content doesn't flicker (quote disappears) during the close animation.
|
||||
const [stableId, setStableId] = useState(id);
|
||||
if (id && id !== stableId) setStableId(id);
|
||||
|
||||
const usdEquivalent = useMemo(() => {
|
||||
if (!quote || amountTmt <= 0) return "";
|
||||
const val = amountTmt / quote.exchangeRateUsd;
|
||||
return val.toFixed(2);
|
||||
}, [amountTmt, quote]);
|
||||
|
||||
const totalTmt = useMemo(() => {
|
||||
if (!quote || amountTmt <= 0) return "";
|
||||
const val = amountTmt + quote.bankFeeTmt + quote.gbusFeeTmt;
|
||||
return val.toFixed(2);
|
||||
}, [amountTmt, quote]);
|
||||
|
||||
const isMonthCorrect = selectedMonth === currentMonthValue();
|
||||
|
||||
function handleSubmit() {
|
||||
if (!amountTmt || amountTmt <= 0) {
|
||||
toast.error(t("intlPayment.pay.amountRequired", "Töleg möçberini giriziň"));
|
||||
return;
|
||||
}
|
||||
if (quote && amountTmt > quote.maxAmountTmt) {
|
||||
toast.error(t("intlPayment.pay.amountExceedsMax", "Möçber iň ýokary möçberden geçýär"));
|
||||
return;
|
||||
}
|
||||
const paymentPeriod = buildPaymentPeriod(selectedMonth);
|
||||
pay({ id, payload: { amountTmt, paymentPeriod } }, { onSuccess: () => onOpenChange(false) });
|
||||
// Block every close path (ESC, overlay click, X button) while the payment request is in flight.
|
||||
function handleOpenChange(next: boolean) {
|
||||
if (isPaying) return;
|
||||
onOpenChange(next);
|
||||
}
|
||||
|
||||
if (!open) return null;
|
||||
function handleSubmit(payload: PayPayload) {
|
||||
pay({ id: stableId, payload }, { onSuccess: () => onOpenChange(false) });
|
||||
}
|
||||
|
||||
return (
|
||||
/* Overlay */
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
{/* Backdrop */}
|
||||
<div className="absolute inset-0 bg-black/40 backdrop-blur-sm" />
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-base font-bold uppercase tracking-widest">{t("intlPayment.pay.title", "Töleg")}</DialogTitle>
|
||||
<DialogDescription>{t("intlPayment.pay.instruction", 'Ýerine ýetirmek üçin "dowam et" düwmä basyň.')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Panel */}
|
||||
<div className="relative z-10 w-full max-w-lg mx-4 bg-white rounded-2xl shadow-2xl overflow-hidden">
|
||||
{/* Header */}
|
||||
<div className="px-6 pt-6 pb-4 border-b border-gray-100">
|
||||
<h2 className="text-base font-bold uppercase tracking-widest text-gray-800">{t("intlPayment.pay.title", "Töleg")}</h2>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="px-6 py-5 space-y-5">
|
||||
{/* Instruction */}
|
||||
<p className="text-sm text-gray-600">{t("intlPayment.pay.instruction", 'Ýerine ýetirmek üçin "dowam et" düwmä basyň.')}</p>
|
||||
|
||||
{/* Quote info */}
|
||||
{quoteLoading ? (
|
||||
<div className="flex items-center gap-2 text-sm text-gray-400">
|
||||
<Loader2 size={14} className="animate-spin" />
|
||||
{t("common.loading", "Ýüklenýär...")}
|
||||
</div>
|
||||
) : quote ? (
|
||||
<div className="text-xs font-semibold uppercase tracking-wide text-gray-700 space-y-0.5">
|
||||
<p>1 USD = {quote.exchangeRateUsd} TMT</p>
|
||||
<p>
|
||||
{t("intlPayment.pay.bankFee", "BANKYŇ TUTUMY")}: {quote.bankFeeTmt} TMT
|
||||
</p>
|
||||
<p>
|
||||
{t("intlPayment.pay.gbusFee", "GBÜS TUTUMY")}: {quote.gbusFeeTmt} TMT
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Töleg aý */}
|
||||
<div className="flex items-start gap-6">
|
||||
<label className="min-w-[120px] pt-2.5 text-sm text-gray-600">{t("intlPayment.pay.month", "Töleg aý")}</label>
|
||||
<div className="flex-1">
|
||||
<Select value={selectedMonth} onValueChange={setSelectedMonth}>
|
||||
<SelectTrigger className="w-full h-10 border-gray-200 rounded-lg text-sm focus:ring-1 focus:ring-primary focus:border-primary">
|
||||
<SelectValue placeholder={t("intlPayment.pay.selectMonth", "Aý saýlaň")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{MONTHS.map((m) => (
|
||||
<SelectItem key={m.value} value={m.value}>
|
||||
{m.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Töleg möçberi */}
|
||||
<div className="flex items-start gap-6">
|
||||
<label className="min-w-[120px] pt-2.5 text-sm text-gray-600">
|
||||
<span className="text-red-500 mr-1">*</span>
|
||||
{t("intlPayment.pay.amount", "Töleg möçberi (TMT)")}
|
||||
</label>
|
||||
<div className="flex-1">
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
max={quote?.maxAmountTmt}
|
||||
value={amountStr}
|
||||
onChange={(e) => setAmountStr(e.target.value)}
|
||||
className="w-full h-10 px-3 border-2 border-primary rounded-lg text-sm outline-none focus:ring-1 focus:ring-primary/40"
|
||||
placeholder="0"
|
||||
/>
|
||||
{quote && (
|
||||
<p className="mt-1 text-xs text-gray-400 italic">
|
||||
{t("intlPayment.pay.maxAmount", "Iň ýokary möçberi")}: {quote.maxAmountTmt} TMT
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* USD ekwalendi */}
|
||||
<div className="flex items-start gap-6">
|
||||
<label className="min-w-[120px] pt-2.5 text-sm text-gray-600">{t("intlPayment.pay.usdEquiv", "USD ekwalendi")}</label>
|
||||
<div className="flex-1">
|
||||
<input
|
||||
readOnly
|
||||
value={usdEquivalent}
|
||||
placeholder="0"
|
||||
className="w-full h-10 px-3 border border-gray-200 rounded-lg text-sm text-gray-400 bg-gray-50 outline-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Jemi */}
|
||||
<div className="flex items-start gap-6">
|
||||
<label className="min-w-[120px] pt-2.5 text-sm text-gray-600">{t("intlPayment.pay.total", "Jemi (TMT)")}</label>
|
||||
<div className="flex-1">
|
||||
<input
|
||||
readOnly
|
||||
value={totalTmt}
|
||||
placeholder="0"
|
||||
className="w-full h-10 px-3 border border-gray-200 rounded-lg text-sm text-gray-400 bg-gray-50 outline-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Wrong month warning */}
|
||||
{!isMonthCorrect && (
|
||||
<div className="flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-lg px-4 py-2.5 text-sm text-amber-700">
|
||||
<AlertCircle size={14} className="shrink-0" />
|
||||
{t("intlPayment.pay.wrongMonth", "Dogry töleg aýyny saýlamagyňyzy haýyş edýäris!!!!")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="px-6 pb-6 flex items-center justify-end gap-3">
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isPaying}>
|
||||
{t("intlPayment.pay.cancel", "Ýatyr")}
|
||||
</Button>
|
||||
<Button type="button" onClick={handleSubmit} disabled={isPaying || quoteLoading}>
|
||||
{isPaying ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<Loader2 size={14} className="animate-spin" />
|
||||
{t("common.saving", "Saklanýar...")}
|
||||
</span>
|
||||
) : (
|
||||
t("intlPayment.pay.confirm", "Dowam et")
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<PayForm id={stableId} isPaying={isPaying} onSubmit={handleSubmit} onCancel={() => handleOpenChange(false)} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -944,6 +944,15 @@
|
||||
"branches.sections.address": "Address and contact",
|
||||
"branches.sections.basic": "Basic information",
|
||||
"branches.sections.billing": "Billing credentials",
|
||||
"branches.steps.basic": "Basic information",
|
||||
"branches.steps.basic.shortLabel": "Basic",
|
||||
"branches.steps.basic.subtitle": "Name, unique code, region",
|
||||
"branches.steps.address": "Address and contact",
|
||||
"branches.steps.address.shortLabel": "Address",
|
||||
"branches.steps.address.subtitle": "Address, phone numbers",
|
||||
"branches.steps.billing": "Billing credentials",
|
||||
"branches.steps.billing.shortLabel": "Billing",
|
||||
"branches.steps.billing.subtitle": "Username and passwords",
|
||||
"branches.viewTitle": "Branch detail",
|
||||
"cardBalance.deleteConfirm": "Delete this card balance?",
|
||||
"cardBalance.deleteDescription": "This action is irreversible. The card balance will be permanently deleted.",
|
||||
@@ -1434,21 +1443,27 @@
|
||||
"roles.fields.guardName": "GUARD NAME",
|
||||
"roles.fields.name": "NAME",
|
||||
"roles.searchPlaceholder": "Search...",
|
||||
"branches.fields.name": "NAME",
|
||||
"branches.fields.region": "REGION",
|
||||
"branches.fields.district": "DISTRICT",
|
||||
"branches.fields.uniqueCode": "UNIQUE CODE",
|
||||
"branches.fields.isActive": "ACTIVE",
|
||||
"branches.fields.billingIbr": "BILLING USERNAME (IBR)",
|
||||
"branches.fields.billingPassword": "BILLING PASSWORD",
|
||||
"branches.fields.billingSber": "BILLING USERNAME (SBER)",
|
||||
"branches.fields.billingSberPassword": "PASSWORD (SBER)",
|
||||
"branches.fields.billingSwift": "BILLING USERNAME (SWIFT)",
|
||||
"branches.fields.billingSwiftPassword": "PASSWORD (SWIFT)",
|
||||
"branches.fields.address": "ADDRESS",
|
||||
"branches.fields.billingVisa": "BILLING USERNAME (VISA)",
|
||||
"branches.fields.billingVisaPassword": "PASSWORD (VISA)",
|
||||
"branches.fields.phoneNumbers": "PHONE NUMBERS",
|
||||
"branches.fields.name": "Branch name",
|
||||
"branches.fields.namePlaceholder": "Branch name",
|
||||
"branches.fields.region": "Region",
|
||||
"branches.fields.regionPlaceholder": "Ashgabat city",
|
||||
"branches.fields.district": "District",
|
||||
"branches.fields.districtPlaceholder": "Select district",
|
||||
"branches.fields.uniqueCode": "Unique code",
|
||||
"branches.fields.uniqueCodePlaceholder": "ORG-XXX-XXXX",
|
||||
"branches.fields.isActive": "Active",
|
||||
"branches.fields.billingIbr": "Billing username (IBR)",
|
||||
"branches.fields.billingPassword": "Billing password",
|
||||
"branches.fields.billingSber": "Billing username (SBER)",
|
||||
"branches.fields.billingSberPassword": "Password (SBER)",
|
||||
"branches.fields.billingSwift": "Billing username (SWIFT)",
|
||||
"branches.fields.billingSwiftPassword": "Password (SWIFT)",
|
||||
"branches.fields.address": "Address",
|
||||
"branches.fields.addressPlaceholder": "Address",
|
||||
"branches.fields.billingVisa": "Billing username (VISA)",
|
||||
"branches.fields.billingVisaPassword": "Password (VISA)",
|
||||
"branches.fields.phoneNumbers": "Phone numbers",
|
||||
"branches.fields.phoneNumbersPlaceholder": "+99312998877, +99365123456",
|
||||
"users.title": "All users",
|
||||
"users.searchPlaceholder": "Search",
|
||||
"users.createTitle": "Add New User",
|
||||
|
||||
@@ -945,6 +945,15 @@
|
||||
"branches.sections.address": "Адрес и контакты",
|
||||
"branches.sections.basic": "Основная информация",
|
||||
"branches.sections.billing": "Учетные данные биллинга",
|
||||
"branches.steps.basic": "Основные данные",
|
||||
"branches.steps.basic.shortLabel": "Основные",
|
||||
"branches.steps.basic.subtitle": "Название, уникальный код, велаят",
|
||||
"branches.steps.address": "Адрес и контакты",
|
||||
"branches.steps.address.shortLabel": "Адрес",
|
||||
"branches.steps.address.subtitle": "Адрес, телефоны",
|
||||
"branches.steps.billing": "Учетные данные биллинга",
|
||||
"branches.steps.billing.shortLabel": "Биллинг",
|
||||
"branches.steps.billing.subtitle": "Имя пользователя и пароли",
|
||||
"branches.viewTitle": "Детали филиала",
|
||||
"cardBalance.deleteConfirm": "Удалить баланс карты?",
|
||||
"cardBalance.deleteDescription": "Это действие необратимо. Баланс карты будет удалён безвозвратно.",
|
||||
@@ -1435,21 +1444,27 @@
|
||||
"roles.fields.guardName": "GUARD NAME",
|
||||
"roles.fields.name": "ИМЯ",
|
||||
"roles.searchPlaceholder": "Поиск...",
|
||||
"branches.fields.name": "НАЗВАНИЕ",
|
||||
"branches.fields.region": "ВЕЛАЯТ",
|
||||
"branches.fields.district": "РАЙОН",
|
||||
"branches.fields.uniqueCode": "УНИКАЛЬНЫЙ КОД",
|
||||
"branches.fields.isActive": "АКТИВНЫЙ",
|
||||
"branches.fields.billingIbr": "ЛОГИН БИЛЛИНГА (IBR)",
|
||||
"branches.fields.billingPassword": "ПАРОЛЬ БИЛЛИНГА",
|
||||
"branches.fields.billingSber": "ЛОГИН БИЛЛИНГА (SBER)",
|
||||
"branches.fields.billingSberPassword": "ПАРОЛЬ (SBER)",
|
||||
"branches.fields.billingSwift": "ЛОГИН БИЛЛИНГА (SWIFT)",
|
||||
"branches.fields.billingSwiftPassword": "ПАРОЛЬ (SWIFT)",
|
||||
"branches.fields.address": "АДРЕС",
|
||||
"branches.fields.billingVisa": "ЛОГИН БИЛЛИНГА (VISA)",
|
||||
"branches.fields.billingVisaPassword": "ПАРОЛЬ (VISA)",
|
||||
"branches.fields.phoneNumbers": "ТЕЛЕФОНЫ",
|
||||
"branches.fields.name": "Название филиала",
|
||||
"branches.fields.namePlaceholder": "Название филиала",
|
||||
"branches.fields.region": "Велаят",
|
||||
"branches.fields.regionPlaceholder": "г. Ашхабад",
|
||||
"branches.fields.district": "Район",
|
||||
"branches.fields.districtPlaceholder": "Выберите район",
|
||||
"branches.fields.uniqueCode": "Уникальный код",
|
||||
"branches.fields.uniqueCodePlaceholder": "ORG-XXX-XXXX",
|
||||
"branches.fields.isActive": "Активный",
|
||||
"branches.fields.billingIbr": "Логин биллинга (IBR)",
|
||||
"branches.fields.billingPassword": "Пароль биллинга",
|
||||
"branches.fields.billingSber": "Логин биллинга (SBER)",
|
||||
"branches.fields.billingSberPassword": "Пароль (SBER)",
|
||||
"branches.fields.billingSwift": "Логин биллинга (SWIFT)",
|
||||
"branches.fields.billingSwiftPassword": "Пароль (SWIFT)",
|
||||
"branches.fields.address": "Адрес",
|
||||
"branches.fields.addressPlaceholder": "Адрес",
|
||||
"branches.fields.billingVisa": "Логин биллинга (VISA)",
|
||||
"branches.fields.billingVisaPassword": "Пароль (VISA)",
|
||||
"branches.fields.phoneNumbers": "Номера телефонов",
|
||||
"branches.fields.phoneNumbersPlaceholder": "+99312998877, +99365123456",
|
||||
"users.title": "Все пользователи",
|
||||
"users.searchPlaceholder": "Поиск",
|
||||
"users.createTitle": "Создание пользователя",
|
||||
|
||||
@@ -942,6 +942,15 @@
|
||||
"branches.sections.address": "Salgy we habarlaşmak",
|
||||
"branches.sections.basic": "Esasy maglumatlar",
|
||||
"branches.sections.billing": "Billing maglumatlary",
|
||||
"branches.steps.basic": "Esasy maglumatlar",
|
||||
"branches.steps.basic.shortLabel": "Esasy",
|
||||
"branches.steps.basic.subtitle": "Ady, unikal belgisi, welaýaty",
|
||||
"branches.steps.address": "Salgy we habarlaşmak",
|
||||
"branches.steps.address.shortLabel": "Salgy",
|
||||
"branches.steps.address.subtitle": "Salgy, telefonlar",
|
||||
"branches.steps.billing": "Billing maglumatlary",
|
||||
"branches.steps.billing.shortLabel": "Billing",
|
||||
"branches.steps.billing.subtitle": "Ulanyjy ady we parollar",
|
||||
"branches.viewTitle": "Şahamça giňişleýin",
|
||||
"cardBalance.deleteConfirm": "Bu ýazgy pozulsynmy?",
|
||||
"cardBalance.deleteDescription": "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.",
|
||||
@@ -1433,21 +1442,27 @@
|
||||
"permissions.fields.name": "ADY",
|
||||
"permissions.fields.guardName": "GUARD NAME",
|
||||
"permissions.searchPlaceholder": "Gözlemek...",
|
||||
"branches.fields.name": "ADY",
|
||||
"branches.fields.region": "WELAÝAT",
|
||||
"branches.fields.district": "ETRAP",
|
||||
"branches.fields.uniqueCode": "UNIKAL BELGI",
|
||||
"branches.fields.isActive": "IŞJEŇ",
|
||||
"branches.fields.billingIbr": "BILLING ULANYJY ADY",
|
||||
"branches.fields.billingPassword": "BILLING PAROL",
|
||||
"branches.fields.billingSber": "BILLING USERNAME (SBER)",
|
||||
"branches.fields.billingSberPassword": "PAROL (SBER)",
|
||||
"branches.fields.billingSwift": "BILLING ULANYJY ADY (SWIFT)",
|
||||
"branches.fields.billingSwiftPassword": "PAROL (SWIFT)",
|
||||
"branches.fields.address": "SALGY",
|
||||
"branches.fields.billingVisa": "BILLING USERNAME (VISA)",
|
||||
"branches.fields.billingVisaPassword": "PAROL (VISA)",
|
||||
"branches.fields.phoneNumbers": "TELEFONLAR",
|
||||
"branches.fields.name": "Şahamçanyň ady",
|
||||
"branches.fields.namePlaceholder": "Şahamçanyň ady",
|
||||
"branches.fields.region": "Welaýat",
|
||||
"branches.fields.regionPlaceholder": "Aşgabat şäheri",
|
||||
"branches.fields.district": "Etrap",
|
||||
"branches.fields.districtPlaceholder": "Etrap saýlaň",
|
||||
"branches.fields.uniqueCode": "Unikal belgisi",
|
||||
"branches.fields.uniqueCodePlaceholder": "ORG-XXX-XXXX",
|
||||
"branches.fields.isActive": "Işjeň",
|
||||
"branches.fields.billingIbr": "Billing ulanyjy ady",
|
||||
"branches.fields.billingPassword": "Billing paroly",
|
||||
"branches.fields.billingSber": "Billing ulanyjy ady (SBER)",
|
||||
"branches.fields.billingSberPassword": "Parol (SBER)",
|
||||
"branches.fields.billingSwift": "Billing ulanyjy ady (SWIFT)",
|
||||
"branches.fields.billingSwiftPassword": "Parol (SWIFT)",
|
||||
"branches.fields.address": "Salgy",
|
||||
"branches.fields.addressPlaceholder": "Salgy",
|
||||
"branches.fields.billingVisa": "Billing ulanyjy ady (VISA)",
|
||||
"branches.fields.billingVisaPassword": "Parol (VISA)",
|
||||
"branches.fields.phoneNumbers": "Telefonlar",
|
||||
"branches.fields.phoneNumbersPlaceholder": "+99312998877, +99365123456",
|
||||
"users.title": "Ähli ulanyjylar",
|
||||
"users.searchPlaceholder": "Gözlemek",
|
||||
"users.createTitle": "Ulanyjy döretmek",
|
||||
|
||||
@@ -1,163 +1,17 @@
|
||||
// pages/OnlinePaymentHistoryPage.tsx
|
||||
|
||||
import { useState } from "react";
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Eye, Rss } from "lucide-react";
|
||||
import { Eye } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
||||
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
||||
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import type { VisibilityState } from "@tanstack/react-table";
|
||||
import { useGetOnlinePayments, useTriggerPaymentCallback } from "@/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory";
|
||||
import { useGetOnlinePayments } from "@/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory";
|
||||
import type { OnlinePayment } from "@/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi";
|
||||
import { PaymentStatusBadge } from "../../features/onlinePaymentHistory/components/PaymentStatusBadge";
|
||||
|
||||
// ─── Defaults ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const DEFAULT_VISIBILITY = {
|
||||
amount: true,
|
||||
apiClient: true,
|
||||
description: true,
|
||||
status: true,
|
||||
username: true,
|
||||
createdAt: true,
|
||||
};
|
||||
const DEFAULT_ORDER = ["amount", "apiClient", "description", "status", "username", "createdAt", "actions"];
|
||||
|
||||
// ─── OnlinePaymentHistoryPage ─────────────────────────────────────────────────
|
||||
|
||||
export default function OnlinePaymentHistoryPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage] = useState(25);
|
||||
const [search, setSearch] = useState("");
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(DEFAULT_VISIBILITY);
|
||||
const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER);
|
||||
|
||||
const { data, isLoading } = useGetOnlinePayments({ page, perPage, search });
|
||||
const callbackMutation = useTriggerPaymentCallback();
|
||||
|
||||
const handleSearchChange = (val: string) => {
|
||||
setSearch(val);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
// ─── Columns ──────────────────────────────────────────────────────────────
|
||||
|
||||
const columns: ColumnDef<OnlinePayment>[] = [
|
||||
{
|
||||
accessorKey: "amount",
|
||||
header: t("onlinePayments.columns.amount", "MÖÇBERI"),
|
||||
cell: ({ row }) => <span className="tabular-nums text-foreground font-medium">{row.original.amount}</span>,
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
accessorKey: "apiClient",
|
||||
header: t("onlinePayments.columns.apiClient", "API CLIENT"),
|
||||
cell: ({ row }) => <span className="text-foreground text-xs font-mono truncate max-w-[180px] block">{row.original.apiClient}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "description",
|
||||
header: t("onlinePayments.columns.description", "DESC"),
|
||||
cell: ({ row }) => <span className="text-foreground text-sm">{row.original.description}</span>,
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: t("onlinePayments.columns.status", "STATUS"),
|
||||
cell: ({ row }) => <PaymentStatusBadge status={row.original.status} />,
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
accessorKey: "username",
|
||||
header: t("onlinePayments.columns.username", "USERNAME"),
|
||||
cell: ({ row }) => <span className="text-foreground text-xs font-mono">{row.original.username}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: t("onlinePayments.columns.createdAt", "DÖREDILEN WAGTY"),
|
||||
cell: ({ row }) => <span className="text-muted-foreground text-xs whitespace-nowrap">{formatDateTime(row.original.createdAt)}</span>,
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
{/* Callback trigger */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||
disabled={callbackMutation.isPending}
|
||||
onClick={() => callbackMutation.mutate(row.original.id)}
|
||||
title={t("onlinePayments.actions.callback", "Callback ugrat")}
|
||||
>
|
||||
<Rss size={15} />
|
||||
</Button>
|
||||
{/* View detail */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => navigate(`/online-payments-history/${row.original.id}`)}
|
||||
title={t("common.view", "Görmek")}
|
||||
>
|
||||
<Eye size={15} />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
size: 90,
|
||||
},
|
||||
];
|
||||
|
||||
const columnMeta = columns
|
||||
.filter((c) => "accessorKey" in c && c.accessorKey)
|
||||
.map((c) => ({
|
||||
id: String(("accessorKey" in c ? c.accessorKey : c.id) ?? ""),
|
||||
label: typeof c.header === "string" ? c.header : "",
|
||||
}));
|
||||
|
||||
// ─── Render ───────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-foreground mb-5">{t("onlinePayments.title", "Onlaýn töleg taryhy")}</h1>
|
||||
<DataTable
|
||||
toolbar={
|
||||
<DataTableToolbar
|
||||
searchValue={search}
|
||||
onSearchChange={handleSearchChange}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={columnMeta}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
hideAction
|
||||
/>
|
||||
}
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
enableRowSelection
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={data?.totalPages ?? 1}
|
||||
totalCount={data?.total ?? 0}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
import { GatewayStatusBadge, PaidBadge } from "../../features/onlinePaymentHistory/components/PaymentStatusBadge";
|
||||
import { useInfiniteBranches } from "@/features/branches/hooks/useBranches";
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -170,3 +24,304 @@ function formatDateTime(iso: string): string {
|
||||
const yy = d.getFullYear();
|
||||
return `${hh}:${mm}, ${dd}.${mo}.${yy}`;
|
||||
}
|
||||
|
||||
/** Map i18n language code → backend localized text key. */
|
||||
function resolveLang(lang: string): "en" | "ru" | "tm" {
|
||||
if (lang === "ru") return "ru";
|
||||
if (lang === "tk") return "tm";
|
||||
return "en";
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const COLUMN_IDS = ["id", "orderId", "type", "branchName", "passport", "totalAmountTmt", "gatewayStatus", "paid", "createdAt"] as const;
|
||||
|
||||
const DEFAULT_VISIBILITY: VisibilityState = {
|
||||
id: true,
|
||||
orderId: true,
|
||||
type: true,
|
||||
branchName: true,
|
||||
passport: true,
|
||||
totalAmountTmt: true,
|
||||
gatewayStatus: true,
|
||||
paid: true,
|
||||
createdAt: true,
|
||||
};
|
||||
|
||||
const DEFAULT_ORDER = [...COLUMN_IDS, "actions"];
|
||||
|
||||
/** Gateway status options for the filter dropdown. */
|
||||
const GATEWAY_STATUS_OPTIONS = [
|
||||
{ value: "success", label: "Success" },
|
||||
{ value: "failed", label: "Failed" },
|
||||
{ value: "pending", label: "Pending" },
|
||||
{ value: "processing", label: "Processing" },
|
||||
];
|
||||
|
||||
// ─── OnlinePaymentHistoryPage ─────────────────────────────────────────────────
|
||||
|
||||
export default function OnlinePaymentHistoryPage() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const lang = resolveLang(i18n.language);
|
||||
|
||||
// ─── Pagination & search
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
// ─── Column state
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(DEFAULT_VISIBILITY);
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([...DEFAULT_ORDER]);
|
||||
|
||||
// ─── Filters — fieldId matches query param name for easy mapping
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
{ fieldId: "status", value: "" },
|
||||
{ fieldId: "branchId", value: "" },
|
||||
{ fieldId: "orderId", value: "" },
|
||||
{ fieldId: "userId", value: "" },
|
||||
]);
|
||||
|
||||
// ─── Branch infinite-select data
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const {
|
||||
data: branchesInfiniteData,
|
||||
fetchNextPage: fetchNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
isFetchingNextPage: isFetchingNextBranches,
|
||||
isLoading: isBranchesLoading,
|
||||
} = useInfiniteBranches(branchSearch);
|
||||
|
||||
const branchOptions = useMemo(
|
||||
() =>
|
||||
(branchesInfiniteData?.pages ?? []).flatMap((p) =>
|
||||
(p?.branches ?? []).map((b) => ({
|
||||
value: String(b.id),
|
||||
label: b.name[lang] || b.name.tm,
|
||||
})),
|
||||
),
|
||||
[branchesInfiniteData, lang],
|
||||
);
|
||||
|
||||
// ─── Derive query params from active filters
|
||||
const filterMap = useMemo(() => Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value])), [activeFilters]);
|
||||
|
||||
const queryParams = useMemo(
|
||||
() => ({
|
||||
page,
|
||||
limit: perPage,
|
||||
search: search || undefined,
|
||||
status: filterMap.status || undefined,
|
||||
branchId: filterMap.branchId ? Number(filterMap.branchId) : undefined,
|
||||
orderId: filterMap.orderId ? Number(filterMap.orderId) : undefined,
|
||||
userId: filterMap.userId ? Number(filterMap.userId) : undefined,
|
||||
}),
|
||||
[page, perPage, search, filterMap],
|
||||
);
|
||||
|
||||
const { data, isLoading } = useGetOnlinePayments(queryParams);
|
||||
|
||||
// ─── Handlers
|
||||
const handleSearchChange = useCallback((val: string) => {
|
||||
setSearch(val);
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setActiveFilters((prev) => prev.map((f) => ({ ...f, value: "" })));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
// ─── Filter field definitions
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "status",
|
||||
label: t("onlinePayments.filters.status", "Status"),
|
||||
type: "select",
|
||||
options: GATEWAY_STATUS_OPTIONS,
|
||||
},
|
||||
{
|
||||
id: "branchId",
|
||||
label: t("onlinePayments.filters.branch", "Branch"),
|
||||
type: "infinite-select",
|
||||
options: branchOptions,
|
||||
loading: isBranchesLoading,
|
||||
isLoadingMore: isFetchingNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
onLoadMore: fetchNextBranches,
|
||||
searchValue: branchSearch,
|
||||
onSearchChange: setBranchSearch,
|
||||
},
|
||||
{
|
||||
id: "orderId",
|
||||
label: t("onlinePayments.filters.orderId", "Order ID"),
|
||||
type: "text",
|
||||
},
|
||||
{
|
||||
id: "userId",
|
||||
label: t("onlinePayments.filters.userId", "User ID"),
|
||||
type: "text",
|
||||
},
|
||||
],
|
||||
[t, branchOptions, isBranchesLoading, isFetchingNextBranches, hasNextBranches, branchSearch],
|
||||
);
|
||||
|
||||
// ─── Columns
|
||||
const columns = useMemo<ColumnDef<OnlinePayment>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("onlinePayments.columns.id", "ID"),
|
||||
cell: ({ row }) => <span className="tabular-nums text-foreground font-medium">{row.original.id}</span>,
|
||||
size: 50,
|
||||
},
|
||||
{
|
||||
id: "orderId",
|
||||
accessorKey: "orderId",
|
||||
header: t("onlinePayments.columns.orderId", "ORDER ID"),
|
||||
cell: ({ row }) => <span className="tabular-nums text-foreground font-medium">{row.original.orderId}</span>,
|
||||
size: 90,
|
||||
},
|
||||
{
|
||||
id: "type",
|
||||
accessorKey: "type",
|
||||
header: t("onlinePayments.columns.type", "TYPE"),
|
||||
cell: ({ row }) => <span className="text-xs font-semibold uppercase tracking-wide text-foreground">{row.original.type}</span>,
|
||||
size: 80,
|
||||
},
|
||||
{
|
||||
id: "branchName",
|
||||
accessorKey: "branchName",
|
||||
header: t("onlinePayments.columns.branch", "BRANCH"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground truncate max-w-[200px] block">
|
||||
{row.original.branchName?.[lang] ?? row.original.branchName?.en ?? "—"}
|
||||
</span>
|
||||
),
|
||||
size: 200,
|
||||
},
|
||||
{
|
||||
id: "passport",
|
||||
accessorKey: "passport",
|
||||
header: t("onlinePayments.columns.passport", "PASSPORT"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground">
|
||||
{row.original.passportName} {row.original.passportSurname}
|
||||
</span>
|
||||
),
|
||||
size: 150,
|
||||
},
|
||||
{
|
||||
id: "totalAmountTmt",
|
||||
accessorKey: "totalAmountTmt",
|
||||
header: t("onlinePayments.columns.totalAmount", "TOTAL (TMT)"),
|
||||
cell: ({ row }) => <span className="tabular-nums text-foreground font-medium">{row.original.totalAmountTmt.toLocaleString()}</span>,
|
||||
size: 110,
|
||||
},
|
||||
{
|
||||
id: "gatewayStatus",
|
||||
accessorKey: "gatewayStatus",
|
||||
header: t("onlinePayments.columns.gatewayStatus", "GATEWAY STATUS"),
|
||||
cell: ({ row }) => <GatewayStatusBadge status={row.original.gatewayStatus} />,
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
id: "paid",
|
||||
accessorKey: "paid",
|
||||
header: t("onlinePayments.columns.paid", "PAID"),
|
||||
cell: ({ row }) => <PaidBadge paid={row.original.paid} />,
|
||||
size: 90,
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: t("onlinePayments.columns.createdAt", "CREATED AT"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-muted-foreground text-xs whitespace-nowrap">{formatDateTime(row.original.createdAt)}</span>
|
||||
),
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => navigate(`/online-payments-history/${row.original.orderId}`)}
|
||||
title={t("common.view", "Görmek")}
|
||||
>
|
||||
<Eye size={15} />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
size: 60,
|
||||
},
|
||||
],
|
||||
[t, navigate, lang],
|
||||
);
|
||||
|
||||
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`onlinePayments.columns.${id}`, id) })), [t]);
|
||||
|
||||
// ─── Derived pagination
|
||||
const totalCount = data?.count ?? 0;
|
||||
const totalPages = Math.ceil(totalCount / perPage) || 1;
|
||||
|
||||
// ─── Render ───────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("onlinePayments.title", "Onlaýn töleg taryhy")}</h1>
|
||||
|
||||
<DataTable
|
||||
toolbar={
|
||||
<DataTableToolbar
|
||||
searchValue={search}
|
||||
onSearchChange={handleSearchChange}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={toggleableColumns}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
hideAction
|
||||
filterFields={filterFields}
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
perPageOptions={[10, 25, 50, 100]}
|
||||
perPage={perPage}
|
||||
onPerPageChange={(v) => {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
columns={columns}
|
||||
data={data?.items ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
enableRowSelection
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={totalPages}
|
||||
totalCount={totalCount}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,78 +2,11 @@
|
||||
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Section, InfoRow } from "@/components/viewPageComponents";
|
||||
import { Section } from "@/components/viewPageComponents";
|
||||
import { useGetOnlinePaymentById } from "@/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory";
|
||||
import { PaymentStatusBadge } from "../../features/onlinePaymentHistory/components/PaymentStatusBadge";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
// ─── OnlinePaymentDetailPage ──────────────────────────────────────────────────
|
||||
|
||||
export default function OnlinePaymentDetailPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const numericId = Number(id);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { data: payment, isLoading } = useGetOnlinePaymentById(numericId);
|
||||
|
||||
// ─── Loading skeleton ──────────────────────────────────────────────────────
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="p-6 space-y-4">
|
||||
<Skeleton className="h-6 w-96" />
|
||||
<Skeleton className="h-[560px] w-full rounded-xl" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!payment) {
|
||||
return (
|
||||
<div className="p-6">
|
||||
<p className="text-muted-foreground">{t("onlinePayments.notFound", "Töleg tapylmady")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const title = `${t("onlinePayments.detail.title", "Onlaýn töleg taryhy giňişleýin")}: ${payment.orderId}`;
|
||||
|
||||
// ─── Render ───────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground mb-6 break-all">{title}</h1>
|
||||
|
||||
{/* Detail Card */}
|
||||
<Section>
|
||||
<InfoRow label={t("common.id", "ID")} value={payment.id} />
|
||||
<InfoRow label={t("onlinePayments.fields.amount", "amount")} value={payment.amount} />
|
||||
<InfoRow label={t("onlinePayments.fields.orderNumber", "orderNumber")} value={payment.orderNumber} />
|
||||
<InfoRow label={t("onlinePayments.fields.apiClient", "Api Client")} value={payment.apiClient} />
|
||||
<InfoRow label={t("onlinePayments.fields.description", "description")} value={payment.description} />
|
||||
<InfoRow label={t("onlinePayments.fields.orderId", "orderId")} value={payment.orderId} />
|
||||
<InfoRow label={t("onlinePayments.fields.formUrl", "formUrl")} isLink href={payment.formUrl ?? undefined} value={payment.formUrl} />
|
||||
<InfoRow
|
||||
label={t("onlinePayments.fields.successUrl", "successUrl")}
|
||||
isLink
|
||||
href={payment.successUrl ?? undefined}
|
||||
value={payment.successUrl}
|
||||
/>
|
||||
<InfoRow label={t("onlinePayments.fields.status", "Status")}>
|
||||
<PaymentStatusBadge status={payment.status} />
|
||||
</InfoRow>
|
||||
<InfoRow label={t("onlinePayments.fields.callbackStatus", "callbackStatus")} value={payment.callbackStatus ?? "—"} />
|
||||
<InfoRow label={t("onlinePayments.fields.username", "username")} value={payment.username} />
|
||||
<InfoRow label={t("onlinePayments.fields.onlinePaymantableId", "online_paymantable_id")} value={payment.onlinePaymantableId} />
|
||||
<InfoRow
|
||||
label={t("onlinePayments.fields.onlinePaymantableType", "online_paymantable_type")}
|
||||
value={payment.onlinePaymantableType}
|
||||
/>
|
||||
<InfoRow label={t("onlinePayments.fields.createdAt", "Döredilen wagty")} value={formatDateTime(payment.createdAt)} />
|
||||
<InfoRow label={t("onlinePayments.fields.updatedAt", "Updated at")} value={formatDateTime(payment.updatedAt)} />
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
import type { PaymentHistoryStep } from "@/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi";
|
||||
import { GatewayStatusBadge } from "@/features/onlinePaymentHistory/components/PaymentStatusBadge";
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -86,3 +19,96 @@ function formatDateTime(iso: string): string {
|
||||
const yy = d.getFullYear();
|
||||
return `${hh}:${mm}, ${dd}.${mo}.${yy}`;
|
||||
}
|
||||
|
||||
// ─── StepRow ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function StepRow({ step }: { step: PaymentHistoryStep }) {
|
||||
const detailEntries = Object.entries(step.detail ?? {});
|
||||
|
||||
return (
|
||||
<div className="flex gap-4 relative">
|
||||
{/* Timeline line */}
|
||||
<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>
|
||||
|
||||
{/* Content */}
|
||||
<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]">{key}</span>
|
||||
<span className="text-foreground break-all">{String(value)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── OnlinePaymentDetailPage ──────────────────────────────────────────────────
|
||||
|
||||
export default function OnlinePaymentDetailPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const numericId = Number(id);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { data: steps, isLoading } = useGetOnlinePaymentById(numericId);
|
||||
|
||||
// ─── Loading skeleton ──────────────────────────────────────────────────────
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="p-6 space-y-4">
|
||||
<Skeleton className="h-6 w-72" />
|
||||
<Skeleton className="h-[400px] w-full rounded-xl" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!steps || steps.length === 0) {
|
||||
return (
|
||||
<div className="p-6">
|
||||
<p className="text-muted-foreground">{t("onlinePayments.noHistory", "Töleg taryhy tapylmady")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const orderId = steps[0]?.orderId;
|
||||
|
||||
// ─── Render ───────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground mb-6">
|
||||
{t("onlinePayments.detail.title", "Onlaýn töleg taryhy giňişleýin")}
|
||||
{orderId ? ` — Order #${orderId}` : ""}
|
||||
</h1>
|
||||
|
||||
<Section>
|
||||
<div className="px-1 py-2">
|
||||
<p className="text-sm font-medium text-muted-foreground mb-6">
|
||||
{t("onlinePayments.detail.stepsCount", "Ädimler")}: {steps.length}
|
||||
</p>
|
||||
|
||||
{/* Timeline */}
|
||||
<div>
|
||||
{steps.map((step) => (
|
||||
<StepRow key={step.id} step={step} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user