updated payment

This commit is contained in:
Jelaletdin12 committed 2026-09-22 18:01:18 +05:00
1 parent 61a0995ea4
commit cc3c718861
4 files changed
+243 -53

No files matched your search

@@ -1,14 +1,14 @@
import { useId, useMemo, useState } from "react";
import { useEffect, useId, useMemo, useRef, useState } from "react";
import type { ChangeEvent, FormEvent, ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { AlertCircle, Loader2 } from "lucide-react";
import { useQuoteIntlPayment, usePayIntlPayment } from "../hooks/useVisaMasterPayments";
import { AlertCircle, CheckCircle2, ExternalLink, Loader2, RefreshCw, XCircle } from "lucide-react";
import { useQuoteIntlPayment, usePayIntlPayment, useCheckIntlPaymentStatus } from "../hooks/useVisaMasterPayments";
import type { PaymentResultResponse, 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";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
// ─── Constants ────────────────────────────────────────────────────────────────
@@ -36,6 +36,11 @@ 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();
@@ -73,6 +78,27 @@ function FieldRow({ label, htmlFor, required, children }: FieldRowProps) {
);
}
// Opens the bank's hosted payment page and returns the window handle so the
// caller can watch it for navigation back to successUrl (see watchBankPage
// below) - noopener/noreferrer would make window.open return null, so the
// opener link is severed from our side instead (popup.opener = null) once we
// have the handle, keeping the same tabnabbing mitigation. A popup blocker
// falls back to a same-tab navigation, which returns null - there's nothing
// to watch then, but the manual "Netijäni barla" button still works.
function openBankPage(formUrl: string): Window | null {
const popup = window.open(formUrl, "_blank");
if (!popup || popup.closed || typeof popup.closed === "undefined") {
window.location.href = formUrl;
return null;
}
try {
popup.opener = null;
} catch {
// some browsers disallow this - not fatal, just skip the mitigation
}
return popup;
}
// ─── Form (mounted only while the dialog is open → state resets automatically) ─
interface PayPayload {
@@ -97,7 +123,6 @@ function PayForm({ id, isPaying, onSubmit, onCancel }: PayFormProps) {
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);
@@ -106,14 +131,15 @@ function PayForm({ id, isPaying, onSubmit, onCancel }: PayFormProps) {
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(quote.gbusFeeTmt)),
totalTmt: fromMinor(toMinor(amountTmt) + toMinor(quote.bankFeeTmt) + toMinor(extraFeeTmt)),
};
}, [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;
@@ -128,7 +154,7 @@ function PayForm({ id, isPaying, onSubmit, onCancel }: PayFormProps) {
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!canSubmit) return;
onSubmit({ amountTmt, paymentPeriod: buildPaymentPeriod(selectedMonth) });
onSubmit({ amountTmt, paymentPeriod: buildPaymentPeriod(currentMonth) });
}
return (
@@ -159,27 +185,24 @@ function PayForm({ id, isPaying, onSubmit, onCancel }: PayFormProps) {
<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>
{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}>
<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>
<Input id={monthId} readOnly tabIndex={-1} value={currentMonthLabel(currentMonth, t)} className="bg-muted text-muted-foreground" />
</FieldRow>
{/* Töleg möçberi */}
@@ -218,14 +241,6 @@ function PayForm({ id, isPaying, onSubmit, onCancel }: PayFormProps) {
<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")}
@@ -256,20 +271,100 @@ interface PayDialogProps {
export function PayDialog({ id, open, onOpenChange }: PayDialogProps) {
const { t } = useTranslation();
const { mutate: pay, isPending: isPaying } = usePayIntlPayment();
const { mutate: checkStatus, isPending: isChecking } = useCheckIntlPaymentStatus();
const [paymentInit, setPaymentInit] = useState<PayResponse | null>(null);
const [paymentResult, setPaymentResult] = useState<PaymentResultResponse | 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);
if (id && id !== stableId) setStableId(id);
function stopWatchingBankPage() {
if (pollRef.current != null) {
clearInterval(pollRef.current);
pollRef.current = null;
}
popupRef.current = null;
}
// GBÜS redirects the popup to successUrl (the backend's own callback URL)
// once the bank-side flow ends. Reading a cross-origin window's location
// throws until it navigates back to our own origin, so most ticks just
// retry - this lets the result show up without the operator having to
// click "Netijäni barla" themselves once that happens.
function watchBankPage(popup: Window, successUrl: string) {
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)) {
win.close();
stopWatchingBankPage();
handleCheckStatus();
}
}, 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) return;
if (isPaying || isChecking) return;
if (!next) {
setPaymentInit(null);
setPaymentResult(null);
stopWatchingBankPage();
}
onOpenChange(next);
}
function handleSubmit(payload: PayPayload) {
pay({ id: stableId, payload }, { onSuccess: () => onOpenChange(false) });
pay(
{ id: stableId, payload },
{
onSuccess: (data) => {
setPaymentInit(data);
setPaymentResult(null);
if (data.formUrl) {
const popup = openBankPage(data.formUrl);
if (popup && data.successUrl) watchBankPage(popup, data.successUrl);
}
},
},
);
}
function handleCheckStatus() {
checkStatus(stableId, {
onSuccess: (result) => {
setPaymentResult(result);
stopWatchingBankPage();
},
});
}
return (
@@ -277,10 +372,64 @@ export function PayDialog({ id, open, onOpenChange }: PayDialogProps) {
<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>
<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>
<PayForm id={stableId} isPaying={isPaying} onSubmit={handleSubmit} onCancel={() => handleOpenChange(false)} />
{paymentInit ? (
<div className="space-y-4">
<Alert>
<ExternalLink className="h-4 w-4" />
<AlertDescription>
{t(
"intlPayment.pay.bankPageOpened",
"Bankyň töleg sahypasy açyldy. Kart maglumatlary girizilip gutarandan soň netijäni şu ýerden barlaň.",
)}
</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.paid
? t("intlPayment.paySuccess", "Töleg üstünlikli amala aşyryldy")
: t("intlPayment.payFailed", "Töleg amala aşyrylmady")}
<span className="ml-2 text-xs text-muted-foreground">({paymentResult.gatewayStatus})</span>
</AlertDescription>
</Alert>
) : null}
<DialogFooter className="gap-2">
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={isChecking}>
{t("common.close", "Ýap")}
</Button>
{paymentInit.formUrl ? (
<Button
type="button"
variant="outline"
onClick={() => {
const popup = openBankPage(paymentInit.formUrl!);
if (popup && paymentInit.successUrl) watchBankPage(popup, paymentInit.successUrl);
}}
disabled={isChecking}
>
<ExternalLink className="mr-2 h-4 w-4" />
{t("intlPayment.pay.openBankPage", "Bank sahypasyny aç")}
</Button>
) : null}
<Button type="button" onClick={handleCheckStatus} disabled={isChecking}>
{isChecking ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <RefreshCw className="mr-2 h-4 w-4" />}
{t("intlPayment.pay.checkStatus", "Netijäni barla")}
</Button>
</DialogFooter>
</div>
) : (
<PayForm id={stableId} isPaying={isPaying} onSubmit={handleSubmit} onCancel={() => handleOpenChange(false)} />
)}
</DialogContent>
</Dialog>
);