updated payment

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

View File

@@ -6,16 +6,22 @@ import { postFile, buildFileUrl } from "@/features/shared/api/sharedApi";
// ─── Shared types ─────────────────────────────────────────────────────────────
export type IntlPaymentStatus = "pending" | "approved" | "rejected";
export type IntlPaymentStatus = "pending" | "approved" | "rejected" | "completed";
export type CurrencyType = "visa" | "mastercard";
// ─── Quote / Pay types ────────────────────────────────────────────────────────
// gbusFeeTmt/tvebFeeUsd/tvebFeeTmt are optional to match the backend's
// PaymentQuoteDTO: sber orders omit gbusFeeTmt and populate the tveb fee
// pair instead, visa/master orders do the opposite.
export interface QuoteResponse {
type: string;
exchangeRateUsd: number;
exchangeRateRub?: number;
bankFeeTmt: number;
gbusFeeTmt: number;
gbusFeeTmt?: number;
tvebFeeUsd?: number;
tvebFeeTmt?: number;
maxAmountTmt: number;
payableToday: boolean;
}
@@ -27,10 +33,33 @@ export interface PayPayload {
export interface PayResponse {
paymentId?: number;
orderId?: number;
formUrl?: string;
successUrl?: string;
[key: string]: unknown;
}
export interface PaymentResultResponse {
id: number;
orderId: number;
type: string;
paid: boolean;
amountUsd: number;
exchangeRateUsd: number;
exchangeRateRub?: number;
amountTmt: number;
bankFeeTmt: number;
gbusFeeTmt?: number;
tvebFeeUsd?: number;
tvebFeeTmt?: number;
totalAmountTmt: number;
paymentPeriod: string;
gatewayStatus: "pending" | "success" | "failed" | string;
gatewayReference?: string;
createdAt: string;
updatedAt: string;
}
/** Kabul ediji + Upgradyý resminamalar (15 sany) — hem UI hem Payload ortak */
export interface IntlPaymentDocs {
doc_sberbank_account: string | null;
@@ -91,7 +120,6 @@ export interface IntlPaymentListParams {
per_page?: number;
search?: string;
status?: IntlPaymentStatus | "";
month?: string;
province?: string;
region?: string;
branch?: string;
@@ -220,6 +248,7 @@ const DOC_FILE_TO_KEY: Record<string, string> = {
upd_doc_visa: "kinship_documents",
upd_doc_acceptance_letter: "first_passport_series_info",
upd_doc_passport_biometric: "police_passport_series_info",
upd_doc_passport_old: "old_passport_series_info",
};
function mapDocs(d: Record<string, string[]>): IntlPaymentDocs {
@@ -238,7 +267,7 @@ function mapDocs(d: Record<string, string[]>): IntlPaymentDocs {
upd_doc_visa: firstFileUrl(d.kinship_documents),
upd_doc_acceptance_letter: firstFileUrl(d.first_passport_series_info),
upd_doc_passport_biometric: firstFileUrl(d.police_passport_series_info),
upd_doc_passport_old: null,
upd_doc_passport_old: firstFileUrl(d.old_passport_series_info),
};
}
@@ -344,7 +373,6 @@ export const intlPaymentApi = {
branch_id: params.branch_id || params.branch || undefined,
user_id: params.user_id || undefined,
region: params.region || params.province || undefined,
month: params.month || undefined,
},
});
@@ -390,7 +418,11 @@ export const intlPaymentApi = {
async pay(id: string, payload: PayPayload): Promise<PayResponse> {
const res = await apiClient.post<any>(`/visa-master-payment-orders/${id}/pay`, payload);
const data = res.data?.data ?? res.data;
return data as PayResponse;
return res.data as PayResponse;
},
async status(id: string): Promise<PaymentResultResponse> {
const { data } = await apiClient.get<PaymentResultResponse>(`/visa-master-payment-orders/${id}/status`);
return data;
},
};

View File

@@ -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>
);

View File

@@ -88,14 +88,25 @@ export function usePayIntlPayment() {
const { t } = useTranslation();
return useMutation({
mutationFn: ({ id, payload }: { id: string; payload: PayPayload }) => intlPaymentApi.pay(id, payload),
onSuccess: () => {
qc.invalidateQueries({ queryKey: INTL_PAYMENT_KEYS.lists() });
toast.success(t("intlPayment.payStarted", "Bank töleg sahypasy açyldy"));
},
});
}
export function useCheckIntlPaymentStatus() {
const qc = useQueryClient();
const { t } = useTranslation();
return useMutation({
mutationFn: (id: string) => intlPaymentApi.status(id),
onSuccess: (data) => {
qc.invalidateQueries({ queryKey: INTL_PAYMENT_KEYS.lists() });
toast.success(t("intlPayment.paySuccess", "Töleg üstünlikli amala aşyryldy"));
if (data?.formUrl) {
const newWindow = window.open(data.formUrl, "_blank");
if (!newWindow || newWindow.closed || typeof newWindow.closed === "undefined") {
window.location.href = data.formUrl;
}
qc.invalidateQueries({ queryKey: INTL_PAYMENT_KEYS.detail(String(data.orderId)) });
if (data.paid) {
toast.success(t("intlPayment.paySuccess", "Töleg üstünlikli amala aşyryldy"));
} else {
toast.error(t("intlPayment.payFailed", "Töleg amala aşyrylmady"));
}
},
});

View File

@@ -38,7 +38,6 @@ export default function IntlPaymentsPage() {
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(25);
const [search, setSearch] = useState("");
const [month] = useState("");
const [statusFilter, setStatusFilter] = useState<IntlPaymentStatus | "">("");
const [regionFilter, setRegionFilter] = useState("");
const [branchFilter, setBranchFilter] = useState("");
@@ -75,7 +74,6 @@ export default function IntlPaymentsPage() {
per_page: perPage,
search,
status: statusFilter,
month,
region: regionFilter || undefined,
branch_id: branchFilter || undefined,
user_id: userFilter || undefined,