Merge pull request #339 from BEDOLAGA-DEV/dev

Dev
This commit is contained in:
Egor
2026-03-22 07:35:31 +03:00
committed by GitHub
14 changed files with 527 additions and 110 deletions

View File

@@ -48,6 +48,12 @@ export interface BroadcastButtonsResponse {
buttons: BroadcastButton[]; buttons: BroadcastButton[];
} }
export interface CustomBroadcastButton {
label: string;
action_type: 'callback' | 'url';
action_value: string;
}
export interface BroadcastMedia { export interface BroadcastMedia {
type: 'photo' | 'video' | 'document'; type: 'photo' | 'video' | 'document';
file_id: string; file_id: string;
@@ -73,6 +79,7 @@ export interface CombinedBroadcastCreateRequest {
// Telegram fields // Telegram fields
message_text?: string; message_text?: string;
selected_buttons?: string[]; selected_buttons?: string[];
custom_buttons?: CustomBroadcastButton[];
media?: BroadcastMedia; media?: BroadcastMedia;
// Email fields // Email fields
email_subject?: string; email_subject?: string;

View File

@@ -290,7 +290,7 @@ export const authApi = {
return response.data; return response.data;
}, },
pollDeepLinkToken: async (token: string): Promise<AuthResponse> => { pollDeepLinkToken: async (token: string, campaignSlug?: string | null): Promise<AuthResponse> => {
// validateStatus: only treat 200 as success. // validateStatus: only treat 200 as success.
// Server returns 202 for "pending" and 410 for "expired" — // Server returns 202 for "pending" and 410 for "expired" —
// these must reject so the polling catch-block can handle them. // these must reject so the polling catch-block can handle them.
@@ -299,7 +299,7 @@ export const authApi = {
// which triggers checkAdminStatus() → 401 → safeRedirectToLogin() → infinite reload. // which triggers checkAdminStatus() → 401 → safeRedirectToLogin() → infinite reload.
const response = await apiClient.post<AuthResponse>( const response = await apiClient.post<AuthResponse>(
'/cabinet/auth/deeplink/poll', '/cabinet/auth/deeplink/poll',
{ token }, { token, campaign_slug: campaignSlug || undefined },
{ validateStatus: (status) => status === 200 }, { validateStatus: (status) => status === 200 },
); );
return response.data; return response.data;

View File

@@ -2,10 +2,13 @@ import { useEffect, useRef, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { isAxiosError } from 'axios'; import { isAxiosError } from 'axios';
import { QRCodeSVG } from 'qrcode.react';
import { brandingApi, type TelegramWidgetConfig } from '../api/branding'; import { brandingApi, type TelegramWidgetConfig } from '../api/branding';
import { authApi } from '../api/auth'; import { authApi } from '../api/auth';
import { useAuthStore } from '../store/auth'; import { useAuthStore } from '../store/auth';
import { useNavigate } from 'react-router'; import { useNavigate } from 'react-router';
import { consumeCampaignSlug } from '../utils/campaign';
import { copyToClipboard } from '../utils/clipboard';
interface TelegramLoginButtonProps { interface TelegramLoginButtonProps {
referralCode?: string; referralCode?: string;
@@ -29,11 +32,18 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
const [deepLinkBotUsername, setDeepLinkBotUsername] = useState<string>(''); const [deepLinkBotUsername, setDeepLinkBotUsername] = useState<string>('');
const [deepLinkPolling, setDeepLinkPolling] = useState(false); const [deepLinkPolling, setDeepLinkPolling] = useState(false);
const [deepLinkError, setDeepLinkError] = useState(''); const [deepLinkError, setDeepLinkError] = useState('');
const [copied, setCopied] = useState(false);
const pollTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null); const pollTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);
const expireTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null); const expireTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);
const copiedTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);
const pollInFlightRef = useRef(false);
const loginWithDeepLink = useAuthStore((s) => s.loginWithDeepLink); const loginWithDeepLink = useAuthStore((s) => s.loginWithDeepLink);
// Capture campaign slug once on mount (before any retry clears it)
const capturedCampaignRef = useRef<string | null>(null);
const codesConsumedRef = useRef(false);
const { data: widgetConfig } = useQuery<TelegramWidgetConfig>({ const { data: widgetConfig } = useQuery<TelegramWidgetConfig>({
queryKey: ['telegram-widget-config'], queryKey: ['telegram-widget-config'],
queryFn: brandingApi.getTelegramWidgetConfig, queryFn: brandingApi.getTelegramWidgetConfig,
@@ -56,15 +66,12 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
}; };
}, []); }, []);
// Cleanup polling and expire timeout on unmount // Cleanup all timeouts on unmount
useEffect(() => { useEffect(() => {
return () => { return () => {
if (pollTimeoutRef.current) { if (pollTimeoutRef.current) clearTimeout(pollTimeoutRef.current);
clearTimeout(pollTimeoutRef.current); if (expireTimeoutRef.current) clearTimeout(expireTimeoutRef.current);
} if (copiedTimeoutRef.current) clearTimeout(copiedTimeoutRef.current);
if (expireTimeoutRef.current) {
clearTimeout(expireTimeoutRef.current);
}
}; };
}, []); }, []);
@@ -228,7 +235,7 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
const startDeepLinkAuth = useCallback(async () => { const startDeepLinkAuth = useCallback(async () => {
setDeepLinkError(''); setDeepLinkError('');
// Clear any previous timers // Clear any previous timers and in-flight guard
if (pollTimeoutRef.current) { if (pollTimeoutRef.current) {
clearTimeout(pollTimeoutRef.current); clearTimeout(pollTimeoutRef.current);
pollTimeoutRef.current = null; pollTimeoutRef.current = null;
@@ -237,8 +244,20 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
clearTimeout(expireTimeoutRef.current); clearTimeout(expireTimeoutRef.current);
expireTimeoutRef.current = null; expireTimeoutRef.current = null;
} }
pollInFlightRef.current = false;
try { try {
// Consume campaign slug ONCE (first call only).
// Clears localStorage on first call, so subsequent retries reuse the ref.
// Note: referral code is NOT consumed here — deep link auth is for existing
// bot users where referrals don't apply. Leaving it in localStorage allows
// other auth methods (OIDC, widget) to pick it up if the user switches paths.
if (!codesConsumedRef.current) {
capturedCampaignRef.current = consumeCampaignSlug();
codesConsumedRef.current = true;
}
const capturedCampaign = capturedCampaignRef.current;
const response = await authApi.requestDeepLinkToken(); const response = await authApi.requestDeepLinkToken();
const { token, bot_username, expires_in } = response; const { token, bot_username, expires_in } = response;
setDeepLinkToken(token); setDeepLinkToken(token);
@@ -247,9 +266,11 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
// Recursive setTimeout prevents overlapping async calls // Recursive setTimeout prevents overlapping async calls
const poll = async () => { const poll = async () => {
if (!mountedRef.current) return; if (!mountedRef.current || pollInFlightRef.current) return;
pollInFlightRef.current = true;
try { try {
await loginWithDeepLink(token); // Deep link auth is for existing bot users — only campaign_slug applies
await loginWithDeepLink(token, capturedCampaign);
// Success — auth store is updated, navigate // Success — auth store is updated, navigate
if (expireTimeoutRef.current) { if (expireTimeoutRef.current) {
clearTimeout(expireTimeoutRef.current); clearTimeout(expireTimeoutRef.current);
@@ -268,16 +289,26 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
return; return;
} }
if (err.response?.status === 410) { if (err.response?.status === 410) {
// Token expired // Token expired — clear expire timer to prevent stale timer killing future sessions
if (expireTimeoutRef.current) {
clearTimeout(expireTimeoutRef.current);
expireTimeoutRef.current = null;
}
setDeepLinkPolling(false); setDeepLinkPolling(false);
setDeepLinkToken(null); setDeepLinkToken(null);
setDeepLinkError(t('auth.deepLinkExpired')); setDeepLinkError(t('auth.deepLinkExpired'));
return; return;
} }
} }
// Other error — stop polling // Other error — stop polling and clear expire timer
if (expireTimeoutRef.current) {
clearTimeout(expireTimeoutRef.current);
expireTimeoutRef.current = null;
}
setDeepLinkPolling(false); setDeepLinkPolling(false);
setDeepLinkError(t('common.error')); setDeepLinkError(t('common.error'));
} finally {
pollInFlightRef.current = false;
} }
}; };
@@ -318,6 +349,77 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
} }
}, [scriptFailed, deepLinkToken, deepLinkPolling, startDeepLinkAuth]); }, [scriptFailed, deepLinkToken, deepLinkPolling, startDeepLinkAuth]);
// Resume polling immediately when user returns to the page (e.g. after confirming in Telegram)
// Browsers throttle setTimeout in background tabs, so polling may have stalled.
useEffect(() => {
if (!deepLinkPolling || !deepLinkToken) return;
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible' && mountedRef.current) {
// Clear any pending throttled timer and trigger an immediate poll
if (pollTimeoutRef.current) {
clearTimeout(pollTimeoutRef.current);
pollTimeoutRef.current = null;
}
// Skip if another poll is already in-flight to prevent race conditions
if (pollInFlightRef.current) return;
const capturedCampaign = capturedCampaignRef.current;
const immediatePoll = async () => {
if (!mountedRef.current || pollInFlightRef.current) return;
pollInFlightRef.current = true;
try {
await loginWithDeepLink(deepLinkToken, capturedCampaign);
if (expireTimeoutRef.current) {
clearTimeout(expireTimeoutRef.current);
expireTimeoutRef.current = null;
}
if (mountedRef.current) {
setDeepLinkPolling(false);
navigate('/');
}
} catch (err: unknown) {
if (!mountedRef.current) return;
if (isAxiosError(err)) {
if (err.response?.status === 202) {
pollTimeoutRef.current = setTimeout(immediatePoll, DEEPLINK_POLL_INTERVAL_MS);
return;
}
if (err.response?.status === 410) {
if (expireTimeoutRef.current) {
clearTimeout(expireTimeoutRef.current);
expireTimeoutRef.current = null;
}
setDeepLinkPolling(false);
setDeepLinkToken(null);
setDeepLinkError(t('auth.deepLinkExpired'));
return;
}
}
if (expireTimeoutRef.current) {
clearTimeout(expireTimeoutRef.current);
expireTimeoutRef.current = null;
}
setDeepLinkPolling(false);
setDeepLinkError(t('common.error'));
} finally {
pollInFlightRef.current = false;
}
};
immediatePoll();
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
// Sever any in-flight recursive immediatePoll chain from this effect cycle
if (pollTimeoutRef.current) {
clearTimeout(pollTimeoutRef.current);
pollTimeoutRef.current = null;
}
};
}, [deepLinkPolling, deepLinkToken, loginWithDeepLink, navigate, t]);
if (!botUsername || botUsername === 'your_bot') { if (!botUsername || botUsername === 'your_bot') {
return ( return (
<div className="py-4 text-center text-sm text-gray-500"> <div className="py-4 text-center text-sm text-gray-500">
@@ -328,79 +430,90 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
// Deep link fallback UI // Deep link fallback UI
if (scriptFailed) { if (scriptFailed) {
const resolvedBotUsername = deepLinkBotUsername || botUsername;
const deepLinkUrl = deepLinkToken const deepLinkUrl = deepLinkToken
? `https://t.me/${deepLinkBotUsername || botUsername}?start=webauth_${deepLinkToken}` ? `https://t.me/${resolvedBotUsername}?start=webauth_${deepLinkToken}`
: ''; : '';
const startCommand = deepLinkToken ? `/start webauth_${deepLinkToken}` : '';
return ( return (
<div className="flex flex-col items-center space-y-4"> <div className="flex flex-col items-center space-y-5">
<div className="flex flex-col items-center space-y-3"> {/* Info message */}
{/* Info message */} <p className="max-w-xs text-center text-xs text-dark-400">
<p className="max-w-xs text-center text-xs text-dark-400"> {t('auth.telegramWidgetBlocked')}
{t('auth.telegramWidgetBlocked')} </p>
</p>
{deepLinkToken && deepLinkUrl ? ( {deepLinkToken && deepLinkUrl ? (
<> <>
{/* Deep link button */} {/* QR Code */}
<a
href={deepLinkUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 rounded-lg bg-[#54a9eb] px-6 py-3 text-sm font-medium text-white shadow-sm transition-colors hover:bg-[#4a96d2]"
>
<svg className="h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
</svg>
{t('auth.openBotToLogin')}
</a>
{/* Polling status */}
{deepLinkPolling && (
<div className="flex items-center gap-2 text-xs text-dark-400">
<span className="h-3 w-3 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
{t('auth.waitingForConfirmation')}
</div>
)}
</>
) : deepLinkError ? (
<div className="flex flex-col items-center space-y-2"> <div className="flex flex-col items-center space-y-2">
<p className="text-xs text-red-500">{deepLinkError}</p> <div className="rounded-2xl bg-white p-4">
<QRCodeSVG value={deepLinkUrl} size={180} level="M" includeMargin={false} />
</div>
<p className="text-[11px] text-dark-500">{t('auth.scanQrToLogin')}</p>
</div>
{/* Open bot button */}
<a
href={deepLinkUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 rounded-lg bg-[#54a9eb] px-6 py-3 text-sm font-medium text-white shadow-sm transition-colors hover:bg-[#4a96d2]"
>
<svg className="h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
</svg>
{t('auth.openBotToLogin')}
</a>
{/* Manual command */}
<div className="flex w-full max-w-xs flex-col items-center space-y-1.5">
<p className="text-[11px] text-dark-500">{t('auth.orSendCommand')}</p>
<button <button
type="button" type="button"
onClick={startDeepLinkAuth} onClick={() => {
className="text-sm text-accent-400 transition-colors hover:text-accent-300" copyToClipboard(startCommand)
.then(() => {
setCopied(true);
if (copiedTimeoutRef.current) clearTimeout(copiedTimeoutRef.current);
copiedTimeoutRef.current = setTimeout(() => setCopied(false), 2000);
})
.catch(() => {});
}}
className="group flex w-full items-center justify-between rounded-lg border border-dark-700 bg-dark-800/50 px-3 py-2 transition-colors hover:border-dark-600"
> >
{t('auth.tryAgain')} <code className="truncate text-xs text-dark-300">{startCommand}</code>
<span className="ml-2 flex-shrink-0 text-[10px] text-dark-500 transition-colors group-hover:text-dark-300">
{copied ? t('auth.commandCopied') : t('common.copy')}
</span>
</button> </button>
</div> </div>
) : (
<div className="flex items-center gap-2 text-xs text-dark-400">
<span className="h-3 w-3 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
{t('common.loading')}
</div>
)}
</div>
{/* Bot link fallback */} {/* Polling status */}
<div className="text-center"> {deepLinkPolling && (
<p className="mb-2 text-xs text-dark-500">{t('auth.orOpenInApp')}</p> <div className="flex items-center gap-2 text-xs text-dark-400">
<a <span className="h-3 w-3 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
href={ {t('auth.waitingForConfirmation')}
referralCode </div>
? `https://t.me/${botUsername}?start=${encodeURIComponent(referralCode)}` )}
: `https://t.me/${botUsername}` </>
} ) : deepLinkError ? (
target="_blank" <div className="flex flex-col items-center space-y-2">
rel="noopener noreferrer" <p className="text-xs text-red-500">{deepLinkError}</p>
className="text-telegram-blue inline-flex items-center text-sm hover:underline" <button
> type="button"
<svg className="mr-1 h-4 w-4" viewBox="0 0 24 24" fill="currentColor"> onClick={startDeepLinkAuth}
<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" /> className="text-sm text-accent-400 transition-colors hover:text-accent-300"
</svg> >
@{botUsername} {t('auth.tryAgain')}
</a> </button>
</div> </div>
) : (
<div className="flex items-center gap-2 text-xs text-dark-400">
<span className="h-3 w-3 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
{t('common.loading')}
</div>
)}
</div> </div>
); );
} }

View File

@@ -180,6 +180,9 @@
"waitingForConfirmation": "Waiting for confirmation...", "waitingForConfirmation": "Waiting for confirmation...",
"deepLinkExpired": "Link expired. Please try again.", "deepLinkExpired": "Link expired. Please try again.",
"tryAgain": "Try Again", "tryAgain": "Try Again",
"scanQrToLogin": "Scan QR code with your phone camera",
"orSendCommand": "Or send the bot this command:",
"commandCopied": "Command copied",
"welcomeBack": "Welcome back!", "welcomeBack": "Welcome back!",
"loginTitle": "Login to Cabinet", "loginTitle": "Login to Cabinet",
"loginSubtitle": "Sign in with Telegram or use your email", "loginSubtitle": "Sign in with Telegram or use your email",
@@ -1701,7 +1704,14 @@
"enableEmail": "Email", "enableEmail": "Email",
"sendingBoth": "2 broadcasts will be created", "sendingBoth": "2 broadcasts will be created",
"bothCreated": "Broadcasts created", "bothCreated": "Broadcasts created",
"atLeastOneChannel": "Select at least one channel" "atLeastOneChannel": "Select at least one channel",
"customButtons": "Custom buttons",
"addCustomButton": "Add button",
"customButtonLabelPlaceholder": "Button text",
"customButtonTypeCallback": "Callback",
"customButtonTypeUrl": "URL",
"customButtonCallbackPlaceholder": "callback_data (e.g. back_to_menu)",
"customButtonUrlPlaceholder": "https://example.com"
}, },
"pinnedMessages": { "pinnedMessages": {
"title": "Pinned Messages", "title": "Pinned Messages",

View File

@@ -172,6 +172,9 @@
"waitingForConfirmation": "در انتظار تایید...", "waitingForConfirmation": "در انتظار تایید...",
"deepLinkExpired": "لینک منقضی شده است. لطفا دوباره تلاش کنید.", "deepLinkExpired": "لینک منقضی شده است. لطفا دوباره تلاش کنید.",
"tryAgain": "تلاش مجدد", "tryAgain": "تلاش مجدد",
"scanQrToLogin": "کد QR را با دوربین گوشی اسکن کنید",
"orSendCommand": "یا این دستور را به ربات ارسال کنید:",
"commandCopied": "دستور کپی شد",
"welcomeBack": "خوش آمدید!", "welcomeBack": "خوش آمدید!",
"loginTitle": "ورود به کابین", "loginTitle": "ورود به کابین",
"loginSubtitle": "با تلگرام یا ایمیل وارد شوید", "loginSubtitle": "با تلگرام یا ایمیل وارد شوید",
@@ -1336,7 +1339,14 @@
"enableEmail": "Email", "enableEmail": "Email",
"sendingBoth": "۲ پیام‌رسانی ایجاد خواهد شد", "sendingBoth": "۲ پیام‌رسانی ایجاد خواهد شد",
"bothCreated": "پیام‌رسانی‌ها ایجاد شدند", "bothCreated": "پیام‌رسانی‌ها ایجاد شدند",
"atLeastOneChannel": "حداقل یک کانال را انتخاب کنید" "atLeastOneChannel": "حداقل یک کانال را انتخاب کنید",
"customButtons": "دکمه‌های سفارشی",
"addCustomButton": "افزودن دکمه",
"customButtonLabelPlaceholder": "متن دکمه",
"customButtonTypeCallback": "Callback",
"customButtonTypeUrl": "لینک",
"customButtonCallbackPlaceholder": "callback_data (مثلاً back_to_menu)",
"customButtonUrlPlaceholder": "https://example.com"
}, },
"pinnedMessages": { "pinnedMessages": {
"title": "Pinned Messages", "title": "Pinned Messages",

View File

@@ -183,6 +183,9 @@
"waitingForConfirmation": "Ожидание подтверждения...", "waitingForConfirmation": "Ожидание подтверждения...",
"deepLinkExpired": "Ссылка истекла. Попробуйте снова.", "deepLinkExpired": "Ссылка истекла. Попробуйте снова.",
"tryAgain": "Попробовать снова", "tryAgain": "Попробовать снова",
"scanQrToLogin": "Отсканируйте QR-код камерой телефона",
"orSendCommand": "Или отправьте боту команду:",
"commandCopied": "Команда скопирована",
"welcomeBack": "Добро пожаловать!", "welcomeBack": "Добро пожаловать!",
"loginTitle": "Вход в личный кабинет", "loginTitle": "Вход в личный кабинет",
"loginSubtitle": "Войдите через Telegram или используйте email", "loginSubtitle": "Войдите через Telegram или используйте email",
@@ -1726,7 +1729,14 @@
"enableEmail": "Email", "enableEmail": "Email",
"sendingBoth": "Будет создано 2 рассылки", "sendingBoth": "Будет создано 2 рассылки",
"bothCreated": "Рассылки созданы", "bothCreated": "Рассылки созданы",
"atLeastOneChannel": "Выберите хотя бы один канал" "atLeastOneChannel": "Выберите хотя бы один канал",
"customButtons": "Кастомные кнопки",
"addCustomButton": "Добавить кнопку",
"customButtonLabelPlaceholder": "Текст кнопки",
"customButtonTypeCallback": "Callback",
"customButtonTypeUrl": "Ссылка",
"customButtonCallbackPlaceholder": "callback_data (например, back_to_menu)",
"customButtonUrlPlaceholder": "https://example.com"
}, },
"pinnedMessages": { "pinnedMessages": {
"title": "Закреплённые сообщения", "title": "Закреплённые сообщения",

View File

@@ -172,6 +172,9 @@
"waitingForConfirmation": "等待确认...", "waitingForConfirmation": "等待确认...",
"deepLinkExpired": "链接已过期,请重试。", "deepLinkExpired": "链接已过期,请重试。",
"tryAgain": "重试", "tryAgain": "重试",
"scanQrToLogin": "用手机相机扫描二维码",
"orSendCommand": "或向机器人发送命令:",
"commandCopied": "命令已复制",
"welcomeBack": "欢迎回来!", "welcomeBack": "欢迎回来!",
"loginTitle": "登录个人中心", "loginTitle": "登录个人中心",
"loginSubtitle": "通过Telegram或邮箱登录", "loginSubtitle": "通过Telegram或邮箱登录",
@@ -1410,7 +1413,14 @@
"enableEmail": "Email", "enableEmail": "Email",
"sendingBoth": "将创建2个群发", "sendingBoth": "将创建2个群发",
"bothCreated": "群发已创建", "bothCreated": "群发已创建",
"atLeastOneChannel": "请至少选择一个渠道" "atLeastOneChannel": "请至少选择一个渠道",
"customButtons": "自定义按钮",
"addCustomButton": "添加按钮",
"customButtonLabelPlaceholder": "按钮文字",
"customButtonTypeCallback": "回调",
"customButtonTypeUrl": "链接",
"customButtonCallbackPlaceholder": "callback_data例如 back_to_menu",
"customButtonUrlPlaceholder": "https://example.com"
}, },
"pinnedMessages": { "pinnedMessages": {
"title": "置顶消息", "title": "置顶消息",

View File

@@ -7,6 +7,7 @@ import {
BroadcastFilter, BroadcastFilter,
TariffFilter, TariffFilter,
CombinedBroadcastCreateRequest, CombinedBroadcastCreateRequest,
CustomBroadcastButton,
} from '../api/adminBroadcasts'; } from '../api/adminBroadcasts';
import { AdminBackButton } from '../components/admin'; import { AdminBackButton } from '../components/admin';
@@ -130,6 +131,11 @@ export default function AdminBroadcastCreate() {
// Telegram-specific state // Telegram-specific state
const [messageText, setMessageText] = useState(''); const [messageText, setMessageText] = useState('');
const [selectedButtons, setSelectedButtons] = useState<string[]>(['home']); const [selectedButtons, setSelectedButtons] = useState<string[]>(['home']);
const [customButtons, setCustomButtons] = useState<CustomBroadcastButton[]>([]);
const [isAddingCustomButton, setIsAddingCustomButton] = useState(false);
const [newButtonLabel, setNewButtonLabel] = useState('');
const [newButtonActionType, setNewButtonActionType] = useState<'callback' | 'url'>('callback');
const [newButtonActionValue, setNewButtonActionValue] = useState('');
const [mediaFile, setMediaFile] = useState<File | null>(null); const [mediaFile, setMediaFile] = useState<File | null>(null);
const [mediaType, setMediaType] = useState<'photo' | 'video' | 'document'>('photo'); const [mediaType, setMediaType] = useState<'photo' | 'video' | 'document'>('photo');
const [mediaPreview, setMediaPreview] = useState<string | null>(null); const [mediaPreview, setMediaPreview] = useState<string | null>(null);
@@ -275,28 +281,33 @@ export default function AdminBroadcastCreate() {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (!file) return; if (!file) return;
setMediaFile(file); // Determine type locally to avoid stale state in async call
let detectedType: 'photo' | 'video' | 'document';
if (file.type.startsWith('image/')) { if (file.type.startsWith('image/')) {
setMediaType('photo'); detectedType = 'photo';
} else if (file.type.startsWith('video/')) {
detectedType = 'video';
} else {
detectedType = 'document';
}
setMediaFile(file);
setMediaType(detectedType);
if (detectedType === 'photo') {
if (mediaPreviewRef.current) URL.revokeObjectURL(mediaPreviewRef.current); if (mediaPreviewRef.current) URL.revokeObjectURL(mediaPreviewRef.current);
const url = URL.createObjectURL(file); const url = URL.createObjectURL(file);
mediaPreviewRef.current = url; mediaPreviewRef.current = url;
setMediaPreview(url); setMediaPreview(url);
} else if (file.type.startsWith('video/')) {
setMediaType('video');
setMediaPreview(null);
} else { } else {
setMediaType('document');
setMediaPreview(null); setMediaPreview(null);
} }
setIsUploading(true); setIsUploading(true);
try { try {
const result = await adminBroadcastsApi.uploadMedia(file, mediaType); const result = await adminBroadcastsApi.uploadMedia(file, detectedType);
setUploadedFileId(result.file_id); setUploadedFileId(result.file_id);
} catch (err) { } catch {
console.error('Upload failed:', err);
setMediaFile(null); setMediaFile(null);
setMediaPreview(null); setMediaPreview(null);
} finally { } finally {
@@ -325,6 +336,39 @@ export default function AdminBroadcastCreate() {
); );
}; };
// Custom button validation
const isNewButtonValid = useMemo(() => {
if (!newButtonLabel.trim() || !newButtonActionValue.trim()) return false;
if (newButtonActionType === 'url') {
return /^https:\/\/|^tg:\/\//.test(newButtonActionValue.trim());
}
if (newButtonActionType === 'callback') {
return new TextEncoder().encode(newButtonActionValue.trim()).length <= 64;
}
return true;
}, [newButtonLabel, newButtonActionType, newButtonActionValue]);
// Custom button handlers
const addCustomButton = () => {
if (!isNewButtonValid) return;
setCustomButtons((prev) => [
...prev,
{
label: newButtonLabel.trim(),
action_type: newButtonActionType,
action_value: newButtonActionValue.trim(),
},
]);
setNewButtonLabel('');
setNewButtonActionValue('');
setNewButtonActionType('callback');
setIsAddingCustomButton(false);
};
const removeCustomButton = (index: number) => {
setCustomButtons((prev) => prev.filter((_, i) => i !== index));
};
// Validate form // Validate form
const isTelegramValid = telegramEnabled && telegramTarget && messageText.trim().length > 0; const isTelegramValid = telegramEnabled && telegramTarget && messageText.trim().length > 0;
const isEmailValid = const isEmailValid =
@@ -350,6 +394,7 @@ export default function AdminBroadcastCreate() {
target: telegramTarget, target: telegramTarget,
message_text: messageText, message_text: messageText,
selected_buttons: selectedButtons, selected_buttons: selectedButtons,
custom_buttons: customButtons.length > 0 ? customButtons : undefined,
}; };
if (uploadedFileId) { if (uploadedFileId) {
data.media = { type: mediaType, file_id: uploadedFileId }; data.media = { type: mediaType, file_id: uploadedFileId };
@@ -377,6 +422,7 @@ export default function AdminBroadcastCreate() {
target: telegramTarget, target: telegramTarget,
message_text: messageText, message_text: messageText,
selected_buttons: selectedButtons, selected_buttons: selectedButtons,
custom_buttons: customButtons.length > 0 ? customButtons : undefined,
}; };
if (uploadedFileId) { if (uploadedFileId) {
telegramData.media = { type: mediaType, file_id: uploadedFileId }; telegramData.media = { type: mediaType, file_id: uploadedFileId };
@@ -655,6 +701,123 @@ export default function AdminBroadcastCreate() {
))} ))}
</div> </div>
</div> </div>
{/* Custom buttons */}
<div>
<label className="mb-2 block text-sm font-medium text-dark-300">
{t('admin.broadcasts.customButtons')}
</label>
{/* Existing custom buttons */}
{customButtons.length > 0 && (
<div className="mb-3 space-y-2">
{customButtons.map((btn, index) => (
<div
key={index}
className="flex items-center justify-between rounded-lg border border-dark-700 bg-dark-800 px-3 py-2"
>
<div className="flex items-center gap-2 overflow-hidden">
<span className="shrink-0 rounded bg-dark-700 px-1.5 py-0.5 text-xs text-dark-400">
{btn.action_type === 'url'
? t('admin.broadcasts.customButtonTypeUrl')
: t('admin.broadcasts.customButtonTypeCallback')}
</span>
<span className="truncate text-sm text-dark-100">{btn.label}</span>
<span className="truncate text-xs text-dark-500">{btn.action_value}</span>
</div>
<button
onClick={() => removeCustomButton(index)}
className="ml-2 shrink-0 rounded p-1 text-dark-400 hover:bg-dark-700 hover:text-error-400"
>
<XIcon />
</button>
</div>
))}
</div>
)}
{/* Inline add form */}
{isAddingCustomButton ? (
<form
onSubmit={(e) => {
e.preventDefault();
addCustomButton();
}}
className="space-y-3 rounded-lg border border-dark-600 bg-dark-800/50 p-3"
>
<input
type="text"
value={newButtonLabel}
onChange={(e) => setNewButtonLabel(e.target.value)}
placeholder={t('admin.broadcasts.customButtonLabelPlaceholder')}
maxLength={64}
className="input"
autoFocus
/>
<div className="flex gap-2">
<button
type="button"
onClick={() => setNewButtonActionType('callback')}
className={`flex-1 rounded-lg px-3 py-2 text-sm transition-colors ${
newButtonActionType === 'callback'
? 'bg-accent-500 text-white'
: 'border border-dark-700 bg-dark-800 text-dark-300 hover:bg-dark-700'
}`}
>
{t('admin.broadcasts.customButtonTypeCallback')}
</button>
<button
type="button"
onClick={() => setNewButtonActionType('url')}
className={`flex-1 rounded-lg px-3 py-2 text-sm transition-colors ${
newButtonActionType === 'url'
? 'bg-accent-500 text-white'
: 'border border-dark-700 bg-dark-800 text-dark-300 hover:bg-dark-700'
}`}
>
{t('admin.broadcasts.customButtonTypeUrl')}
</button>
</div>
<input
type="text"
value={newButtonActionValue}
onChange={(e) => setNewButtonActionValue(e.target.value)}
placeholder={
newButtonActionType === 'url'
? t('admin.broadcasts.customButtonUrlPlaceholder')
: t('admin.broadcasts.customButtonCallbackPlaceholder')
}
maxLength={newButtonActionType === 'callback' ? 64 : 256}
className="input"
/>
<div className="flex gap-2">
<button
type="button"
onClick={() => {
setIsAddingCustomButton(false);
setNewButtonLabel('');
setNewButtonActionValue('');
}}
className="btn-secondary flex-1"
>
{t('common.cancel')}
</button>
<button type="submit" disabled={!isNewButtonValid} className="btn-primary flex-1">
{t('common.add')}
</button>
</div>
</form>
) : (
<button
onClick={() => setIsAddingCustomButton(true)}
disabled={customButtons.length >= 10}
className="flex w-full items-center justify-center gap-2 rounded-lg border border-dashed border-dark-600 bg-dark-800/50 px-4 py-3 text-sm text-dark-400 transition-colors hover:border-dark-500 hover:bg-dark-800 hover:text-dark-300"
>
<span>+</span>
<span>{t('admin.broadcasts.addCustomButton')}</span>
</button>
)}
</div>
</div> </div>
)} )}

View File

@@ -1387,8 +1387,10 @@ export default function AdminUserDetail() {
{t('admin.users.detail.subscription.traffic')} {t('admin.users.detail.subscription.traffic')}
</div> </div>
<div className="text-dark-100"> <div className="text-dark-100">
{user.subscription.traffic_used_gb.toFixed(1)} /{' '} {panelInfo?.found
{user.subscription.traffic_limit_gb} {t('common.units.gb')} ? (panelInfo.used_traffic_bytes / (1024 * 1024 * 1024)).toFixed(1)
: user.subscription.traffic_used_gb.toFixed(1)}{' '}
/ {user.subscription.traffic_limit_gb} {t('common.units.gb')}
</div> </div>
</div> </div>
<div> <div>

View File

@@ -15,14 +15,14 @@ import {
type BrandingInfo, type BrandingInfo,
type EmailAuthEnabled, type EmailAuthEnabled,
} from '../api/branding'; } from '../api/branding';
import { getAndClearReturnUrl } from '../utils/token'; import { getAndClearReturnUrl, tokenStorage } from '../utils/token';
import { isInTelegramWebApp, getTelegramInitData, useTelegramSDK } from '../hooks/useTelegramSDK'; import { isInTelegramWebApp, getTelegramInitData, useTelegramSDK } from '../hooks/useTelegramSDK';
import { closeMiniApp } from '@telegram-apps/sdk-react'; import { closeMiniApp } from '@telegram-apps/sdk-react';
import LanguageSwitcher from '../components/LanguageSwitcher'; import LanguageSwitcher from '../components/LanguageSwitcher';
import TelegramLoginButton from '../components/TelegramLoginButton'; import TelegramLoginButton from '../components/TelegramLoginButton';
import OAuthProviderIcon from '../components/OAuthProviderIcon'; import OAuthProviderIcon from '../components/OAuthProviderIcon';
import { saveOAuthState } from '../utils/oauth'; import { saveOAuthState } from '../utils/oauth';
import { consumeReferralCode, getPendingReferralCode } from '../utils/referral'; import { getPendingReferralCode } from '../utils/referral';
export default function Login() { export default function Login() {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -146,16 +146,6 @@ export default function Login() {
} }
}; };
const botUsername = import.meta.env.VITE_TELEGRAM_BOT_USERNAME || '';
// If email auth is disabled but user came with ref param, redirect to bot
useEffect(() => {
if (referralCode && emailAuthConfig?.enabled === false && botUsername) {
consumeReferralCode();
window.location.href = `https://t.me/${botUsername}?start=${encodeURIComponent(referralCode)}`;
}
}, [referralCode, emailAuthConfig, botUsername]);
const appName = branding ? branding.name : import.meta.env.VITE_APP_NAME || 'VPN'; const appName = branding ? branding.name : import.meta.env.VITE_APP_NAME || 'VPN';
const appLogo = branding?.logo_letter || import.meta.env.VITE_APP_LOGO || 'V'; const appLogo = branding?.logo_letter || import.meta.env.VITE_APP_LOGO || 'V';
const logoUrl = branding ? brandingApi.getLogoUrl(branding) : null; const logoUrl = branding ? brandingApi.getLogoUrl(branding) : null;
@@ -215,11 +205,18 @@ export default function Login() {
}, [isAuthInitializing, loginWithTelegram, navigate, t, getReturnUrl]); }, [isAuthInitializing, loginWithTelegram, navigate, t, getReturnUrl]);
const handleRetryTelegramAuth = () => { const handleRetryTelegramAuth = () => {
// Clear ALL cached auth state to prevent stale token/initData loops
tokenStorage.clearTokens();
sessionStorage.removeItem('tapps/launchParams');
sessionStorage.removeItem('telegram_init_data');
localStorage.removeItem('cabinet-auth');
localStorage.removeItem('tg_user_id');
try { try {
sessionStorage.removeItem('tapps/launchParams'); // Close miniapp — Telegram will provide fresh initData on reopen
sessionStorage.removeItem('telegram_init_data');
closeMiniApp(); closeMiniApp();
} catch { } catch {
// If closeMiniApp fails, force a clean page reload
window.location.reload(); window.location.reload();
} }
}; };

View File

@@ -2124,7 +2124,12 @@ export default function Subscription() {
<div className="text-sm font-semibold text-dark-50"> <div className="text-sm font-semibold text-dark-50">
{device.device_model || device.platform} {device.device_model || device.platform}
</div> </div>
<div className="text-[11px] text-dark-50/30">{device.platform}</div> <div className="flex items-center gap-1.5 text-[11px] text-dark-50/30">
<span>{device.platform}</span>
<span className="font-mono text-dark-50/20">
{device.hwid.slice(0, 8).toUpperCase()}
</span>
</div>
</div> </div>
</div> </div>
<button <button

View File

@@ -45,7 +45,12 @@ export default function SubscriptionPurchase() {
const subscription = subscriptionResponse?.subscription ?? null; const subscription = subscriptionResponse?.subscription ?? null;
// Purchase options // Purchase options
const { data: purchaseOptions, isLoading: optionsLoading } = useQuery({ const {
data: purchaseOptions,
isLoading: optionsLoading,
isError: optionsError,
refetch: refetchOptions,
} = useQuery({
queryKey: ['purchase-options'], queryKey: ['purchase-options'],
queryFn: subscriptionApi.getPurchaseOptions, queryFn: subscriptionApi.getPurchaseOptions,
staleTime: 0, staleTime: 0,
@@ -362,6 +367,58 @@ export default function SubscriptionPurchase() {
); );
} }
if (optionsError || (!purchaseOptions && !optionsLoading)) {
return (
<div className="space-y-6">
<div className="flex items-center gap-3">
<button
onClick={() => navigate('/subscription')}
aria-label="Back"
className="flex h-9 w-9 items-center justify-center rounded-xl transition-colors"
style={{
background: g.innerBg,
border: `1px solid ${g.innerBorder}`,
}}
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="text-dark-50/60"
>
<path d="M19 12H5M12 19l-7-7 7-7" />
</svg>
</button>
<h1 className="text-2xl font-bold text-dark-50 sm:text-3xl">
{t('subscription.extend')}
</h1>
</div>
<div
className="rounded-3xl p-6 text-center"
style={{
background: g.cardBg,
border: `1px solid ${g.cardBorder}`,
}}
>
<p className="mb-4 text-dark-300">
{t('subscription.loadError', 'Не удалось загрузить варианты подписки')}
</p>
<button
onClick={() => refetchOptions()}
className="rounded-xl bg-accent-500 px-6 py-2 text-sm font-medium text-white transition-colors hover:bg-accent-600"
>
{t('common.retry')}
</button>
</div>
</div>
);
}
return ( return (
<div className="space-y-6"> <div className="space-y-6">
{/* Header with back link */} {/* Header with back link */}
@@ -1936,6 +1993,30 @@ export default function SubscriptionPurchase() {
)} )}
</div> </div>
)} )}
{/* No options available fallback */}
{purchaseOptions &&
!optionsLoading &&
!(isTariffsMode && tariffs.length > 0) &&
!(classicOptions && classicOptions.periods.length > 0) && (
<div
className="rounded-3xl p-6 text-center"
style={{
background: g.cardBg,
border: `1px solid ${g.cardBorder}`,
}}
>
<p className="mb-4 text-dark-300">
{t('subscription.noOptionsAvailable', 'Нет доступных вариантов подписки')}
</p>
<button
onClick={() => refetchOptions()}
className="rounded-xl bg-accent-500 px-6 py-2 text-sm font-medium text-white transition-colors hover:bg-accent-600"
>
{t('common.retry')}
</button>
</div>
)}
</div> </div>
); );
} }

View File

@@ -6,6 +6,7 @@ import { useAuthStore } from '../store/auth';
import { useShallow } from 'zustand/shallow'; import { useShallow } from 'zustand/shallow';
import { brandingApi } from '../api/branding'; import { brandingApi } from '../api/branding';
import { isInTelegramWebApp, getTelegramInitData } from '../hooks/useTelegramSDK'; import { isInTelegramWebApp, getTelegramInitData } from '../hooks/useTelegramSDK';
import { tokenStorage } from '../utils/token';
// Validate redirect URL to prevent open redirect attacks // Validate redirect URL to prevent open redirect attacks
const getSafeRedirectUrl = (url: string | null): string => { const getSafeRedirectUrl = (url: string | null): string => {
@@ -117,6 +118,14 @@ export default function TelegramRedirect() {
const newCount = retryCount + 1; const newCount = retryCount + 1;
setRetryCount(newCount); setRetryCount(newCount);
sessionStorage.setItem(RETRY_COUNT_KEY, String(newCount)); sessionStorage.setItem(RETRY_COUNT_KEY, String(newCount));
// Clear all cached auth state to prevent stale token/initData loops
tokenStorage.clearTokens();
sessionStorage.removeItem('tapps/launchParams');
sessionStorage.removeItem('telegram_init_data');
localStorage.removeItem('cabinet-auth');
localStorage.removeItem('tg_user_id');
setStatus('loading'); setStatus('loading');
setErrorMessage(''); setErrorMessage('');
window.location.reload(); window.location.reload();

View File

@@ -45,7 +45,7 @@ interface AuthState {
state: string, state: string,
deviceId?: string | null, deviceId?: string | null,
) => Promise<void>; ) => Promise<void>;
loginWithDeepLink: (token: string) => Promise<void>; loginWithDeepLink: (token: string, campaignSlug?: string | null) => Promise<void>;
registerWithEmail: ( registerWithEmail: (
email: string, email: string,
password: string, password: string,
@@ -322,8 +322,8 @@ export const useAuthStore = create<AuthState>()(
await get().checkAdminStatus(); await get().checkAdminStatus();
}, },
loginWithDeepLink: async (token) => { loginWithDeepLink: async (token, campaignSlug) => {
const response = await authApi.pollDeepLinkToken(token); const response = await authApi.pollDeepLinkToken(token, campaignSlug);
if (!response.access_token || !response.refresh_token) { if (!response.access_token || !response.refresh_token) {
throw new Error('Invalid auth response: missing tokens'); throw new Error('Invalid auth response: missing tokens');
} }