changed pay dialog
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user