diff --git a/src/features/visaMasterPayments/api/visaMasterPaymentsApi.ts b/src/features/visaMasterPayments/api/visaMasterPaymentsApi.ts index b6cea99..196a077 100644 --- a/src/features/visaMasterPayments/api/visaMasterPaymentsApi.ts +++ b/src/features/visaMasterPayments/api/visaMasterPaymentsApi.ts @@ -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 = { 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): IntlPaymentDocs { @@ -238,7 +267,7 @@ function mapDocs(d: Record): 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 { const res = await apiClient.post(`/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 { + const { data } = await apiClient.get(`/visa-master-payment-orders/${id}/status`); + return data; }, }; diff --git a/src/features/visaMasterPayments/components/PayDialog.tsx b/src/features/visaMasterPayments/components/PayDialog.tsx index 45e3695..e10e4a6 100644 --- a/src/features/visaMasterPayments/components/PayDialog.tsx +++ b/src/features/visaMasterPayments/components/PayDialog.tsx @@ -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["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(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) { 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) {
{t("intlPayment.pay.bankFee", "BANKYŇ TUTUMY")}
{quote.bankFeeTmt} TMT
-
-
{t("intlPayment.pay.gbusFee", "GBÜS TUTUMY")}
-
{quote.gbusFeeTmt} TMT
-
+ {quote.gbusFeeTmt != null && ( +
+
{t("intlPayment.pay.gbusFee", "GBÜS TUTUMY")}
+
{quote.gbusFeeTmt} TMT
+
+ )} + {quote.tvebFeeTmt != null && ( +
+
{t("intlPayment.pay.tvebFee", "TVEB TUTUMY")}
+
{quote.tvebFeeTmt} TMT
+
+ )} ) : null} {/* Töleg aý */} - + {/* Töleg möçberi */} @@ -218,14 +241,6 @@ function PayForm({ id, isPaying, onSubmit, onCancel }: PayFormProps) { - {/* Wrong month warning */} - {!isMonthCorrect && ( - - - {t("intlPayment.pay.wrongMonth", "Dogry töleg aýyny saýlamagyňyzy haýyş edýäris!")} - - )} - + {paymentInit.formUrl ? ( + + ) : null} + + + + ) : ( + handleOpenChange(false)} /> + )} ); diff --git a/src/features/visaMasterPayments/hooks/useVisaMasterPayments.ts b/src/features/visaMasterPayments/hooks/useVisaMasterPayments.ts index 3cbf625..31b6b21 100644 --- a/src/features/visaMasterPayments/hooks/useVisaMasterPayments.ts +++ b/src/features/visaMasterPayments/hooks/useVisaMasterPayments.ts @@ -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")); } }, }); diff --git a/src/pages/internationalPayments/visaMasterPayments/index.tsx b/src/pages/internationalPayments/visaMasterPayments/index.tsx index a51e2fb..3d80f65 100644 --- a/src/pages/internationalPayments/visaMasterPayments/index.tsx +++ b/src/pages/internationalPayments/visaMasterPayments/index.tsx @@ -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(""); 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,