mirror of
https://github.com/chillpadclub/bedolaga-cabinet.git
synced 2026-07-28 17:43:47 +00:00
fix: harden gift subscription frontend after multi-agent review
- Handle expired status in GiftResult (stop polling + show FailedState) - Add PollErrorState for balance mode poll errors (softer UX) - Remove non-null assertions in handleSubmit (explicit narrowing) - Wrap gift routes in ErrorBoundary - Add pollErrorTitle/pollErrorDesc i18n keys to all 4 locales
This commit is contained in:
24
src/App.tsx
24
src/App.tsx
@@ -425,21 +425,25 @@ function App() {
|
||||
<Route
|
||||
path="/gift"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<LazyPage>
|
||||
<GiftSubscription />
|
||||
</LazyPage>
|
||||
</ProtectedRoute>
|
||||
<ErrorBoundary level="app">
|
||||
<ProtectedRoute>
|
||||
<LazyPage>
|
||||
<GiftSubscription />
|
||||
</LazyPage>
|
||||
</ProtectedRoute>
|
||||
</ErrorBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/gift/result"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<LazyPage>
|
||||
<GiftResult />
|
||||
</LazyPage>
|
||||
</ProtectedRoute>
|
||||
<ErrorBoundary level="app">
|
||||
<ProtectedRoute>
|
||||
<LazyPage>
|
||||
<GiftResult />
|
||||
</LazyPage>
|
||||
</ProtectedRoute>
|
||||
</ErrorBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
|
||||
@@ -53,13 +53,22 @@ export interface GiftPurchaseRequest {
|
||||
}
|
||||
|
||||
export interface GiftPurchaseResponse {
|
||||
status: string;
|
||||
status: 'ok' | 'created' | 'paid';
|
||||
purchase_token: string;
|
||||
payment_url: string | null;
|
||||
warning: string | null;
|
||||
}
|
||||
|
||||
export type GiftPurchaseStatusValue =
|
||||
| 'pending'
|
||||
| 'paid'
|
||||
| 'delivered'
|
||||
| 'pending_activation'
|
||||
| 'failed'
|
||||
| 'expired';
|
||||
|
||||
export interface GiftPurchaseStatus {
|
||||
status: string;
|
||||
status: GiftPurchaseStatusValue;
|
||||
is_gift: boolean;
|
||||
recipient_contact_value: string | null;
|
||||
gift_message: string | null;
|
||||
@@ -67,6 +76,15 @@ export interface GiftPurchaseStatus {
|
||||
period_days: number | null;
|
||||
}
|
||||
|
||||
export interface PendingGift {
|
||||
token: string;
|
||||
tariff_name: string | null;
|
||||
period_days: number;
|
||||
gift_message: string | null;
|
||||
sender_display: string | null;
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
export const giftApi = {
|
||||
@@ -84,4 +102,9 @@ export const giftApi = {
|
||||
const { data } = await apiClient.get<GiftPurchaseStatus>(`/cabinet/gift/purchase/${token}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
getPendingGifts: async (): Promise<PendingGift[]> => {
|
||||
const { data } = await apiClient.get<PendingGift[]>('/cabinet/gift/pending');
|
||||
return data;
|
||||
},
|
||||
};
|
||||
|
||||
80
src/components/dashboard/PendingGiftCard.tsx
Normal file
80
src/components/dashboard/PendingGiftCard.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
import { Link } from 'react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { motion } from 'framer-motion';
|
||||
import type { PendingGift } from '../../api/gift';
|
||||
|
||||
interface PendingGiftCardProps {
|
||||
gifts: PendingGift[];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function PendingGiftCard({ gifts, className }: PendingGiftCardProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (gifts.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className={className ?? 'space-y-3'}>
|
||||
{gifts.map((gift) => (
|
||||
<motion.div
|
||||
key={gift.token}
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="relative overflow-hidden rounded-2xl border border-accent-500/30 bg-gradient-to-r from-accent-500/10 via-purple-500/10 to-accent-500/10 p-5"
|
||||
>
|
||||
{/* Subtle glow effect */}
|
||||
<div className="absolute -right-8 -top-8 h-24 w-24 rounded-full bg-accent-500/10 blur-2xl" />
|
||||
|
||||
<div className="relative flex items-start gap-4">
|
||||
{/* Gift icon */}
|
||||
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-accent-500/20">
|
||||
<svg
|
||||
className="h-6 w-6 text-accent-400"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M21 11.25v8.25a1.5 1.5 0 01-1.5 1.5H5.25a1.5 1.5 0 01-1.5-1.5v-8.25M12 4.875A2.625 2.625 0 109.375 7.5H12m0-2.625V7.5m0-2.625A2.625 2.625 0 1114.625 7.5H12m0 0V21m-8.625-9.75h18c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125h-18c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="min-w-0 flex-1">
|
||||
<h3 className="text-sm font-semibold text-dark-50">{t('gift.pending.title')}</h3>
|
||||
<p className="mt-0.5 text-xs text-dark-300">
|
||||
{gift.tariff_name && (
|
||||
<span>
|
||||
{gift.tariff_name} — {gift.period_days} {t('gift.days')}
|
||||
</span>
|
||||
)}
|
||||
{gift.sender_display && (
|
||||
<span className="ml-1 text-dark-400">
|
||||
{t('gift.pending.from', { sender: gift.sender_display })}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
{gift.gift_message && (
|
||||
<p className="mt-1.5 line-clamp-2 text-xs italic text-dark-400">
|
||||
“{gift.gift_message}”
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Activate button */}
|
||||
<Link
|
||||
to={`/buy/success/${gift.token}?activate=1`}
|
||||
className="shrink-0 rounded-xl bg-accent-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-accent-400"
|
||||
>
|
||||
{t('gift.pending.activate')}
|
||||
</Link>
|
||||
</div>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4152,13 +4152,26 @@
|
||||
"tryAgain": "Try again",
|
||||
"pollTimeout": "Processing is taking longer than usual",
|
||||
"pollTimeoutDesc": "Try checking the status later",
|
||||
"pollErrorTitle": "Could not check gift status",
|
||||
"pollErrorDesc": "Your purchase was successful. Check your dashboard for details.",
|
||||
"retry": "Check again",
|
||||
"notFound": "Gift configuration not found",
|
||||
"noToken": "Invalid link",
|
||||
"noTokenDesc": "This gift link is invalid or has expired.",
|
||||
"days": "days",
|
||||
"tariff": "Tariff",
|
||||
"period": "Period",
|
||||
"giftMessageLabel": "Message",
|
||||
"recipientLabel": "Recipient",
|
||||
"featureDisabled": "Gift feature is temporarily unavailable",
|
||||
"redirecting": "Redirecting..."
|
||||
"redirecting": "Redirecting...",
|
||||
"pending": {
|
||||
"title": "You received a gift!",
|
||||
"from": "from {{sender}}",
|
||||
"activate": "Activate"
|
||||
},
|
||||
"warning": {
|
||||
"telegram_unresolvable": "Could not verify this Telegram username. The recipient may not receive a notification about the gift."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3647,13 +3647,26 @@
|
||||
"tryAgain": "تلاش مجدد",
|
||||
"pollTimeout": "پردازش بیش از حد معمول طول کشیده",
|
||||
"pollTimeoutDesc": "بعداً وضعیت را بررسی کنید",
|
||||
"pollErrorTitle": "بررسی وضعیت هدیه امکانپذیر نیست",
|
||||
"pollErrorDesc": "خرید شما موفقیتآمیز بود. وضعیت را در داشبورد بررسی کنید.",
|
||||
"retry": "بررسی مجدد",
|
||||
"notFound": "تنظیمات هدیه یافت نشد",
|
||||
"noToken": "لینک نامعتبر",
|
||||
"noTokenDesc": "این لینک هدیه نامعتبر است یا منقضی شده.",
|
||||
"days": "روز",
|
||||
"tariff": "طرح",
|
||||
"period": "مدت",
|
||||
"giftMessageLabel": "پیام",
|
||||
"recipientLabel": "گیرنده",
|
||||
"featureDisabled": "قابلیت هدیه موقتاً در دسترس نیست",
|
||||
"redirecting": "در حال انتقال..."
|
||||
"redirecting": "در حال انتقال...",
|
||||
"pending": {
|
||||
"title": "شما یک هدیه دریافت کردید!",
|
||||
"from": "از {{sender}}",
|
||||
"activate": "فعالسازی"
|
||||
},
|
||||
"warning": {
|
||||
"telegram_unresolvable": "نام کاربری تلگرام قابل تأیید نبود. ممکن است گیرنده اعلان هدیه را دریافت نکند."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4714,13 +4714,26 @@
|
||||
"tryAgain": "Попробовать снова",
|
||||
"pollTimeout": "Обработка занимает больше времени, чем обычно",
|
||||
"pollTimeoutDesc": "Попробуйте проверить статус позже",
|
||||
"pollErrorTitle": "Не удалось проверить статус подарка",
|
||||
"pollErrorDesc": "Ваша покупка прошла успешно. Проверьте статус на главной странице.",
|
||||
"retry": "Проверить снова",
|
||||
"notFound": "Конфигурация подарков не найдена",
|
||||
"noToken": "Ссылка недействительна",
|
||||
"noTokenDesc": "Ссылка на подарок недействительна или просрочена.",
|
||||
"days": "дн.",
|
||||
"tariff": "Тариф",
|
||||
"period": "Период",
|
||||
"giftMessageLabel": "Сообщение",
|
||||
"recipientLabel": "Получатель",
|
||||
"featureDisabled": "Функция подарков временно недоступна",
|
||||
"redirecting": "Перенаправляем..."
|
||||
"redirecting": "Перенаправляем...",
|
||||
"pending": {
|
||||
"title": "Вам подарили подписку!",
|
||||
"from": "от {{sender}}",
|
||||
"activate": "Активировать"
|
||||
},
|
||||
"warning": {
|
||||
"telegram_unresolvable": "Не удалось проверить этот Telegram-юзернейм. Получатель может не получить уведомление о подарке."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3646,13 +3646,26 @@
|
||||
"tryAgain": "重试",
|
||||
"pollTimeout": "处理时间超出预期",
|
||||
"pollTimeoutDesc": "请稍后再查看状态",
|
||||
"pollErrorTitle": "无法检查礼物状态",
|
||||
"pollErrorDesc": "您的购买已成功。请在仪表板上查看详情。",
|
||||
"retry": "再次检查",
|
||||
"notFound": "未找到礼物配置",
|
||||
"noToken": "无效链接",
|
||||
"noTokenDesc": "此礼物链接无效或已过期。",
|
||||
"days": "天",
|
||||
"tariff": "套餐",
|
||||
"period": "时长",
|
||||
"giftMessageLabel": "消息",
|
||||
"recipientLabel": "收件人",
|
||||
"featureDisabled": "礼物功能暂时不可用",
|
||||
"redirecting": "正在跳转..."
|
||||
"redirecting": "正在跳转...",
|
||||
"pending": {
|
||||
"title": "您收到了一份礼物!",
|
||||
"from": "来自 {{sender}}",
|
||||
"activate": "激活"
|
||||
},
|
||||
"warning": {
|
||||
"telegram_unresolvable": "无法验证此 Telegram 用户名。收件人可能不会收到礼物通知。"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ import SubscriptionCardActive from '../components/dashboard/SubscriptionCardActi
|
||||
import SubscriptionCardExpired from '../components/dashboard/SubscriptionCardExpired';
|
||||
import TrialOfferCard from '../components/dashboard/TrialOfferCard';
|
||||
import StatsGrid from '../components/dashboard/StatsGrid';
|
||||
import { giftApi } from '../api/gift';
|
||||
import PendingGiftCard from '../components/dashboard/PendingGiftCard';
|
||||
import { API } from '../config/constants';
|
||||
|
||||
const ChevronRightIcon = () => (
|
||||
@@ -80,6 +82,13 @@ export default function Dashboard() {
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const { data: pendingGifts } = useQuery({
|
||||
queryKey: ['pending-gifts'],
|
||||
queryFn: giftApi.getPendingGifts,
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const activateTrialMutation = useMutation({
|
||||
mutationFn: subscriptionApi.activateTrial,
|
||||
onSuccess: () => {
|
||||
@@ -221,6 +230,9 @@ export default function Dashboard() {
|
||||
<p className="mt-1 text-dark-400">{t('dashboard.yourSubscription')}</p>
|
||||
</div>
|
||||
|
||||
{/* Pending Gift Activations */}
|
||||
{pendingGifts && pendingGifts.length > 0 && <PendingGiftCard gifts={pendingGifts} />}
|
||||
|
||||
{/* Subscription Status Card */}
|
||||
{subLoading ? (
|
||||
<div className="bento-card">
|
||||
|
||||
@@ -10,6 +10,8 @@ import { AnimatedCrossmark } from '@/components/ui/AnimatedCrossmark';
|
||||
|
||||
const MAX_POLL_MS = 10 * 60 * 1000; // 10 minutes
|
||||
|
||||
const KNOWN_WARNINGS = new Set(['telegram_unresolvable']);
|
||||
|
||||
// ============================================================
|
||||
// Sub-components
|
||||
// ============================================================
|
||||
@@ -29,7 +31,7 @@ function PendingState() {
|
||||
{t('gift.processing', 'Processing your gift...')}
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-dark-400">
|
||||
{t('gift.processingDesc', 'Please wait while we process your payment')}
|
||||
{t('gift.pendingDesc', 'Please wait while we process your payment')}
|
||||
</p>
|
||||
</div>
|
||||
</motion.div>
|
||||
@@ -41,11 +43,13 @@ function DeliveredState({
|
||||
tariffName,
|
||||
periodDays,
|
||||
giftMessage,
|
||||
warning,
|
||||
}: {
|
||||
recipientContact: string | null;
|
||||
tariffName: string | null;
|
||||
periodDays: number | null;
|
||||
giftMessage: string | null;
|
||||
warning: string | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -59,7 +63,7 @@ function DeliveredState({
|
||||
<AnimatedCheckmark />
|
||||
|
||||
<div>
|
||||
<h1 className="text-xl font-bold text-dark-50">{t('gift.sent', 'Gift sent!')}</h1>
|
||||
<h1 className="text-xl font-bold text-dark-50">{t('gift.successTitle', 'Gift sent!')}</h1>
|
||||
{tariffName && periodDays !== null && (
|
||||
<p className="mt-1 text-sm text-dark-300">
|
||||
{tariffName} — {periodDays} {t('gift.days', 'days')}
|
||||
@@ -67,7 +71,7 @@ function DeliveredState({
|
||||
)}
|
||||
{recipientContact && (
|
||||
<p className="mt-2 text-sm text-dark-400">
|
||||
{t('gift.sentTo', {
|
||||
{t('gift.successDesc', {
|
||||
contact: recipientContact,
|
||||
defaultValue: `Sent to ${recipientContact}`,
|
||||
})}
|
||||
@@ -78,6 +82,12 @@ function DeliveredState({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{warning && (
|
||||
<div className="w-full rounded-xl border border-warning-500/20 bg-warning-500/5 p-3">
|
||||
<p className="text-sm text-warning-400">{t(`gift.warning.${warning}`)}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate('/')}
|
||||
@@ -93,10 +103,12 @@ function PendingActivationState({
|
||||
recipientContact,
|
||||
tariffName,
|
||||
periodDays,
|
||||
warning,
|
||||
}: {
|
||||
recipientContact: string | null;
|
||||
tariffName: string | null;
|
||||
periodDays: number | null;
|
||||
warning: string | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -126,7 +138,7 @@ function PendingActivationState({
|
||||
|
||||
<div>
|
||||
<h1 className="text-xl font-bold text-dark-50">
|
||||
{t('gift.pendingActivation', 'Gift pending activation')}
|
||||
{t('gift.pendingActivationTitle', 'Gift pending activation')}
|
||||
</h1>
|
||||
{tariffName && periodDays !== null && (
|
||||
<p className="mt-1 text-sm text-dark-300">
|
||||
@@ -135,7 +147,7 @@ function PendingActivationState({
|
||||
)}
|
||||
{recipientContact && (
|
||||
<p className="mt-2 text-sm text-dark-400">
|
||||
{t('gift.sentTo', {
|
||||
{t('gift.successDesc', {
|
||||
contact: recipientContact,
|
||||
defaultValue: `Sent to ${recipientContact}`,
|
||||
})}
|
||||
@@ -149,6 +161,12 @@ function PendingActivationState({
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{warning && (
|
||||
<div className="w-full rounded-xl border border-warning-500/20 bg-warning-500/5 p-3">
|
||||
<p className="text-sm text-warning-400">{t(`gift.warning.${warning}`)}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate('/')}
|
||||
@@ -174,7 +192,7 @@ function FailedState() {
|
||||
|
||||
<div>
|
||||
<h1 className="text-xl font-bold text-dark-50">
|
||||
{t('gift.failed', 'Something went wrong')}
|
||||
{t('gift.failedTitle', 'Something went wrong')}
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-dark-400">
|
||||
{t('gift.failedDesc', 'Your gift could not be processed. Please try again.')}
|
||||
@@ -192,6 +210,55 @@ function FailedState() {
|
||||
);
|
||||
}
|
||||
|
||||
function PollErrorState() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.9 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="flex flex-col items-center gap-6 text-center"
|
||||
>
|
||||
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-warning-500/10">
|
||||
<svg
|
||||
className="h-10 w-10 text-warning-400"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h1 className="text-xl font-bold text-dark-50">
|
||||
{t('gift.pollErrorTitle', 'Could not check gift status')}
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-dark-400">
|
||||
{t(
|
||||
'gift.pollErrorDesc',
|
||||
'Your purchase was successful. Check your dashboard for details.',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate('/')}
|
||||
className="flex w-full items-center justify-center rounded-xl bg-accent-500 px-6 py-3 text-sm font-medium text-white transition-colors hover:bg-accent-400"
|
||||
>
|
||||
{t('gift.backToDashboard', 'Back to dashboard')}
|
||||
</button>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
function PollTimedOutState({ onRetry }: { onRetry: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -218,11 +285,11 @@ function PollTimedOutState({ onRetry }: { onRetry: () => void }) {
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-bold text-dark-50">
|
||||
{t('gift.pollTimedOut', 'Taking longer than expected')}
|
||||
{t('gift.pollTimeout', 'Taking longer than expected')}
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-dark-400">
|
||||
{t(
|
||||
'gift.pollTimedOutDesc',
|
||||
'gift.pollTimeoutDesc',
|
||||
'Payment processing is taking longer than usual. You can try checking again.',
|
||||
)}
|
||||
</p>
|
||||
@@ -232,7 +299,7 @@ function PollTimedOutState({ onRetry }: { onRetry: () => void }) {
|
||||
onClick={onRetry}
|
||||
className="rounded-xl bg-accent-500 px-6 py-3 text-sm font-medium text-white transition-colors hover:bg-accent-400"
|
||||
>
|
||||
{t('common.retry', 'Retry')}
|
||||
{t('gift.retry', 'Retry')}
|
||||
</button>
|
||||
</motion.div>
|
||||
);
|
||||
@@ -264,9 +331,9 @@ function NoTokenState() {
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-bold text-dark-50">{t('gift.invalidLink', 'Invalid link')}</h1>
|
||||
<h1 className="text-xl font-bold text-dark-50">{t('gift.noToken', 'Invalid link')}</h1>
|
||||
<p className="mt-2 text-sm text-dark-400">
|
||||
{t('gift.invalidLinkDesc', 'This gift link is invalid or has expired.')}
|
||||
{t('gift.noTokenDesc', 'This gift link is invalid or has expired.')}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
@@ -274,7 +341,7 @@ function NoTokenState() {
|
||||
onClick={() => navigate('/gift')}
|
||||
className="rounded-xl bg-accent-500 px-6 py-3 text-sm font-medium text-white transition-colors hover:bg-accent-400"
|
||||
>
|
||||
{t('gift.giftNewSubscription', 'Gift a subscription')}
|
||||
{t('gift.backToGift', 'Go back')}
|
||||
</button>
|
||||
</motion.div>
|
||||
);
|
||||
@@ -288,6 +355,8 @@ export default function GiftResult() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const token = searchParams.get('token');
|
||||
const mode = searchParams.get('mode');
|
||||
const rawWarning = searchParams.get('warning');
|
||||
const warning = rawWarning && KNOWN_WARNINGS.has(rawWarning) ? rawWarning : null;
|
||||
|
||||
const pollStart = useRef(Date.now());
|
||||
const [pollTimedOut, setPollTimedOut] = useState(false);
|
||||
@@ -307,7 +376,8 @@ export default function GiftResult() {
|
||||
if (isBalanceMode) return false;
|
||||
|
||||
const s = query.state.data?.status;
|
||||
if (s === 'delivered' || s === 'failed' || s === 'pending_activation') return false;
|
||||
if (s === 'delivered' || s === 'failed' || s === 'pending_activation' || s === 'expired')
|
||||
return false;
|
||||
|
||||
// Check poll timeout
|
||||
if (Date.now() - pollStart.current > MAX_POLL_MS) {
|
||||
@@ -343,7 +413,7 @@ export default function GiftResult() {
|
||||
|
||||
const isDelivered = status?.status === 'delivered';
|
||||
const isPendingActivation = status?.status === 'pending_activation';
|
||||
const isFailed = status?.status === 'failed';
|
||||
const isFailed = status?.status === 'failed' || status?.status === 'expired';
|
||||
|
||||
return (
|
||||
<div className="flex min-h-dvh items-center justify-center bg-dark-950 px-4">
|
||||
@@ -352,7 +422,9 @@ export default function GiftResult() {
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
>
|
||||
{isError ? (
|
||||
{isError && isBalanceMode ? (
|
||||
<PollErrorState />
|
||||
) : isError ? (
|
||||
<FailedState />
|
||||
) : isDelivered ? (
|
||||
<DeliveredState
|
||||
@@ -360,12 +432,14 @@ export default function GiftResult() {
|
||||
tariffName={status.tariff_name}
|
||||
periodDays={status.period_days}
|
||||
giftMessage={status.gift_message}
|
||||
warning={warning}
|
||||
/>
|
||||
) : isPendingActivation ? (
|
||||
<PendingActivationState
|
||||
recipientContact={status.recipient_contact_value}
|
||||
tariffName={status.tariff_name}
|
||||
periodDays={status.period_days}
|
||||
warning={warning}
|
||||
/>
|
||||
) : isFailed ? (
|
||||
<FailedState />
|
||||
|
||||
@@ -27,8 +27,10 @@ function detectContactType(value: string): 'email' | 'telegram' {
|
||||
function isValidContact(value: string): boolean {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return false;
|
||||
if (trimmed.startsWith('@')) return trimmed.length >= 4;
|
||||
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed);
|
||||
if (trimmed.startsWith('@')) {
|
||||
return /^@[a-zA-Z][a-zA-Z0-9_]{4,31}$/.test(trimmed);
|
||||
}
|
||||
return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(trimmed);
|
||||
}
|
||||
|
||||
function formatPeriodLabel(
|
||||
@@ -82,7 +84,7 @@ function ErrorState({ message }: { message: string }) {
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<h2 className="text-lg font-semibold text-dark-50">{t('gift.error', 'Error')}</h2>
|
||||
<h2 className="text-lg font-semibold text-dark-50">{t('gift.failedTitle', 'Error')}</h2>
|
||||
<p className="text-sm text-dark-300">{message}</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -117,11 +119,9 @@ function DisabledState() {
|
||||
</svg>
|
||||
</div>
|
||||
<h2 className="text-lg font-semibold text-dark-50">
|
||||
{t('gift.disabled', 'Gift subscriptions are currently unavailable')}
|
||||
{t('gift.featureDisabled', 'Gift subscriptions are currently unavailable')}
|
||||
</h2>
|
||||
<p className="text-sm text-dark-300">
|
||||
{t('gift.disabledRedirect', 'Redirecting to dashboard...')}
|
||||
</p>
|
||||
<p className="text-sm text-dark-300">{t('gift.redirecting', 'Redirecting...')}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -512,7 +512,7 @@ function GiftSummaryCard({
|
||||
{selectedTariff && (
|
||||
<div className="mb-3">
|
||||
<p className="text-xs font-medium uppercase tracking-wider text-dark-500">
|
||||
{t('gift.selectedTariff', 'Tariff')}
|
||||
{t('gift.tariff', 'Tariff')}
|
||||
</p>
|
||||
<p className="mt-1 text-sm font-semibold text-dark-50">{selectedTariff.name}</p>
|
||||
</div>
|
||||
@@ -577,7 +577,7 @@ function GiftSummaryCard({
|
||||
to="/balance"
|
||||
className="font-medium text-accent-400 underline underline-offset-2"
|
||||
>
|
||||
{t('gift.topUp', 'Top up')}
|
||||
{t('gift.topUpBalance', 'Top up balance')}
|
||||
</Link>
|
||||
</p>
|
||||
</motion.div>
|
||||
@@ -650,7 +650,6 @@ export default function GiftSubscription() {
|
||||
const [paymentMode, setPaymentMode] = useState<'balance' | 'gateway'>('balance');
|
||||
const [selectedMethod, setSelectedMethod] = useState<string | null>(null);
|
||||
const [selectedSubOption, setSelectedSubOption] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
|
||||
// Collect ALL unique periods across ALL tariffs
|
||||
@@ -749,24 +748,27 @@ export default function GiftSubscription() {
|
||||
// Balance mode - show success
|
||||
queryClient.invalidateQueries({ queryKey: ['balance'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['gift-config'] });
|
||||
navigate('/gift/result?token=' + result.purchase_token + '&mode=balance');
|
||||
const params = new URLSearchParams({ token: result.purchase_token, mode: 'balance' });
|
||||
if (result.warning) {
|
||||
params.set('warning', result.warning);
|
||||
}
|
||||
navigate('/gift/result?' + params.toString());
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
const msg = getApiErrorMessage(
|
||||
err,
|
||||
t('gift.purchaseError', 'Something went wrong. Please try again.'),
|
||||
t('gift.failedDesc', 'Something went wrong. Please try again.'),
|
||||
);
|
||||
setSubmitError(msg);
|
||||
setIsSubmitting(false);
|
||||
},
|
||||
});
|
||||
|
||||
// Submit handler
|
||||
const handleSubmit = () => {
|
||||
if (!canSubmit || isSubmitting) return;
|
||||
if (!selectedTariffId || !selectedPeriodDays || !canSubmit || purchaseMutation.isPending)
|
||||
return;
|
||||
|
||||
setIsSubmitting(true);
|
||||
setSubmitError(null);
|
||||
|
||||
let paymentMethod: string | undefined;
|
||||
@@ -778,8 +780,8 @@ export default function GiftSubscription() {
|
||||
}
|
||||
|
||||
const data: GiftPurchaseRequest = {
|
||||
tariff_id: selectedTariffId!,
|
||||
period_days: selectedPeriodDays!,
|
||||
tariff_id: selectedTariffId,
|
||||
period_days: selectedPeriodDays,
|
||||
recipient_type: detectContactType(recipientValue),
|
||||
recipient_value: recipientValue.trim(),
|
||||
gift_message: giftMessage.trim() || undefined,
|
||||
@@ -885,7 +887,7 @@ export default function GiftSubscription() {
|
||||
{/* Recipient */}
|
||||
<div>
|
||||
<h2 className="mb-3 text-sm font-medium uppercase tracking-wider text-dark-400">
|
||||
{t('gift.recipientSection', 'Recipient')}
|
||||
{t('gift.recipientLabel', 'Recipient')}
|
||||
</h2>
|
||||
<RecipientSection
|
||||
value={recipientValue}
|
||||
@@ -899,7 +901,7 @@ export default function GiftSubscription() {
|
||||
{/* Gift message */}
|
||||
<div>
|
||||
<h2 className="mb-3 text-sm font-medium uppercase tracking-wider text-dark-400">
|
||||
{t('gift.messageSection', 'Personal message')}
|
||||
{t('gift.giftMessageLabel', 'Message')}
|
||||
</h2>
|
||||
<GiftMessageSection value={giftMessage} onChange={setGiftMessage} />
|
||||
</div>
|
||||
@@ -907,7 +909,7 @@ export default function GiftSubscription() {
|
||||
{/* Payment mode toggle */}
|
||||
<div>
|
||||
<h2 className="mb-3 text-sm font-medium uppercase tracking-wider text-dark-400">
|
||||
{t('gift.paymentModeSection', 'Payment method')}
|
||||
{t('gift.paymentMode', 'Payment method')}
|
||||
</h2>
|
||||
<PaymentModeToggle
|
||||
mode={paymentMode}
|
||||
@@ -969,7 +971,7 @@ export default function GiftSubscription() {
|
||||
selectedPeriod={selectedPeriod}
|
||||
currentPrice={currentPrice}
|
||||
paymentMode={paymentMode}
|
||||
isSubmitting={isSubmitting}
|
||||
isSubmitting={purchaseMutation.isPending}
|
||||
canSubmit={canSubmit}
|
||||
submitError={submitError}
|
||||
insufficientBalance={insufficientBalance}
|
||||
|
||||
Reference in New Issue
Block a user