Merge remote-tracking branch 'origin/main' into feat/linear-ui-redesign

# Conflicts:
#	src/components/PromoDiscountBadge.tsx
This commit is contained in:
c0mrade
2026-02-04 03:25:35 +03:00
9 changed files with 614 additions and 130 deletions

View File

@@ -35,6 +35,10 @@ export interface ClaimOfferResponse {
expires_at: string | null;
}
export interface DeactivateDiscountResponse {
success: boolean;
}
export interface LoyaltyTierInfo {
id: number;
name: string;
@@ -94,4 +98,10 @@ export const promoApi = {
const response = await apiClient.delete<{ message: string }>('/cabinet/promo/active-discount');
return response.data;
},
// Deactivate current active promo discount
deactivateDiscount: async (): Promise<DeactivateDiscountResponse> => {
const response = await apiClient.post<DeactivateDiscountResponse>('/cabinet/promo/deactivate');
return response.data;
},
};

View File

@@ -292,13 +292,20 @@ export default function ConnectionModal({ onClose }: ConnectionModalProps) {
const handleConnect = (app: AppInfo) => {
if (!app.deepLink || !isValidDeepLink(app.deepLink)) return;
const lang = i18n.language?.startsWith('ru') ? 'ru' : 'en';
const redirectUrl = `${window.location.origin}/miniapp/redirect.html?url=${encodeURIComponent(app.deepLink)}&lang=${lang}`;
const deepLink = app.deepLink;
// All deep links (including custom schemes like happ://, clash://, etc.)
// go through redirect.html. Telegram's openLink opens the redirect page
// in an external browser, which then performs window.location.href to the
// actual deep link URL. This works for both http(s) and custom schemes.
const redirectUrl = `${window.location.origin}/miniapp/redirect.html?url=${encodeURIComponent(deepLink)}&lang=${i18n.language || 'en'}`;
const tg = (
window as unknown as {
Telegram?: { WebApp?: { openLink?: (url: string, options?: object) => void } };
}
).Telegram?.WebApp;
if (tg?.openLink) {
try {
tg.openLink(redirectUrl, { try_instant_view: false, try_browser: true });

View File

@@ -0,0 +1,378 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import { promoApi } from '../api/promo';
const SparklesIcon = () => (
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09z"
/>
</svg>
);
const ClockIcon = () => (
<svg
className="h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
);
const XCircleIcon = () => (
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
);
const WarningIcon = () => (
<svg
className="h-12 w-12"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={1.5}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"
/>
</svg>
);
const formatTimeLeft = (expiresAt: string, t: (key: string) => string): string => {
const now = new Date();
// Ensure UTC parsing - if no timezone specified, assume UTC
let expires: Date;
if (expiresAt.includes('Z') || expiresAt.includes('+') || expiresAt.includes('-', 10)) {
expires = new Date(expiresAt);
} else {
// No timezone - treat as UTC
expires = new Date(expiresAt + 'Z');
}
const diffMs = expires.getTime() - now.getTime();
if (diffMs <= 0) return '';
const hours = Math.floor(diffMs / (1000 * 60 * 60));
const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
if (hours > 24) {
const days = Math.floor(hours / 24);
return `${days}${t('promo.time.days')}`;
}
if (hours > 0) {
return `${hours}${t('promo.time.hours')} ${minutes}${t('promo.time.minutes')}`;
}
return `${minutes}${t('promo.time.minutes')}`;
};
// ------- Confirmation Modal -------
interface DeactivateConfirmModalProps {
isOpen: boolean;
discountPercent: number;
isDeactivating: boolean;
onConfirm: () => void;
onCancel: () => void;
}
function DeactivateConfirmModal({
isOpen,
discountPercent,
isDeactivating,
onConfirm,
onCancel,
}: DeactivateConfirmModalProps) {
const { t } = useTranslation();
// Escape key to close
useEffect(() => {
if (!isOpen) return;
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && !isDeactivating) {
e.preventDefault();
onCancel();
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [isOpen, isDeactivating, onCancel]);
// Scroll lock
useEffect(() => {
if (!isOpen) return;
document.body.style.overflow = 'hidden';
return () => {
document.body.style.overflow = '';
};
}, [isOpen]);
if (!isOpen) return null;
const modalContent = (
<div
className="fixed inset-0 z-[100] flex items-center justify-center"
role="dialog"
aria-modal="true"
aria-labelledby="deactivate-modal-title"
>
{/* Backdrop */}
<div
className="absolute inset-0 bg-black/70 backdrop-blur-sm"
onClick={isDeactivating ? undefined : onCancel}
/>
{/* Modal */}
<div
className="relative mx-4 w-full max-w-sm overflow-hidden rounded-2xl border border-dark-700/50 bg-dark-900 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
{/* Warning header */}
<div className="flex flex-col items-center bg-gradient-to-br from-warning-500/20 to-red-500/20 px-6 pb-6 pt-8">
<div className="mb-3 text-warning-400">
<WarningIcon />
</div>
<h2 id="deactivate-modal-title" className="text-center text-lg font-bold text-dark-100">
{t('promo.deactivate.confirmTitle')}
</h2>
<p className="mt-2 text-center text-sm text-dark-300">
{t('promo.deactivate.confirmDescription', { percent: discountPercent })}
</p>
</div>
{/* Warning text */}
<div className="px-6 py-4">
<div className="rounded-lg border border-warning-500/20 bg-warning-500/10 px-4 py-3">
<p className="text-center text-sm text-warning-400">{t('promo.deactivate.warning')}</p>
</div>
</div>
{/* Action buttons */}
<div className="flex gap-3 px-6 pb-6">
<button
onClick={onCancel}
disabled={isDeactivating}
className="flex-1 rounded-xl bg-dark-800 py-3 font-semibold text-dark-300 transition-colors hover:bg-dark-700 hover:text-dark-100 disabled:opacity-50"
>
{t('common.cancel')}
</button>
<button
onClick={onConfirm}
disabled={isDeactivating}
className="flex-1 rounded-xl bg-gradient-to-r from-red-500 to-red-600 py-3 font-semibold text-white shadow-lg shadow-red-500/25 transition-all hover:from-red-400 hover:to-red-500 active:from-red-600 active:to-red-700 disabled:opacity-50"
>
{isDeactivating ? (
<span className="flex items-center justify-center gap-2">
<span className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
{t('promo.deactivate.deactivating')}
</span>
) : (
t('promo.deactivate.confirm')
)}
</button>
</div>
</div>
</div>
);
if (typeof document !== 'undefined') {
return createPortal(modalContent, document.body);
}
return modalContent;
}
// ------- Main Component -------
export default function PromoDiscountBadge() {
const { t } = useTranslation();
const navigate = useNavigate();
const queryClient = useQueryClient();
const [isOpen, setIsOpen] = useState(false);
const [showConfirmModal, setShowConfirmModal] = useState(false);
const [deactivateError, setDeactivateError] = useState<string | null>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
const { data: activeDiscount } = useQuery({
queryKey: ['active-discount'],
queryFn: promoApi.getActiveDiscount,
staleTime: 30000,
refetchInterval: 60000, // Refresh every minute
});
const deactivateMutation = useMutation({
mutationFn: promoApi.deactivateDiscount,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['active-discount'] });
queryClient.invalidateQueries({ queryKey: ['promo-offers'] });
queryClient.invalidateQueries({ queryKey: ['subscription'] });
queryClient.invalidateQueries({ queryKey: ['purchase-options'] });
setShowConfirmModal(false);
setIsOpen(false);
setDeactivateError(null);
},
onError: (error: unknown) => {
const axiosErr = error as { response?: { data?: { detail?: string } } };
setDeactivateError(axiosErr.response?.data?.detail || t('promo.deactivate.error'));
},
});
const handleCloseConfirmModal = useCallback(() => {
if (!deactivateMutation.isPending) {
setShowConfirmModal(false);
setDeactivateError(null);
}
}, [deactivateMutation.isPending]);
const handleConfirmDeactivate = useCallback(() => {
setDeactivateError(null);
deactivateMutation.mutate();
}, [deactivateMutation]);
// Close dropdown on click outside
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
setIsOpen(false);
}
}
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
// Don't render if no active discount
if (!activeDiscount || !activeDiscount.is_active || !activeDiscount.discount_percent) {
return null;
}
const timeLeft = activeDiscount.expires_at ? formatTimeLeft(activeDiscount.expires_at, t) : null;
const handleClick = () => {
setIsOpen(!isOpen);
};
const handleGoToSubscription = () => {
setIsOpen(false);
navigate('/subscription');
};
const handleDeactivateClick = () => {
setDeactivateError(null);
setShowConfirmModal(true);
};
return (
<>
<div className="relative" ref={dropdownRef}>
{/* Badge button */}
<button
onClick={handleClick}
className="group relative flex items-center gap-1 rounded-lg bg-success-500/15 px-2.5 py-1.5 transition-all hover:bg-success-500/25"
title={t('promo.activeDiscount', 'Active discount')}
>
<span className="text-sm font-bold text-success-400">
-{activeDiscount.discount_percent}%
</span>
</button>
{/* Dropdown - mobile: fixed centered, desktop: absolute right */}
{isOpen && (
<>
{/* Mobile backdrop */}
<div
className="fixed inset-0 z-40 bg-black/30 sm:hidden"
onClick={() => setIsOpen(false)}
/>
<div className="fixed left-4 right-4 top-20 z-50 animate-fade-in overflow-hidden rounded-xl border border-dark-700/50 bg-dark-800 shadow-xl sm:absolute sm:left-auto sm:right-0 sm:top-auto sm:mt-2 sm:w-72">
{/* Header */}
<div className="border-b border-dark-700/50 bg-gradient-to-r from-success-500/20 to-accent-500/20 p-4">
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-success-500/20 text-success-400">
<SparklesIcon />
</div>
<div>
<div className="font-semibold text-dark-100">{t('promo.discountActive')}</div>
<div className="text-2xl font-bold text-success-400">
-{activeDiscount.discount_percent}%
</div>
</div>
</div>
</div>
{/* Content */}
<div className="space-y-3 p-4">
<p className="text-sm text-dark-300">{t('promo.discountDescription')}</p>
{/* Time remaining */}
{timeLeft && (
<div className="flex items-center gap-2 rounded-lg bg-dark-900/50 px-3 py-2 text-sm text-dark-400">
<ClockIcon />
<span>
{t('promo.expiresIn')}:{' '}
<span className="font-medium text-warning-400">{timeLeft}</span>
</span>
</div>
)}
{/* Deactivation error */}
{deactivateError && (
<div className="rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-400">
{deactivateError}
</div>
)}
{/* CTA Button */}
<button
onClick={handleGoToSubscription}
className="btn-primary w-full py-2.5 text-sm font-medium"
>
{t('promo.useNow')}
</button>
{/* Deactivate Button */}
<button
onClick={handleDeactivateClick}
className="flex w-full items-center justify-center gap-1.5 rounded-lg border border-dark-600/50 bg-dark-900/50 py-2 text-sm text-dark-400 transition-colors hover:border-red-500/30 hover:bg-red-500/10 hover:text-red-400"
aria-label={t('promo.deactivate.button')}
>
<XCircleIcon />
<span>{t('promo.deactivate.button')}</span>
</button>
</div>
</div>
</>
)}
</div>
{/* Deactivation Confirmation Modal */}
<DeactivateConfirmModal
isOpen={showConfirmModal}
discountPercent={activeDiscount.discount_percent}
isDeactivating={deactivateMutation.isPending}
onConfirm={handleConfirmDeactivate}
onCancel={handleCloseConfirmModal}
/>
</>
);
}

View File

@@ -322,7 +322,7 @@
"title": "Choose a plan to continue",
"description": "Your trial period is ending soon. Select a plan to continue using VPN without restrictions."
},
"expired": {
"expiredBanner": {
"title": "Subscription expired",
"selectTariff": "Your subscription has expired. Choose a plan below to restore access to VPN."
},
@@ -2567,6 +2567,15 @@
"activating": "Activating...",
"activate": "Activate",
"serverAccess": "Server access"
},
"deactivate": {
"button": "Cancel promo code",
"confirmTitle": "Cancel promo code?",
"confirmDescription": "Are you sure you want to cancel the {{percent}}% discount? After cancellation, you will be able to activate another promo code.",
"warning": "A cancelled promo code cannot be reused. The discount will stop working immediately.",
"confirm": "Cancel discount",
"deactivating": "Cancelling...",
"error": "Failed to cancel promo code. Please try again later."
}
},
"telegramRedirect": {

View File

@@ -2093,6 +2093,15 @@
"test": "آزمایشی",
"activating": "در حال فعال‌سازی...",
"activate": "فعال‌سازی"
},
"deactivate": {
"button": "لغو کد تخفیف",
"confirmTitle": "لغو کد تخفیف؟",
"confirmDescription": "آیا مطمئنید که می‌خواهید تخفیف {{percent}}% را لغو کنید؟ پس از لغو می‌توانید کد تخفیف دیگری فعال کنید.",
"warning": "کد تخفیف لغو شده قابل استفاده مجدد نیست. تخفیف بلافاصله متوقف می‌شود.",
"confirm": "لغو تخفیف",
"deactivating": "در حال لغو...",
"error": "لغو کد تخفیف ناموفق بود. لطفاً بعداً دوباره امتحان کنید."
}
},
"telegramRedirect": {

View File

@@ -344,7 +344,7 @@
"title": "Выберите тариф для продолжения",
"description": "Ваш пробный период скоро закончится. Выберите подходящий тариф, чтобы продолжить пользоваться VPN без ограничений."
},
"expired": {
"expiredBanner": {
"title": "Подписка истекла",
"selectTariff": "Ваша подписка истекла. Выберите тариф ниже, чтобы возобновить доступ к VPN."
},
@@ -3280,6 +3280,15 @@
"test": "Тест",
"activating": "Активация...",
"activate": "Активировать"
},
"deactivate": {
"button": "Отменить промокод",
"confirmTitle": "Отменить промокод?",
"confirmDescription": "Вы уверены, что хотите отменить скидку {{percent}}%? После отмены вы сможете активировать другой промокод.",
"warning": "Отменённый промокод нельзя будет использовать повторно. Скидка перестанет действовать немедленно.",
"confirm": "Отменить",
"deactivating": "Отмена...",
"error": "Не удалось отменить промокод. Попробуйте позже."
}
},
"telegramRedirect": {

View File

@@ -2092,6 +2092,15 @@
"test": "测试",
"activating": "激活中...",
"activate": "激活"
},
"deactivate": {
"button": "取消优惠码",
"confirmTitle": "取消优惠码?",
"confirmDescription": "您确定要取消 {{percent}}% 的折扣吗?取消后您可以激活其他优惠码。",
"warning": "已取消的优惠码无法重新使用。折扣将立即失效。",
"confirm": "取消折扣",
"deactivating": "取消中...",
"error": "取消优惠码失败,请稍后重试。"
}
},
"telegramRedirect": {

View File

@@ -181,7 +181,10 @@ export default function Subscription() {
if (selectedPeriod?.traffic.selectable && (selectedPeriod.traffic.options?.length ?? 0) > 0) {
result.push('traffic');
}
if (selectedPeriod && (selectedPeriod.servers.options?.length ?? 0) > 0) {
if (
selectedPeriod &&
(selectedPeriod.servers.options?.filter((s) => s.is_available).length ?? 0) > 0
) {
result.push('servers');
}
if (selectedPeriod && selectedPeriod.devices.max > selectedPeriod.devices.min) {
@@ -203,7 +206,12 @@ export default function Subscription() {
classicOptions.periods[0];
setSelectedPeriod(defaultPeriod);
setSelectedTraffic(classicOptions.selection.traffic_value);
setSelectedServers(classicOptions.selection.servers);
const availableServerUuids = new Set(
defaultPeriod.servers.options?.filter((s) => s.is_available).map((s) => s.uuid) ?? [],
);
setSelectedServers(
classicOptions.selection.servers.filter((uuid) => availableServerUuids.has(uuid)),
);
setSelectedDevices(classicOptions.selection.devices);
}
}, [classicOptions, selectedPeriod]);
@@ -1637,99 +1645,101 @@ export default function Subscription() {
)}
<div className="max-h-64 space-y-2 overflow-y-auto">
{countriesData.countries.map((country) => {
const isCurrentlyConnected = country.is_connected;
const isSelected = selectedServersToUpdate.includes(country.uuid);
const willBeAdded = !isCurrentlyConnected && isSelected;
const willBeRemoved = isCurrentlyConnected && !isSelected;
{countriesData.countries
.filter((country) => country.is_available || country.is_connected)
.map((country) => {
const isCurrentlyConnected = country.is_connected;
const isSelected = selectedServersToUpdate.includes(country.uuid);
const willBeAdded = !isCurrentlyConnected && isSelected;
const willBeRemoved = isCurrentlyConnected && !isSelected;
return (
<button
key={country.uuid}
onClick={() => {
if (isSelected) {
setSelectedServersToUpdate((prev) =>
prev.filter((u) => u !== country.uuid),
);
} else {
setSelectedServersToUpdate((prev) => [...prev, country.uuid]);
}
}}
disabled={!country.is_available && !isCurrentlyConnected}
className={`flex w-full items-center justify-between rounded-xl border p-3 text-left transition-all ${
isSelected
? willBeAdded
? 'border-success-500 bg-success-500/10'
: 'border-accent-500 bg-accent-500/10'
: willBeRemoved
? 'border-error-500/50 bg-error-500/5'
: 'border-dark-700/50 bg-dark-800/30 hover:border-dark-600'
} ${!country.is_available && !isCurrentlyConnected ? 'cursor-not-allowed opacity-50' : ''}`}
>
<div className="flex items-center gap-3">
<span className="text-lg">
{willBeAdded
? ''
return (
<button
key={country.uuid}
onClick={() => {
if (isSelected) {
setSelectedServersToUpdate((prev) =>
prev.filter((u) => u !== country.uuid),
);
} else {
setSelectedServersToUpdate((prev) => [...prev, country.uuid]);
}
}}
disabled={!country.is_available && !isCurrentlyConnected}
className={`flex w-full items-center justify-between rounded-xl border p-3 text-left transition-all ${
isSelected
? willBeAdded
? 'border-success-500 bg-success-500/10'
: 'border-accent-500 bg-accent-500/10'
: willBeRemoved
? ''
: isSelected
? ''
: '⚪'}
</span>
<div>
<div className="flex items-center gap-2 font-medium text-dark-100">
{country.name}
{country.has_discount && !isCurrentlyConnected && (
<span className="rounded bg-success-500/20 px-1.5 py-0.5 text-xs text-success-400">
-{country.discount_percent}%
</span>
? 'border-error-500/50 bg-error-500/5'
: 'border-dark-700/50 bg-dark-800/30 hover:border-dark-600'
} ${!country.is_available && !isCurrentlyConnected ? 'cursor-not-allowed opacity-50' : ''}`}
>
<div className="flex items-center gap-3">
<span className="text-lg">
{willBeAdded
? ''
: willBeRemoved
? ''
: isSelected
? '✅'
: '⚪'}
</span>
<div>
<div className="flex items-center gap-2 font-medium text-dark-100">
{country.name}
{country.has_discount && !isCurrentlyConnected && (
<span className="rounded bg-success-500/20 px-1.5 py-0.5 text-xs text-success-400">
-{country.discount_percent}%
</span>
)}
</div>
{willBeAdded && (
<div className="text-xs text-success-400">
+{formatPrice(country.price_kopeks)}{' '}
{t('subscription.serverManagement.forDays', {
days: countriesData.days_left,
})}
{country.has_discount && (
<span className="ml-1 text-dark-500 line-through">
{formatPrice(
Math.round(
(country.base_price_kopeks *
countriesData.days_left) /
30,
),
)}
</span>
)}
</div>
)}
{!willBeAdded && !isCurrentlyConnected && (
<div className="text-xs text-dark-500">
{formatPrice(country.price_per_month_kopeks)}
{t('subscription.serverManagement.perMonth')}
{country.has_discount && (
<span className="ml-1 text-dark-600 line-through">
{formatPrice(country.base_price_kopeks)}
</span>
)}
</div>
)}
{!country.is_available && !isCurrentlyConnected && (
<div className="text-xs text-dark-500">
{t('subscription.serverManagement.unavailable')}
</div>
)}
</div>
{willBeAdded && (
<div className="text-xs text-success-400">
+{formatPrice(country.price_kopeks)}{' '}
{t('subscription.serverManagement.forDays', {
days: countriesData.days_left,
})}
{country.has_discount && (
<span className="ml-1 text-dark-500 line-through">
{formatPrice(
Math.round(
(country.base_price_kopeks *
countriesData.days_left) /
30,
),
)}
</span>
)}
</div>
)}
{!willBeAdded && !isCurrentlyConnected && (
<div className="text-xs text-dark-500">
{formatPrice(country.price_per_month_kopeks)}
{t('subscription.serverManagement.perMonth')}
{country.has_discount && (
<span className="ml-1 text-dark-600 line-through">
{formatPrice(country.base_price_kopeks)}
</span>
)}
</div>
)}
{!country.is_available && !isCurrentlyConnected && (
<div className="text-xs text-dark-500">
{t('subscription.serverManagement.unavailable')}
</div>
)}
</div>
</div>
{country.country_code && (
<span className="text-xl">
{getFlagEmoji(country.country_code)}
</span>
)}
</button>
);
})}
{country.country_code && (
<span className="text-xl">
{getFlagEmoji(country.country_code)}
</span>
)}
</button>
);
})}
</div>
{(() => {
@@ -2002,10 +2012,10 @@ export default function Subscription() {
</div>
<div>
<div className="font-medium text-error-300">
{t('subscription.expired.title')}
{t('subscription.expiredBanner.title')}
</div>
<div className="mt-1 text-sm text-dark-400">
{t('subscription.expired.selectTariff')}
{t('subscription.expiredBanner.selectTariff')}
</div>
</div>
</div>
@@ -3109,7 +3119,14 @@ export default function Subscription() {
setSelectedTraffic(period.traffic.current);
}
if (period.servers.selected) {
setSelectedServers(period.servers.selected);
const availUuids = new Set(
period.servers.options
?.filter((s) => s.is_available)
.map((s) => s.uuid) ?? [],
);
setSelectedServers(
period.servers.selected.filter((uuid) => availUuids.has(uuid)),
);
}
if (period.devices.current) {
setSelectedDevices(period.devices.current);
@@ -3123,7 +3140,7 @@ export default function Subscription() {
>
{displayDiscount && displayDiscount > 0 && (
<div
className={`absolute -right-2 -top-2 rounded-full px-2 py-0.5 text-xs font-medium text-white ${
className={`absolute right-2 top-2 z-10 rounded-full px-2 py-0.5 text-xs font-medium text-white shadow-sm ${
hasExistingDiscount ? 'bg-success-500' : 'bg-orange-500'
}`}
>
@@ -3131,7 +3148,7 @@ export default function Subscription() {
</div>
)}
<div className="text-lg font-semibold text-dark-100">{period.label}</div>
<div className="flex items-center gap-2">
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1">
<span className="font-medium text-accent-400">
{formatPrice(promoPeriod.price)}
</span>
@@ -3170,20 +3187,41 @@ export default function Subscription() {
: ''
} ${!option.is_available ? 'cursor-not-allowed opacity-50' : ''}`}
>
{promoTraffic.percent && (
<div className="absolute -right-2 -top-2 rounded-full bg-orange-500 px-2 py-0.5 text-xs font-medium text-white">
-{promoTraffic.percent}%
</div>
)}
<div className="text-lg font-semibold text-dark-100">{option.label}</div>
<div className="flex items-center justify-center gap-2">
<span className="text-accent-400">{formatPrice(promoTraffic.price)}</span>
{promoTraffic.original && (
<span className="text-xs text-dark-500 line-through">
{formatPrice(promoTraffic.original)}
</span>
)}
</div>
{(() => {
const trafficDisplayDiscount = hasExistingDiscount
? option.discount_percent
: promoTraffic.percent;
const trafficDisplayOriginal = hasExistingDiscount
? option.original_price_kopeks
: promoTraffic.original;
return (
<>
{trafficDisplayDiscount && trafficDisplayDiscount > 0 && (
<div
className={`absolute right-2 top-2 z-10 rounded-full px-2 py-0.5 text-xs font-medium text-white shadow-sm ${
hasExistingDiscount ? 'bg-success-500' : 'bg-orange-500'
}`}
>
-{trafficDisplayDiscount}%
</div>
)}
<div className="text-lg font-semibold text-dark-100">
{option.label}
</div>
<div className="mt-1 flex flex-wrap items-center justify-center gap-x-2 gap-y-1">
<span className="text-accent-400">
{formatPrice(promoTraffic.price)}
</span>
{trafficDisplayOriginal &&
trafficDisplayOriginal > promoTraffic.price && (
<span className="text-xs text-dark-500 line-through">
{formatPrice(trafficDisplayOriginal)}
</span>
)}
</div>
</>
);
})()}
</button>
);
})}
@@ -3194,8 +3232,9 @@ export default function Subscription() {
{currentStep === 'servers' && selectedPeriod?.servers.options && (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
{selectedPeriod.servers.options
// Hide Trial server for users who already have trial subscription
// Hide unavailable (disabled) servers and trial servers for existing trial users
.filter((server) => {
if (!server.is_available) return false;
if (subscription?.is_trial && server.name.toLowerCase().includes('trial')) {
return false;
}
@@ -3223,11 +3262,20 @@ export default function Subscription() {
: 'cursor-not-allowed border-dark-800/30 bg-dark-900/30 opacity-50'
}`}
>
{promoServer.percent && (
<div className="absolute -right-2 -top-2 rounded-full bg-orange-500 px-2 py-0.5 text-xs font-medium text-white">
-{promoServer.percent}%
</div>
)}
{(() => {
const serverDisplayDiscount = hasExistingDiscount
? server.discount_percent
: promoServer.percent;
return serverDisplayDiscount && serverDisplayDiscount > 0 ? (
<div
className={`absolute right-2 top-2 z-10 rounded-full px-2 py-0.5 text-xs font-medium text-white shadow-sm ${
hasExistingDiscount ? 'bg-success-500' : 'bg-orange-500'
}`}
>
-{serverDisplayDiscount}%
</div>
) : null;
})()}
<div className="flex items-center gap-3">
<div
className={`flex h-5 w-5 flex-shrink-0 items-center justify-center rounded border-2 ${
@@ -3240,16 +3288,21 @@ export default function Subscription() {
</div>
<div>
<div className="font-medium text-dark-100">{server.name}</div>
<div className="flex items-center gap-2">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<span className="text-sm text-accent-400">
{formatPrice(promoServer.price)}
{t('subscription.perMonth')}
</span>
{promoServer.original && (
<span className="text-xs text-dark-500 line-through">
{formatPrice(promoServer.original)}
</span>
)}
{(() => {
const serverOriginal = hasExistingDiscount
? server.original_price_kopeks
: promoServer.original;
return serverOriginal && serverOriginal > promoServer.price ? (
<span className="text-xs text-dark-500 line-through">
{formatPrice(serverOriginal)}
</span>
) : null;
})()}
</div>
</div>
</div>