416 lines
16 KiB
TypeScript
416 lines
16 KiB
TypeScript
import { useEffect, useId, useMemo, useRef, useState } from "react";
|
|
import type { ChangeEvent, FormEvent, ReactNode } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
import { AlertCircle, CheckCircle2, ExternalLink, Loader2, XCircle } from "lucide-react";
|
|
import { useQuoteIntlPayment, usePayIntlPayment, useCheckIntlPaymentCallback } from "../hooks/useVisaMasterPayments";
|
|
import type { PaymentCallbackResponse, PayResponse } from "../api/visaMasterPaymentsApi";
|
|
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";
|
|
|
|
// ─── Constants ────────────────────────────────────────────────────────────────
|
|
|
|
const MONTHS = [
|
|
{ value: "01", label: "Ýanwar" },
|
|
{ value: "02", label: "Fewral" },
|
|
{ value: "03", label: "Mart" },
|
|
{ value: "04", label: "Aprel" },
|
|
{ value: "05", label: "Maý" },
|
|
{ value: "06", label: "Iýun" },
|
|
{ value: "07", label: "Iýul" },
|
|
{ value: "08", label: "Awgust" },
|
|
{ value: "09", label: "Sentýabr" },
|
|
{ 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 {
|
|
return String(new Date().getMonth() + 1).padStart(2, "0");
|
|
}
|
|
|
|
function currentMonthLabel(monthValue: string, t: ReturnType<typeof useTranslation>["t"]): string {
|
|
const month = MONTHS.find((m) => m.value === monthValue);
|
|
return month ? t(`intlPayment.pay.months.${month.value}`, month.label) : monthValue;
|
|
}
|
|
|
|
/** Last day of the selected month in the current year, as YYYY-MM-DD */
|
|
function buildPaymentPeriod(monthValue: string): string {
|
|
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 [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: "" };
|
|
// gbusFeeTmt/tvebFeeTmt are mutually exclusive on the backend (visa/master
|
|
// orders set gbusFeeTmt, sber orders set tvebFeeTmt instead) - never both.
|
|
const extraFeeTmt = quote.gbusFeeTmt ?? quote.tvebFeeTmt ?? 0;
|
|
return {
|
|
usdEquivalent: quote.exchangeRateUsd > 0 ? (amountTmt / quote.exchangeRateUsd).toFixed(2) : "",
|
|
totalTmt: fromMinor(toMinor(amountTmt) + toMinor(quote.bankFeeTmt) + toMinor(extraFeeTmt)),
|
|
};
|
|
}, [amountTmt, quote]);
|
|
|
|
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(currentMonth) });
|
|
}
|
|
|
|
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>
|
|
{quote.gbusFeeTmt != null && (
|
|
<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>
|
|
)}
|
|
{quote.tvebFeeTmt != null && (
|
|
<div className="flex justify-between gap-4">
|
|
<dt className="text-muted-foreground">{t("intlPayment.pay.tvebFee", "TVEB TUTUMY")}</dt>
|
|
<dd>{quote.tvebFeeTmt} TMT</dd>
|
|
</div>
|
|
)}
|
|
</dl>
|
|
) : null}
|
|
|
|
{/* Töleg aý */}
|
|
<FieldRow label={t("intlPayment.pay.month", "Töleg aý")} htmlFor={monthId}>
|
|
<Input id={monthId} readOnly tabIndex={-1} value={currentMonthLabel(currentMonth, t)} className="bg-muted text-muted-foreground" />
|
|
</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>
|
|
|
|
<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 {
|
|
id: string;
|
|
open: boolean;
|
|
onOpenChange: (open: boolean) => void;
|
|
}
|
|
|
|
export function PayDialog({ id, open, onOpenChange }: PayDialogProps) {
|
|
const { t } = useTranslation();
|
|
const { mutate: pay, isPending: isPaying } = usePayIntlPayment();
|
|
const { mutate: checkCallback, isPending: isChecking } = useCheckIntlPaymentCallback();
|
|
const [paymentInit, setPaymentInit] = useState<PayResponse | null>(null);
|
|
const [paymentResult, setPaymentResult] = useState<PaymentCallbackResponse | null>(null);
|
|
|
|
// Tracks the open bank-page popup so it can be polled for navigation back
|
|
// to successUrl (GBÜS's callback) - see watchBankPage.
|
|
const popupRef = useRef<Window | null>(null);
|
|
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
|
|
|
// 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);
|
|
|
|
function stopWatchingBankPage() {
|
|
if (pollRef.current != null) {
|
|
clearInterval(pollRef.current);
|
|
pollRef.current = null;
|
|
}
|
|
popupRef.current = null;
|
|
}
|
|
|
|
// Once GBÜS returns to its backend callback URL, send the popup to our
|
|
// callback page. That page requests the final payment state and informs the user.
|
|
function watchBankPage(popup: Window, successUrl: string, paymentId: number) {
|
|
stopWatchingBankPage();
|
|
popupRef.current = popup;
|
|
pollRef.current = setInterval(() => {
|
|
const win = popupRef.current;
|
|
if (!win || win.closed) {
|
|
stopWatchingBankPage();
|
|
return;
|
|
}
|
|
let href: string;
|
|
try {
|
|
href = win.location.href;
|
|
} catch {
|
|
return;
|
|
}
|
|
if (href.startsWith(successUrl)) {
|
|
stopWatchingBankPage();
|
|
win.location.replace(
|
|
new URL(`visa-master/payment-callback?paymentId=${paymentId}`, `${window.location.origin}${import.meta.env.BASE_URL}`).href,
|
|
);
|
|
}
|
|
}, 1500);
|
|
}
|
|
|
|
// Stop polling on unmount so a closed dialog never keeps a timer alive.
|
|
useEffect(() => stopWatchingBankPage, []);
|
|
|
|
useEffect(() => {
|
|
if (!id || id === stableId) return;
|
|
setStableId(id);
|
|
setPaymentInit(null);
|
|
setPaymentResult(null);
|
|
stopWatchingBankPage();
|
|
}, [id, stableId]);
|
|
|
|
// Block every close path (ESC, overlay click, X button) while the payment request is in flight.
|
|
function handleOpenChange(next: boolean) {
|
|
if (isPaying || isChecking) return;
|
|
if (!next) {
|
|
setPaymentInit(null);
|
|
setPaymentResult(null);
|
|
stopWatchingBankPage();
|
|
}
|
|
onOpenChange(next);
|
|
}
|
|
|
|
function handleSubmit(payload: PayPayload) {
|
|
// Reserving the window while this click is still a user gesture prevents
|
|
// browsers from blocking the bank popup after the async status check.
|
|
const bankPopup = window.open("", "_blank");
|
|
if (bankPopup) {
|
|
try {
|
|
bankPopup.opener = null;
|
|
} catch {
|
|
// Some browsers disallow this; navigation can still continue.
|
|
}
|
|
}
|
|
|
|
pay(
|
|
{ id: stableId, payload },
|
|
{
|
|
onSuccess: (data) => {
|
|
setPaymentInit(data);
|
|
setPaymentResult(null);
|
|
|
|
const paymentId = data.paymentId;
|
|
if (!paymentId) {
|
|
bankPopup?.close();
|
|
return;
|
|
}
|
|
|
|
checkCallback(paymentId, {
|
|
onSuccess: (result) => {
|
|
setPaymentResult(result);
|
|
if (result.paid || !data.formUrl) {
|
|
bankPopup?.close();
|
|
return;
|
|
}
|
|
|
|
if (!bankPopup) {
|
|
window.location.href = data.formUrl;
|
|
return;
|
|
}
|
|
|
|
bankPopup.location.href = data.formUrl;
|
|
if (data.successUrl) watchBankPage(bankPopup, data.successUrl, paymentId);
|
|
},
|
|
onError: () => bankPopup?.close(),
|
|
});
|
|
},
|
|
onError: () => bankPopup?.close(),
|
|
},
|
|
);
|
|
}
|
|
|
|
return (
|
|
<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>
|
|
{paymentInit
|
|
? t("intlPayment.pay.statusInstruction", "Bank sahypasynda tölegi tamamlandan soň netijäni barlaň.")
|
|
: t("intlPayment.pay.instruction", 'Ýerine ýetirmek üçin "dowam et" düwmä basyň.')}
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
{paymentInit ? (
|
|
<div className="space-y-4">
|
|
<Alert>
|
|
{isChecking ? <Loader2 className="h-4 w-4 animate-spin" /> : <ExternalLink className="h-4 w-4" />}
|
|
<AlertDescription>
|
|
{isChecking
|
|
? t("intlPayment.pay.checkingStatus", "Töleg ýagdaýy barlanýar...")
|
|
: paymentResult?.paid
|
|
? t("intlPayment.paySuccess", "Töleg üstünlikli amala aşyryldy")
|
|
: t("intlPayment.pay.bankPageOpened", "Bankyň töleg sahypasy açyldy.")}
|
|
</AlertDescription>
|
|
</Alert>
|
|
|
|
{paymentResult ? (
|
|
<Alert variant={paymentResult.paid ? "default" : "destructive"}>
|
|
{paymentResult.paid ? <CheckCircle2 className="h-4 w-4" /> : <XCircle className="h-4 w-4" />}
|
|
<AlertDescription>{paymentResult.data}</AlertDescription>
|
|
</Alert>
|
|
) : null}
|
|
|
|
<DialogFooter className="gap-2">
|
|
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={isChecking}>
|
|
{t("common.close", "Ýap")}
|
|
</Button>
|
|
</DialogFooter>
|
|
</div>
|
|
) : (
|
|
<PayForm id={stableId} isPaying={isPaying} onSubmit={handleSubmit} onCancel={() => handleOpenChange(false)} />
|
|
)}
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|