Merge pull request #258 from BEDOLAGA-DEV/dev

Dev
This commit is contained in:
Egor
2026-03-07 17:22:56 +03:00
committed by GitHub
16 changed files with 1404 additions and 348 deletions

View File

@@ -110,6 +110,7 @@ const AdminPolicyEdit = lazy(() => import('./pages/AdminPolicyEdit'));
const AdminAuditLog = lazy(() => import('./pages/AdminAuditLog'));
const AdminLandings = lazy(() => import('./pages/AdminLandings'));
const AdminLandingEditor = lazy(() => import('./pages/AdminLandingEditor'));
const AdminLandingStats = lazy(() => import('./pages/AdminLandingStats'));
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
@@ -542,6 +543,16 @@ function App() {
</PermissionRoute>
}
/>
<Route
path="/admin/landings/:id/stats"
element={
<PermissionRoute permission="landings:read">
<LazyPage>
<AdminLandingStats />
</LazyPage>
</PermissionRoute>
}
/>
<Route
path="/admin/servers"
element={

View File

@@ -69,7 +69,7 @@ const AUTH_ENDPOINTS = [
'/cabinet/auth/telegram',
'/cabinet/auth/telegram/widget',
'/cabinet/auth/email/login',
'/cabinet/auth/email/register',
'/cabinet/auth/email/register/standalone',
'/cabinet/auth/email/verify',
'/cabinet/auth/refresh',
'/cabinet/auth/password/forgot',

View File

@@ -1,4 +1,5 @@
import apiClient from './client';
import type { AnimationConfig } from '@/components/ui/backgrounds/types';
// ============================================================
// Public types
@@ -91,6 +92,7 @@ export interface LandingConfig {
meta_title: string | null;
meta_description: string | null;
discount: LandingDiscountInfo | null;
background_config: AnimationConfig | null;
}
export interface PurchaseRequest {
@@ -201,6 +203,7 @@ export interface LandingDetail {
discount_starts_at: string | null;
discount_ends_at: string | null;
discount_badge_text: LocaleDict | null;
background_config: AnimationConfig | null;
}
export interface LandingCreateRequest {
@@ -222,6 +225,7 @@ export interface LandingCreateRequest {
discount_starts_at?: string | null;
discount_ends_at?: string | null;
discount_badge_text?: LocaleDict | null;
background_config?: AnimationConfig | null;
}
export type LandingUpdateRequest = Partial<LandingCreateRequest>;
@@ -274,6 +278,72 @@ export const landingApi = {
},
};
// ============================================================
// Admin stats types
// ============================================================
export interface LandingDailyStat {
date: string;
purchases: number;
revenue_kopeks: number;
gifts: number;
}
export interface LandingTariffStat {
tariff_id: number | null;
tariff_name: string;
purchases: number;
revenue_kopeks: number;
}
export interface LandingStatsResponse {
total_purchases: number;
total_revenue_kopeks: number;
total_gifts: number;
total_regular: number;
avg_purchase_kopeks: number;
total_created: number;
total_successful: number;
conversion_rate: number;
daily_stats: LandingDailyStat[];
tariff_stats: LandingTariffStat[];
}
// ============================================================
// Admin purchase list types
// ============================================================
export type PurchaseItemStatus =
| 'pending'
| 'paid'
| 'delivered'
| 'pending_activation'
| 'failed'
| 'expired';
export interface LandingPurchaseItem {
id: number;
token: string;
contact_type: 'email' | 'telegram';
contact_value: string;
is_gift: boolean;
gift_recipient_type: 'email' | 'telegram' | null;
gift_recipient_value: string | null;
tariff_name: string;
period_days: number;
amount_kopeks: number;
currency: string;
payment_method: string;
status: PurchaseItemStatus;
created_at: string;
paid_at: string | null;
}
export interface LandingPurchaseListResponse {
items: LandingPurchaseItem[];
total: number;
}
// ============================================================
// Admin API
// ============================================================
@@ -312,4 +382,21 @@ export const adminLandingsApi = {
reorder: async (landingIds: number[]): Promise<void> => {
await apiClient.put('/cabinet/admin/landings/order', { landing_ids: landingIds });
},
getStats: async (id: number): Promise<LandingStatsResponse> => {
const response = await apiClient.get(`/cabinet/admin/landings/${id}/stats`);
return response.data;
},
getPurchases: async (
id: number,
offset: number,
limit: number,
status?: PurchaseItemStatus,
): Promise<LandingPurchaseListResponse> => {
const params: Record<string, string | number> = { offset, limit };
if (status) params.status = status;
const response = await apiClient.get(`/cabinet/admin/landings/${id}/purchases`, { params });
return response.data;
},
};

View File

@@ -106,6 +106,8 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
}, [isOIDC, widgetConfig?.oidc_client_id, widgetConfig?.request_access]);
// Legacy widget effect (only when NOT OIDC)
const loginWithTelegramWidget = useAuthStore((s) => s.loginWithTelegramWidget);
useEffect(() => {
if (isOIDC || !containerRef.current || !botUsername || !widgetConfig) return;
@@ -114,7 +116,25 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
container.removeChild(container.firstChild);
}
const redirectUrl = `${window.location.origin}/auth/telegram/callback`;
const callbackName = '__onTelegramWidgetAuth';
(window as unknown as Record<string, unknown>)[callbackName] = async (
user: Record<string, unknown>,
) => {
try {
await loginWithTelegramWidget({
id: user.id as number,
first_name: user.first_name as string,
last_name: (user.last_name as string) || undefined,
username: (user.username as string) || undefined,
photo_url: (user.photo_url as string) || undefined,
auth_date: user.auth_date as number,
hash: user.hash as string,
});
navigate('/');
} catch {
// Error handled by auth store
}
};
const script = document.createElement('script');
script.src = 'https://telegram.org/js/telegram-widget.js?23';
@@ -122,7 +142,7 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
script.setAttribute('data-size', widgetConfig.size);
script.setAttribute('data-radius', String(widgetConfig.radius));
script.setAttribute('data-userpic', String(widgetConfig.userpic));
script.setAttribute('data-auth-url', redirectUrl);
script.setAttribute('data-onauth', `${callbackName}(user)`);
if (widgetConfig.request_access) {
script.setAttribute('data-request-access', 'write');
}
@@ -131,11 +151,12 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
container.appendChild(script);
return () => {
delete (window as unknown as Record<string, unknown>)[callbackName];
while (container.firstChild) {
container.removeChild(container.firstChild);
}
};
}, [isOIDC, botUsername, widgetConfig]);
}, [isOIDC, botUsername, widgetConfig, loginWithTelegramWidget, navigate]);
if (!botUsername || botUsername === 'your_bot') {
return (

View File

@@ -0,0 +1,304 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { backgroundRegistry } from '@/components/ui/backgrounds/registry';
import { BackgroundPreview } from '@/components/backgrounds/BackgroundPreview';
import type {
AnimationConfig,
BackgroundType,
SettingDefinition,
} from '@/components/ui/backgrounds/types';
import { Toggle } from './Toggle';
import { cn } from '@/lib/utils';
function SettingField({
def,
value,
onChange,
t,
}: {
def: SettingDefinition;
value: unknown;
onChange: (val: unknown) => void;
t: (key: string) => string;
}) {
if (def.type === 'number') {
const numVal = (value as number) ?? (def.default as number);
const displayVal = numVal < 0.01 ? numVal.toExponential(1) : String(numVal);
return (
<div className="flex items-center justify-between gap-4">
<label className="text-sm text-dark-300">{t(def.label)}</label>
<div className="flex items-center gap-2">
<input
type="range"
min={def.min}
max={def.max}
step={def.step}
value={numVal}
onChange={(e) => onChange(parseFloat(e.target.value))}
className="w-24 accent-accent-500"
/>
<span className="w-16 text-right text-xs tabular-nums text-dark-400">{displayVal}</span>
</div>
</div>
);
}
if (def.type === 'color') {
const colorVal = (value as string) ?? (def.default as string);
const hexForInput = /^#[0-9a-fA-F]{3,8}$/.test(colorVal) ? colorVal : '#818cf8';
return (
<div className="flex items-center justify-between gap-4">
<label className="text-sm text-dark-300">{t(def.label)}</label>
<div className="flex items-center gap-2">
<input
type="color"
value={hexForInput}
onChange={(e) => onChange(e.target.value)}
className="h-7 w-10 cursor-pointer rounded border border-dark-600 bg-transparent"
/>
<span className="w-16 text-right text-xs text-dark-400">{colorVal}</span>
</div>
</div>
);
}
if (def.type === 'boolean') {
const boolVal = (value as boolean) ?? (def.default as boolean);
return (
<div className="flex items-center justify-between gap-4">
<label className="text-sm text-dark-300">{t(def.label)}</label>
<Toggle checked={boolVal} onChange={() => onChange(!boolVal)} />
</div>
);
}
if (def.type === 'select' && def.options) {
const selectVal = (value as string) ?? (def.default as string);
return (
<div className="flex items-center justify-between gap-4">
<label className="text-sm text-dark-300">{t(def.label)}</label>
<select
value={selectVal}
onChange={(e) => onChange(e.target.value)}
className="rounded-lg border border-dark-600 bg-dark-700 px-3 py-1.5 text-sm text-dark-200 focus:border-accent-500 focus:outline-none"
>
{def.options.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label.startsWith('admin.') ? t(opt.label) : opt.label}
</option>
))}
</select>
</div>
);
}
return null;
}
interface BackgroundConfigEditorProps {
value: AnimationConfig;
onChange: (config: AnimationConfig) => void;
}
export function BackgroundConfigEditor({ value: config, onChange }: BackgroundConfigEditorProps) {
const { t } = useTranslation();
const updateConfig = (patch: Partial<AnimationConfig>) => {
onChange({ ...config, ...patch });
};
const updateSetting = (key: string, val: unknown) => {
onChange({ ...config, settings: { ...config.settings, [key]: val } });
};
const handleTypeChange = (type: BackgroundType) => {
const def = backgroundRegistry.find((d) => d.type === type);
const defaults: Record<string, unknown> = {};
if (def) {
for (const s of def.settings) {
defaults[s.key] = s.default;
}
}
onChange({ ...config, type, settings: defaults });
};
const currentDef = useMemo(
() => backgroundRegistry.find((d) => d.type === config.type),
[config.type],
);
const categories = useMemo(() => {
const cats = new Map<string, typeof backgroundRegistry>();
for (const def of backgroundRegistry) {
const list = cats.get(def.category) ?? [];
list.push(def);
cats.set(def.category, list);
}
return cats;
}, []);
return (
<div className="space-y-6">
{/* Header with enable toggle */}
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-semibold text-dark-100">{t('admin.backgrounds.title')}</h3>
<p className="text-sm text-dark-400">{t('admin.backgrounds.description')}</p>
</div>
<Toggle
checked={config.enabled}
onChange={() => updateConfig({ enabled: !config.enabled })}
/>
</div>
{config.enabled && (
<>
{/* Preview */}
<div>
<label className="mb-2 block text-sm font-medium text-dark-300">
{t('admin.backgrounds.preview')}
</label>
<BackgroundPreview
type={config.type}
settings={config.settings}
opacity={config.opacity}
blur={config.blur}
className="h-48"
/>
</div>
{/* Type selector gallery */}
<div>
<label className="mb-2 block text-sm font-medium text-dark-300">
{t('admin.backgrounds.selectType')}
</label>
{/* None option */}
<button
onClick={() => handleTypeChange('none')}
className={cn(
'mb-3 w-full rounded-xl border p-3 text-left transition-colors',
config.type === 'none'
? 'border-accent-500 bg-accent-500/10'
: 'border-dark-700/50 bg-dark-800/30 hover:border-dark-600',
)}
>
<span className="text-sm font-medium text-dark-200">
{t('admin.backgrounds.none')}
</span>
<span className="ml-2 text-xs text-dark-400">{t('admin.backgrounds.noneDesc')}</span>
</button>
{/* Background types by category */}
<div className="space-y-4">
{Array.from(categories.entries()).map(([category, defs]) => (
<div key={category}>
<span className="mb-2 block text-xs font-medium uppercase tracking-wider text-dark-500">
{t(`admin.backgrounds.category${category.toUpperCase()}`)}
</span>
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
{defs.map((def) => (
<button
key={def.type}
onClick={() => handleTypeChange(def.type)}
className={cn(
'rounded-xl border p-3 text-left transition-colors',
config.type === def.type
? 'border-accent-500 bg-accent-500/10'
: 'border-dark-700/50 bg-dark-800/30 hover:border-dark-600',
)}
>
<span className="block text-sm font-medium text-dark-200">
{t(def.labelKey)}
</span>
<span className="block text-xs text-dark-400">{t(def.descriptionKey)}</span>
</button>
))}
</div>
</div>
))}
</div>
</div>
{/* Per-type settings */}
{currentDef && currentDef.settings.length > 0 && (
<div className="rounded-xl border border-dark-700/50 bg-dark-800/30 p-4">
<h4 className="mb-3 text-sm font-medium text-dark-200">
{t('admin.backgrounds.settings')}
</h4>
<div className="space-y-3">
{currentDef.settings.map((def) => (
<SettingField
key={def.key}
def={def}
value={config.settings[def.key]}
onChange={(val) => updateSetting(def.key, val)}
t={t}
/>
))}
</div>
</div>
)}
{/* Global settings */}
<div className="rounded-xl border border-dark-700/50 bg-dark-800/30 p-4">
<div className="space-y-3">
<div className="flex items-center justify-between gap-4">
<label className="text-sm text-dark-300">
{t('admin.backgrounds.globalOpacity')}
</label>
<div className="flex items-center gap-2">
<input
type="range"
min={0.1}
max={1}
step={0.05}
value={config.opacity}
onChange={(e) => updateConfig({ opacity: parseFloat(e.target.value) })}
className="w-24 accent-accent-500"
/>
<span className="w-14 text-right text-xs tabular-nums text-dark-400">
{config.opacity}
</span>
</div>
</div>
<div className="flex items-center justify-between gap-4">
<label className="text-sm text-dark-300">{t('admin.backgrounds.globalBlur')}</label>
<div className="flex items-center gap-2">
<input
type="range"
min={0}
max={20}
step={1}
value={config.blur}
onChange={(e) => updateConfig({ blur: Number(e.target.value) })}
className="w-24 accent-accent-500"
/>
<span className="w-14 text-right text-xs tabular-nums text-dark-400">
{config.blur}px
</span>
</div>
</div>
<div className="flex items-center justify-between gap-4">
<div>
<label className="text-sm text-dark-300">
{t('admin.backgrounds.reducedOnMobile')}
</label>
<p className="text-xs text-dark-500">
{t('admin.backgrounds.reducedOnMobileDesc')}
</p>
</div>
<Toggle
checked={config.reducedOnMobile}
onChange={() => updateConfig({ reducedOnMobile: !config.reducedOnMobile })}
/>
</div>
</div>
</div>
</>
)}
</div>
);
}

View File

@@ -1,111 +1,18 @@
import { useState, useCallback, useMemo, useRef, useEffect } from 'react';
import { useState, useCallback, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { brandingApi } from '@/api/branding';
import { backgroundRegistry } from '@/components/ui/backgrounds/registry';
import { BackgroundPreview } from '@/components/backgrounds/BackgroundPreview';
import { setCachedAnimationConfig } from '@/components/backgrounds/BackgroundRenderer';
import type {
AnimationConfig,
BackgroundType,
SettingDefinition,
} from '@/components/ui/backgrounds/types';
import type { AnimationConfig } from '@/components/ui/backgrounds/types';
import { DEFAULT_ANIMATION_CONFIG } from '@/components/ui/backgrounds/types';
import { Toggle } from './Toggle';
import { BackgroundConfigEditor } from './BackgroundConfigEditor';
import { cn } from '@/lib/utils';
function SettingField({
def,
value,
onChange,
t,
}: {
def: SettingDefinition;
value: unknown;
onChange: (val: unknown) => void;
t: (key: string) => string;
}) {
if (def.type === 'number') {
const numVal = (value as number) ?? (def.default as number);
const displayVal = numVal < 0.01 ? numVal.toExponential(1) : String(numVal);
return (
<div className="flex items-center justify-between gap-4">
<label className="text-sm text-dark-300">{t(def.label)}</label>
<div className="flex items-center gap-2">
<input
type="range"
min={def.min}
max={def.max}
step={def.step}
value={numVal}
onChange={(e) => onChange(parseFloat(e.target.value))}
className="w-24 accent-accent-500"
/>
<span className="w-16 text-right text-xs tabular-nums text-dark-400">{displayVal}</span>
</div>
</div>
);
}
if (def.type === 'color') {
const colorVal = (value as string) ?? (def.default as string);
// HTML color input only supports hex — for rgba defaults, show a neutral hex
const hexForInput = /^#[0-9a-fA-F]{3,8}$/.test(colorVal) ? colorVal : '#818cf8';
return (
<div className="flex items-center justify-between gap-4">
<label className="text-sm text-dark-300">{t(def.label)}</label>
<div className="flex items-center gap-2">
<input
type="color"
value={hexForInput}
onChange={(e) => onChange(e.target.value)}
className="h-7 w-10 cursor-pointer rounded border border-dark-600 bg-transparent"
/>
<span className="w-16 text-right text-xs text-dark-400">{colorVal}</span>
</div>
</div>
);
}
if (def.type === 'boolean') {
const boolVal = (value as boolean) ?? (def.default as boolean);
return (
<div className="flex items-center justify-between gap-4">
<label className="text-sm text-dark-300">{t(def.label)}</label>
<Toggle checked={boolVal} onChange={() => onChange(!boolVal)} />
</div>
);
}
if (def.type === 'select' && def.options) {
const selectVal = (value as string) ?? (def.default as string);
return (
<div className="flex items-center justify-between gap-4">
<label className="text-sm text-dark-300">{t(def.label)}</label>
<select
value={selectVal}
onChange={(e) => onChange(e.target.value)}
className="rounded-lg border border-dark-600 bg-dark-700 px-3 py-1.5 text-sm text-dark-200 focus:border-accent-500 focus:outline-none"
>
{def.options.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label.startsWith('admin.') ? t(opt.label) : opt.label}
</option>
))}
</select>
</div>
);
}
return null;
}
export function BackgroundEditor() {
const { t } = useTranslation();
const queryClient = useQueryClient();
const saveTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
// Clear save timer on unmount
useEffect(() => {
return () => {
if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
@@ -137,40 +44,9 @@ export function BackgroundEditor() {
onError: () => setSaveStatus('idle'),
});
const updateConfig = useCallback(
(patch: Partial<AnimationConfig>) => {
setLocalConfig((prev) => ({
...(prev ?? serverConfig ?? DEFAULT_ANIMATION_CONFIG),
...patch,
}));
},
[serverConfig],
);
// Use functional updater to avoid stale closure when rapidly changing settings
const updateSetting = useCallback(
(key: string, value: unknown) => {
setLocalConfig((prev) => {
const base = prev ?? serverConfig ?? DEFAULT_ANIMATION_CONFIG;
return { ...base, settings: { ...base.settings, [key]: value } };
});
},
[serverConfig],
);
const handleTypeChange = useCallback(
(type: BackgroundType) => {
const def = backgroundRegistry.find((d) => d.type === type);
const defaults: Record<string, unknown> = {};
if (def) {
for (const s of def.settings) {
defaults[s.key] = s.default;
}
}
updateConfig({ type, settings: defaults });
},
[updateConfig],
);
const handleChange = useCallback((newConfig: AnimationConfig) => {
setLocalConfig(newConfig);
}, []);
const handleSave = () => {
saveMutation.mutate(config);
@@ -179,183 +55,9 @@ export function BackgroundEditor() {
const isDirty = localConfig !== null;
const showSaveButton = isDirty || saveStatus === 'saved' || saveStatus === 'saving';
const currentDef = useMemo(
() => backgroundRegistry.find((d) => d.type === config.type),
[config.type],
);
const categories = useMemo(() => {
const cats = new Map<string, typeof backgroundRegistry>();
for (const def of backgroundRegistry) {
const list = cats.get(def.category) ?? [];
list.push(def);
cats.set(def.category, list);
}
return cats;
}, []);
return (
<div className="space-y-6">
{/* Header with enable toggle */}
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-semibold text-dark-100">{t('admin.backgrounds.title')}</h3>
<p className="text-sm text-dark-400">{t('admin.backgrounds.description')}</p>
</div>
<Toggle
checked={config.enabled}
onChange={() => updateConfig({ enabled: !config.enabled })}
/>
</div>
{config.enabled && (
<>
{/* Preview */}
<div>
<label className="mb-2 block text-sm font-medium text-dark-300">
{t('admin.backgrounds.preview')}
</label>
<BackgroundPreview
type={config.type}
settings={config.settings}
opacity={config.opacity}
blur={config.blur}
className="h-48"
/>
</div>
{/* Type selector gallery */}
<div>
<label className="mb-2 block text-sm font-medium text-dark-300">
{t('admin.backgrounds.selectType')}
</label>
{/* None option */}
<button
onClick={() => handleTypeChange('none')}
className={cn(
'mb-3 w-full rounded-xl border p-3 text-left transition-colors',
config.type === 'none'
? 'border-accent-500 bg-accent-500/10'
: 'border-dark-700/50 bg-dark-800/30 hover:border-dark-600',
)}
>
<span className="text-sm font-medium text-dark-200">
{t('admin.backgrounds.none')}
</span>
<span className="ml-2 text-xs text-dark-400">{t('admin.backgrounds.noneDesc')}</span>
</button>
{/* Background types by category */}
<div className="space-y-4">
{Array.from(categories.entries()).map(([category, defs]) => (
<div key={category}>
<span className="mb-2 block text-xs font-medium uppercase tracking-wider text-dark-500">
{t(`admin.backgrounds.category${category.toUpperCase()}`)}
</span>
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
{defs.map((def) => (
<button
key={def.type}
onClick={() => handleTypeChange(def.type)}
className={cn(
'rounded-xl border p-3 text-left transition-colors',
config.type === def.type
? 'border-accent-500 bg-accent-500/10'
: 'border-dark-700/50 bg-dark-800/30 hover:border-dark-600',
)}
>
<span className="block text-sm font-medium text-dark-200">
{t(def.labelKey)}
</span>
<span className="block text-xs text-dark-400">{t(def.descriptionKey)}</span>
</button>
))}
</div>
</div>
))}
</div>
</div>
{/* Per-type settings */}
{currentDef && currentDef.settings.length > 0 && (
<div className="rounded-xl border border-dark-700/50 bg-dark-800/30 p-4">
<h4 className="mb-3 text-sm font-medium text-dark-200">
{t('admin.backgrounds.settings')}
</h4>
<div className="space-y-3">
{currentDef.settings.map((def) => (
<SettingField
key={def.key}
def={def}
value={config.settings[def.key]}
onChange={(val) => updateSetting(def.key, val)}
t={t}
/>
))}
</div>
</div>
)}
{/* Global settings */}
<div className="rounded-xl border border-dark-700/50 bg-dark-800/30 p-4">
<div className="space-y-3">
<div className="flex items-center justify-between gap-4">
<label className="text-sm text-dark-300">
{t('admin.backgrounds.globalOpacity')}
</label>
<div className="flex items-center gap-2">
<input
type="range"
min={0.1}
max={1}
step={0.05}
value={config.opacity}
onChange={(e) => updateConfig({ opacity: parseFloat(e.target.value) })}
className="w-24 accent-accent-500"
/>
<span className="w-14 text-right text-xs tabular-nums text-dark-400">
{config.opacity}
</span>
</div>
</div>
<div className="flex items-center justify-between gap-4">
<label className="text-sm text-dark-300">{t('admin.backgrounds.globalBlur')}</label>
<div className="flex items-center gap-2">
<input
type="range"
min={0}
max={20}
step={1}
value={config.blur}
onChange={(e) => updateConfig({ blur: parseInt(e.target.value) })}
className="w-24 accent-accent-500"
/>
<span className="w-14 text-right text-xs tabular-nums text-dark-400">
{config.blur}px
</span>
</div>
</div>
<div className="flex items-center justify-between gap-4">
<div>
<label className="text-sm text-dark-300">
{t('admin.backgrounds.reducedOnMobile')}
</label>
<p className="text-xs text-dark-500">
{t('admin.backgrounds.reducedOnMobileDesc')}
</p>
</div>
<Toggle
checked={config.reducedOnMobile}
onChange={() => updateConfig({ reducedOnMobile: !config.reducedOnMobile })}
/>
</div>
</div>
</div>
</>
)}
<BackgroundConfigEditor value={config} onChange={handleChange} />
{/* Save button */}
{showSaveButton && (

View File

@@ -96,52 +96,35 @@ function reduceMobileSettings(settings: Record<string, unknown>): Record<string,
return reduced;
}
export function BackgroundRenderer() {
/** Renders the background animation into a portal at document.body */
function RenderBackground({ config }: { config: AnimationConfig }) {
const prefersReducedMotion = useMemo(
() => window.matchMedia('(prefers-reduced-motion: reduce)').matches,
[],
);
const { data: config } = useQuery({
queryKey: ['animation-config'],
queryFn: async () => {
const raw = await brandingApi.getAnimationConfig();
// Validate and clamp API response same as localStorage
const result = validateConfig(raw) ?? DEFAULT_ANIMATION_CONFIG;
setCachedConfig(result);
return result;
},
initialData: getCachedConfig() ?? undefined,
initialDataUpdatedAt: 0,
staleTime: 30_000,
});
const effectiveConfig = config ?? DEFAULT_ANIMATION_CONFIG;
if (!effectiveConfig.enabled || effectiveConfig.type === 'none' || prefersReducedMotion) {
if (!config.enabled || config.type === 'none' || prefersReducedMotion) {
return null;
}
const bgType = effectiveConfig.type as Exclude<BackgroundType, 'none'>;
const bgType = config.type as Exclude<BackgroundType, 'none'>;
const Component = backgroundComponents[bgType];
if (!Component) return null;
const isMobile = window.innerWidth < 768;
const settings =
effectiveConfig.reducedOnMobile && isMobile
? reduceMobileSettings(effectiveConfig.settings)
: effectiveConfig.settings;
config.reducedOnMobile && isMobile ? reduceMobileSettings(config.settings) : config.settings;
// On mobile, cap blur to 4px max — full blur is extremely GPU-heavy
const effectiveBlur = isMobile ? Math.min(effectiveConfig.blur, 4) : effectiveConfig.blur;
const effectiveBlur = isMobile ? Math.min(config.blur, 4) : config.blur;
return createPortal(
<div
className="pointer-events-none fixed inset-0"
style={{
zIndex: -2,
opacity: effectiveConfig.opacity,
opacity: config.opacity,
filter: effectiveBlur > 0 ? `blur(${effectiveBlur}px)` : undefined,
contain: 'strict',
backfaceVisibility: 'hidden',
@@ -154,3 +137,29 @@ export function BackgroundRenderer() {
document.body,
);
}
/** BackgroundRenderer that fetches config from the branding API (for authenticated app shell) */
export function BackgroundRenderer() {
const { data: config } = useQuery({
queryKey: ['animation-config'],
queryFn: async () => {
const raw = await brandingApi.getAnimationConfig();
const result = validateConfig(raw) ?? DEFAULT_ANIMATION_CONFIG;
setCachedConfig(result);
return result;
},
initialData: getCachedConfig() ?? undefined,
initialDataUpdatedAt: 0,
staleTime: 30_000,
});
const effectiveConfig = config ?? DEFAULT_ANIMATION_CONFIG;
return <RenderBackground config={effectiveConfig} />;
}
/** StaticBackgroundRenderer that uses a provided config (for public landing pages) */
export function StaticBackgroundRenderer({ config }: { config: AnimationConfig }) {
const validated = useMemo(() => validateConfig(config), [config]);
if (!validated) return null;
return <RenderBackground config={validated} />;
}

View File

@@ -3192,7 +3192,7 @@
"metaDesc": "Meta Description",
"active": "Active",
"inactive": "Inactive",
"purchases": "purchases",
"purchaseCount": "purchases",
"copyUrl": "Copy URL",
"urlCopied": "URL copied",
"deleteConfirm": "Delete landing \"{{title}}\"?",
@@ -3227,7 +3227,54 @@
"discountOverrides": "Per-tariff overrides",
"discountOverridesHint": "Leave empty to use global discount",
"discountPreview": "Preview",
"discountActive": "Discount"
"discountActive": "Discount",
"statistics": "Statistics",
"stats": {
"title": "Landing Statistics",
"totalPurchases": "Purchases",
"revenue": "Revenue",
"giftPurchases": "Gifts",
"regularPurchases": "Regular",
"conversionRate": "Conversion",
"avgPurchase": "Avg. Check",
"dailyChart": "Purchases & Revenue by Day",
"tariffChart": "Tariff Distribution",
"giftBreakdown": "Gifts vs Regular",
"purchases": "Purchases",
"revenueLabel": "Revenue",
"gifts": "Gifts",
"regular": "Regular",
"created": "Created",
"successful": "Successful",
"funnel": "Funnel",
"loadError": "Failed to load statistics",
"noPurchases": "No purchases"
},
"purchases": {
"title": "Purchases",
"contact": "Contact",
"recipient": "Recipient",
"tariff": "Tariff",
"period": "Period",
"days": "days",
"price": "Price",
"method": "Method",
"date": "Date",
"gift": "Gift",
"forSelf": "For self",
"allStatuses": "All statuses",
"status_pending": "Pending",
"status_paid": "Paid",
"status_delivered": "Delivered",
"status_pending_activation": "Pending activation",
"status_failed": "Failed",
"status_expired": "Expired",
"noPurchases": "No purchases",
"showing": "Showing {{from}}\u2013{{to}} of {{total}}",
"page": "Page {{current}} of {{total}}",
"prev": "Previous",
"next": "Next"
}
}
},
"adminUpdates": {

View File

@@ -2917,7 +2917,7 @@
"metaDesc": "توضیحات متا",
"active": "فعال",
"inactive": "غیرفعال",
"purchases": "خرید",
"purchaseCount": "خرید",
"copyUrl": "کپی URL",
"urlCopied": "URL کپی شد",
"deleteConfirm": "حذف صفحه فرود «{{title}}»؟",

View File

@@ -3743,7 +3743,7 @@
"metaDesc": "Meta Description",
"active": "Активен",
"inactive": "Неактивен",
"purchases": "покупок",
"purchaseCount": "покупок",
"copyUrl": "Скопировать URL",
"urlCopied": "URL скопирован",
"deleteConfirm": "Удалить лендинг «{{title}}»?",
@@ -3778,7 +3778,55 @@
"discountOverrides": "Индивидуальные скидки по тарифам",
"discountOverridesHint": "Оставьте пустым для использования общей скидки",
"discountPreview": "Предпросмотр",
"discountActive": "Скидка"
"discountActive": "Скидка",
"background": "Анимированный фон",
"statistics": "Статистика",
"stats": {
"title": "Статистика лендинга",
"totalPurchases": "Покупки",
"revenue": "Доход",
"giftPurchases": "Подарки",
"regularPurchases": "Обычные",
"conversionRate": "Конверсия",
"avgPurchase": "Средний чек",
"dailyChart": "Покупки и доход по дням",
"tariffChart": "Распределение по тарифам",
"giftBreakdown": "Подарки vs обычные",
"purchases": "Покупки",
"revenueLabel": "Доход",
"gifts": "Подарки",
"regular": "Обычные",
"created": "Создано",
"successful": "Успешных",
"funnel": "Воронка",
"loadError": "Не удалось загрузить статистику",
"noPurchases": "Нет покупок"
},
"purchases": {
"title": "Покупки",
"contact": "Контакт",
"recipient": "Получатель",
"tariff": "Тариф",
"period": "Период",
"days": "дн.",
"price": "Цена",
"method": "Метод",
"date": "Дата",
"gift": "Подарок",
"forSelf": "Для себя",
"allStatuses": "Все статусы",
"status_pending": "Ожидание",
"status_paid": "Оплачен",
"status_delivered": "Доставлен",
"status_pending_activation": "Ожидает активации",
"status_failed": "Ошибка",
"status_expired": "Истёк",
"noPurchases": "Нет покупок",
"showing": "Показано {{from}}\u2013{{to}} из {{total}}",
"page": "Стр. {{current}} из {{total}}",
"prev": "Назад",
"next": "Далее"
}
}
},
"adminUpdates": {

View File

@@ -2916,7 +2916,7 @@
"metaDesc": "Meta描述",
"active": "已激活",
"inactive": "未激活",
"purchases": "次购买",
"purchaseCount": "次购买",
"copyUrl": "复制URL",
"urlCopied": "URL已复制",
"deleteConfirm": "删除落地页「{{title}}」?",

View File

@@ -15,6 +15,9 @@ import { tariffsApi, TariffListItem, PeriodPrice } from '../api/tariffs';
import { formatPrice } from '../utils/format';
import { adminPaymentMethodsApi } from '../api/adminPaymentMethods';
import { Toggle, LocaleTabs, LocalizedInput } from '../components/admin';
import { BackgroundConfigEditor } from '../components/admin/BackgroundConfigEditor';
import type { AnimationConfig } from '@/components/ui/backgrounds/types';
import { DEFAULT_ANIMATION_CONFIG } from '@/components/ui/backgrounds/types';
import { SortableFeatureItem, type FeatureWithId } from '../components/admin/SortableFeatureItem';
import {
SortableSelectedMethodCard,
@@ -102,6 +105,7 @@ export default function AdminLandingEditor() {
discount: false,
methods: false,
gifts: false,
background: false,
footer: false,
});
@@ -127,6 +131,12 @@ export default function AdminLandingEditor() {
const [footerText, setFooterText] = useState<LocaleDict>({});
const [customCss, setCustomCss] = useState('');
// Background config state
const [backgroundConfig, setBackgroundConfig] = useState<AnimationConfig>({
...DEFAULT_ANIMATION_CONFIG,
enabled: false,
});
// Discount state
const [discountPercent, setDiscountPercent] = useState<number | null>(null);
const [discountOverrides, setDiscountOverrides] = useState<Record<string, number>>({});
@@ -245,6 +255,9 @@ export default function AdminLandingEditor() {
setGiftEnabled(landingData.gift_enabled);
setFooterText(toLocaleDict(landingData.footer_text));
setCustomCss(landingData.custom_css ?? '');
if (landingData.background_config) {
setBackgroundConfig(landingData.background_config);
}
setDiscountPercent(landingData.discount_percent ?? null);
setDiscountOverrides(landingData.discount_overrides ?? {});
setDiscountStartsAt(
@@ -364,6 +377,7 @@ export default function AdminLandingEditor() {
discountPercent !== null && discountEndsAt ? new Date(discountEndsAt).toISOString() : null,
discount_badge_text:
discountPercent !== null ? (nonEmptyDict(discountBadgeText) ?? null) : null,
background_config: backgroundConfig.enabled ? backgroundConfig : null,
};
if (isEdit) {
@@ -1056,6 +1070,15 @@ export default function AdminLandingEditor() {
</div>
</Section>
{/* Background Section */}
<Section
title={t('admin.landings.background', 'Background')}
open={openSections.background}
onToggle={() => toggleSection('background')}
>
<BackgroundConfigEditor value={backgroundConfig} onChange={setBackgroundConfig} />
</Section>
{/* Footer & Custom CSS Section */}
<Section
title={t('admin.landings.content')}

View File

@@ -0,0 +1,747 @@
import { useState, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import {
Area,
AreaChart,
Bar,
BarChart,
CartesianGrid,
Cell,
Pie,
PieChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
import {
adminLandingsApi,
resolveLocaleDisplay,
type PurchaseItemStatus,
type LandingPurchaseItem,
} from '../api/landings';
import { useCurrency } from '../hooks/useCurrency';
import { useChartColors } from '../hooks/useChartColors';
import { CHART_COMMON } from '../constants/charts';
import { AdminBackButton } from '../components/admin';
// Icons
const ChartIcon = () => (
<svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z"
/>
</svg>
);
const TARIFF_PALETTE = ['#818cf8', '#34d399', '#f59e0b', '#ec4899', '#06b6d4', '#8b5cf6'];
const GIFT_COLOR = '#a855f7';
const PURCHASE_STATUS_STYLES: Record<string, string> = {
pending: 'bg-warning-500/20 text-warning-400',
paid: 'bg-accent-500/20 text-accent-400',
delivered: 'bg-success-500/20 text-success-400',
pending_activation: 'bg-accent-500/20 text-accent-400',
failed: 'bg-error-500/20 text-error-400',
expired: 'bg-dark-500/20 text-dark-400',
};
const PURCHASE_STATUS_OPTIONS: Array<PurchaseItemStatus | 'all'> = [
'all',
'pending',
'paid',
'delivered',
'pending_activation',
'failed',
'expired',
];
const PURCHASES_PAGE_SIZE = 20;
// Small icons for the purchase cards
const EmailIcon = () => (
<svg
className="h-3.5 w-3.5 shrink-0"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={1.5}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"
/>
</svg>
);
const TelegramSmallIcon = () => (
<svg className="h-3.5 w-3.5 shrink-0" 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>
);
const ArrowRightIcon = () => (
<svg
className="h-3 w-3 shrink-0 text-dark-500"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
>
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" />
</svg>
);
const GiftIcon = () => (
<svg
className="h-3.5 w-3.5 shrink-0"
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>
);
const ChevronLeftSmall = () => (
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
);
const ChevronRightSmall = () => (
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
</svg>
);
// Contact display helper
function ContactDisplay({ type, value }: { type: 'email' | 'telegram'; value: string }) {
return (
<span className="flex items-center gap-1 text-dark-300">
{type === 'email' ? <EmailIcon /> : <TelegramSmallIcon />}
<span className="min-w-0 truncate text-xs">{value}</span>
</span>
);
}
// Purchase card component
interface PurchaseCardProps {
item: LandingPurchaseItem;
formatPrice: (kopeks: number) => string;
lang: string;
t: (key: string, opts?: Record<string, unknown>) => string;
}
function PurchaseCard({ item, formatPrice, lang, t }: PurchaseCardProps) {
const statusStyle = PURCHASE_STATUS_STYLES[item.status] || 'bg-dark-600 text-dark-300';
const dateStr = new Date(item.created_at).toLocaleDateString(lang, {
day: 'numeric',
month: 'short',
year: 'numeric',
});
return (
<div className="rounded-xl border border-dark-700/50 bg-dark-800/40 p-3 transition-colors hover:border-dark-600 sm:p-4">
{/* Mobile: stacked | Desktop: horizontal */}
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-4">
{/* Status badge */}
<div className="shrink-0">
<span
className={`inline-flex items-center rounded-md px-2 py-0.5 text-xs font-medium ${statusStyle}`}
>
{t(`admin.landings.purchases.status_${item.status}`)}
</span>
</div>
{/* Contact info */}
<div className="min-w-0 flex-1">
<div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-3">
<ContactDisplay type={item.contact_type} value={item.contact_value} />
{item.is_gift && item.gift_recipient_type && item.gift_recipient_value && (
<span className="flex items-center gap-1">
<ArrowRightIcon />
<ContactDisplay type={item.gift_recipient_type} value={item.gift_recipient_value} />
</span>
)}
</div>
</div>
{/* Tariff + period */}
<div className="shrink-0 text-sm text-dark-200">
<span className="font-medium">{item.tariff_name}</span>
<span className="text-dark-500">
{' '}
&middot; {item.period_days} {t('admin.landings.purchases.days')}
</span>
</div>
{/* Price */}
<div className="shrink-0 text-sm font-medium text-dark-100">
{formatPrice(item.amount_kopeks)}
</div>
{/* Payment method */}
<div className="shrink-0 text-xs text-dark-500">{item.payment_method}</div>
{/* Gift badge */}
{item.is_gift && (
<div className="shrink-0">
<span className="inline-flex items-center gap-1 rounded-md bg-purple-500/20 px-1.5 py-0.5 text-xs text-purple-400">
<GiftIcon />
{t('admin.landings.purchases.gift')}
</span>
</div>
)}
{/* Date */}
<div className="shrink-0 text-xs text-dark-500">{dateStr}</div>
</div>
</div>
);
}
export default function AdminLandingStats() {
const { t, i18n } = useTranslation();
const { id } = useParams<{ id: string }>();
const numericId = id ? Number(id) : NaN;
const isValidId = !isNaN(numericId);
const navigate = useNavigate();
const { formatWithCurrency } = useCurrency();
const colors = useChartColors();
// Purchases list state
const [purchaseOffset, setPurchaseOffset] = useState(0);
const [purchaseStatusFilter, setPurchaseStatusFilter] = useState<PurchaseItemStatus | 'all'>(
'all',
);
// Fetch stats
const {
data: stats,
isLoading,
error,
} = useQuery({
queryKey: ['landing-stats', numericId],
queryFn: () => adminLandingsApi.getStats(numericId),
enabled: isValidId,
staleTime: CHART_COMMON.STALE_TIME,
});
// Fetch landing detail for header
const { data: landing } = useQuery({
queryKey: ['admin-landing', numericId],
queryFn: () => adminLandingsApi.get(numericId),
enabled: isValidId,
staleTime: CHART_COMMON.STALE_TIME,
});
// Fetch purchases list
const { data: purchasesData, isLoading: purchasesLoading } = useQuery({
queryKey: [
'landing-purchases',
numericId,
purchaseOffset,
PURCHASES_PAGE_SIZE,
purchaseStatusFilter,
],
queryFn: () =>
adminLandingsApi.getPurchases(
numericId,
purchaseOffset,
PURCHASES_PAGE_SIZE,
purchaseStatusFilter === 'all' ? undefined : purchaseStatusFilter,
),
enabled: isValidId,
staleTime: CHART_COMMON.STALE_TIME,
});
const purchaseItems = purchasesData?.items ?? [];
const purchaseTotal = purchasesData?.total ?? 0;
const purchaseTotalPages = Math.ceil(purchaseTotal / PURCHASES_PAGE_SIZE);
const purchaseCurrentPage = Math.floor(purchaseOffset / PURCHASES_PAGE_SIZE) + 1;
// Prepare daily chart data
const dailyData = useMemo(() => {
if (!stats) return [];
return stats.daily_stats.map((item) => ({
label: new Date(item.date + 'T00:00:00').toLocaleDateString(i18n.language, {
month: 'short',
day: 'numeric',
}),
purchases: item.purchases,
revenue: item.revenue_kopeks / CHART_COMMON.KOPEKS_DIVISOR,
gifts: item.gifts,
}));
}, [stats, i18n.language]);
// Prepare tariff chart data
const tariffData = useMemo(() => {
if (!stats) return [];
return stats.tariff_stats.map((item) => ({
name: item.tariff_name,
purchases: item.purchases,
revenue: item.revenue_kopeks / CHART_COMMON.KOPEKS_DIVISOR,
}));
}, [stats]);
// Donut data for gift vs regular
const donutData = useMemo(() => {
if (!stats) return [];
return [
{
name: t('admin.landings.stats.regular'),
value: stats.total_regular,
color: colors.referrals,
},
{ name: t('admin.landings.stats.gifts'), value: stats.total_gifts, color: GIFT_COLOR },
];
}, [stats, t, colors.referrals]);
// Bar chart height based on tariff count
const barChartHeight = useMemo(() => {
const count = tariffData.length;
return Math.max(220, count * 45 + 40);
}, [tariffData.length]);
// Loading state
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<div className="h-8 w-8 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
</div>
);
}
// Error state
if (error || !stats) {
return (
<div className="animate-fade-in">
<div className="mb-6 flex items-center gap-3">
<AdminBackButton to="/admin/landings" />
<h1 className="text-xl font-semibold text-dark-100">{t('admin.landings.stats.title')}</h1>
</div>
<div className="rounded-xl border border-error-500/30 bg-error-500/10 p-6 text-center">
<p className="text-error-400">{t('admin.landings.stats.loadError')}</p>
<button
onClick={() => navigate('/admin/landings')}
className="mt-4 text-sm text-dark-400 hover:text-dark-200"
>
{t('common.back')}
</button>
</div>
</div>
);
}
const landingTitle = landing ? resolveLocaleDisplay(landing.title) : `#${numericId}`;
return (
<div className="animate-fade-in">
{/* Header */}
<div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-center gap-3">
<AdminBackButton to="/admin/landings" />
<div className="rounded-lg bg-accent-500/20 p-2 text-accent-400">
<ChartIcon />
</div>
<div className="min-w-0">
<h1 className="truncate text-xl font-semibold text-dark-100">{landingTitle}</h1>
<div className="mt-1 flex items-center gap-2">
{landing?.is_active ? (
<span className="rounded bg-success-500/20 px-2 py-0.5 text-xs text-success-400">
{t('admin.landings.active')}
</span>
) : (
<span className="rounded bg-dark-600 px-2 py-0.5 text-xs text-dark-400">
{t('admin.landings.inactive')}
</span>
)}
</div>
</div>
</div>
</div>
<div className="space-y-6">
{/* Summary Cards */}
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4 text-center">
<div className="text-xl font-bold text-accent-400 sm:text-2xl">
{stats.total_purchases}
</div>
<div className="text-xs text-dark-500">{t('admin.landings.stats.totalPurchases')}</div>
</div>
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4 text-center">
<div className="truncate text-xl font-bold text-success-400 sm:text-2xl">
{formatWithCurrency(stats.total_revenue_kopeks / CHART_COMMON.KOPEKS_DIVISOR)}
</div>
<div className="text-xs text-dark-500">{t('admin.landings.stats.revenue')}</div>
</div>
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4 text-center">
<div className="text-xl font-bold text-purple-400 sm:text-2xl">{stats.total_gifts}</div>
<div className="text-xs text-dark-500">{t('admin.landings.stats.giftPurchases')}</div>
</div>
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4 text-center">
<div className="text-xl font-bold text-warning-400 sm:text-2xl">
{stats.conversion_rate}%
</div>
<div className="text-xs text-dark-500">{t('admin.landings.stats.conversionRate')}</div>
</div>
</div>
{/* Charts */}
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
{/* Daily Purchases & Revenue */}
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4">
<h3 className="mb-4 font-medium text-dark-200">
{t('admin.landings.stats.dailyChart')}
</h3>
{dailyData.length === 0 ? (
<div className="flex h-[220px] items-center justify-center text-sm text-dark-500">
{t('admin.landings.stats.noPurchases')}
</div>
) : (
<ResponsiveContainer width="100%" height={220}>
<AreaChart data={dailyData} margin={CHART_COMMON.CHART.MARGIN}>
<defs>
<linearGradient
id={`landingPurchaseGrad-${numericId}`}
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop
offset={CHART_COMMON.GRADIENT.START_OFFSET}
stopColor={colors.referrals}
stopOpacity={CHART_COMMON.GRADIENT.START_OPACITY}
/>
<stop
offset={CHART_COMMON.GRADIENT.END_OFFSET}
stopColor={colors.referrals}
stopOpacity={CHART_COMMON.GRADIENT.END_OPACITY}
/>
</linearGradient>
<linearGradient
id={`landingRevenueGrad-${numericId}`}
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop
offset={CHART_COMMON.GRADIENT.START_OFFSET}
stopColor={colors.earnings}
stopOpacity={CHART_COMMON.GRADIENT.START_OPACITY}
/>
<stop
offset={CHART_COMMON.GRADIENT.END_OFFSET}
stopColor={colors.earnings}
stopOpacity={CHART_COMMON.GRADIENT.END_OPACITY}
/>
</linearGradient>
</defs>
<CartesianGrid strokeDasharray={CHART_COMMON.GRID_DASH} stroke={colors.grid} />
<XAxis
dataKey="label"
tick={{ fontSize: CHART_COMMON.AXIS.TICK_FONT_SIZE, fill: colors.tick }}
stroke={colors.grid}
interval="preserveStartEnd"
/>
<YAxis
yAxisId="left"
tick={{ fontSize: CHART_COMMON.AXIS.TICK_FONT_SIZE, fill: colors.tick }}
stroke={colors.grid}
allowDecimals={false}
/>
<YAxis
yAxisId="right"
orientation="right"
tick={{ fontSize: CHART_COMMON.AXIS.TICK_FONT_SIZE, fill: colors.tick }}
stroke={colors.grid}
/>
<Tooltip
contentStyle={{
backgroundColor: colors.tooltipBg,
border: `1px solid ${colors.tooltipBorder}`,
borderRadius: CHART_COMMON.TOOLTIP.BORDER_RADIUS,
fontSize: CHART_COMMON.TOOLTIP.FONT_SIZE,
}}
labelStyle={{ color: colors.label }}
/>
<Area
yAxisId="left"
type="monotone"
dataKey="purchases"
name={t('admin.landings.stats.purchases')}
stroke={colors.referrals}
fill={`url(#landingPurchaseGrad-${numericId})`}
strokeWidth={CHART_COMMON.STROKE_WIDTH}
/>
<Area
yAxisId="right"
type="monotone"
dataKey="revenue"
name={t('admin.landings.stats.revenueLabel')}
stroke={colors.earnings}
fill={`url(#landingRevenueGrad-${numericId})`}
strokeWidth={CHART_COMMON.STROKE_WIDTH}
/>
</AreaChart>
</ResponsiveContainer>
)}
</div>
{/* Tariff Distribution */}
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4">
<h3 className="mb-4 font-medium text-dark-200">
{t('admin.landings.stats.tariffChart')}
</h3>
{tariffData.length === 0 ? (
<div className="flex h-[220px] items-center justify-center text-sm text-dark-500">
{t('admin.landings.stats.noPurchases')}
</div>
) : (
<ResponsiveContainer width="100%" height={barChartHeight}>
<BarChart
data={tariffData}
layout="vertical"
margin={{ ...CHART_COMMON.CHART.MARGIN, left: 10 }}
>
<CartesianGrid strokeDasharray={CHART_COMMON.GRID_DASH} stroke={colors.grid} />
<XAxis
type="number"
tick={{ fontSize: CHART_COMMON.AXIS.TICK_FONT_SIZE, fill: colors.tick }}
stroke={colors.grid}
allowDecimals={false}
/>
<YAxis
type="category"
dataKey="name"
tick={{ fontSize: CHART_COMMON.AXIS.TICK_FONT_SIZE, fill: colors.tick }}
stroke={colors.grid}
width={100}
/>
<Tooltip
contentStyle={{
backgroundColor: colors.tooltipBg,
border: `1px solid ${colors.tooltipBorder}`,
borderRadius: CHART_COMMON.TOOLTIP.BORDER_RADIUS,
fontSize: CHART_COMMON.TOOLTIP.FONT_SIZE,
}}
labelStyle={{ color: colors.label }}
formatter={(value: number | undefined) => {
return [value ?? 0, t('admin.landings.stats.purchases')];
}}
/>
<Bar
dataKey="purchases"
name={t('admin.landings.stats.purchases')}
radius={[0, 4, 4, 0]}
>
{tariffData.map((_, index) => (
<Cell key={index} fill={TARIFF_PALETTE[index % TARIFF_PALETTE.length]} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
)}
</div>
</div>
{/* Additional Stats Row */}
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4">
<div className="mb-1 text-sm text-dark-400">
{t('admin.landings.stats.avgPurchase')}
</div>
<div className="text-lg font-medium text-dark-200">
{formatWithCurrency(stats.avg_purchase_kopeks / CHART_COMMON.KOPEKS_DIVISOR)}
</div>
</div>
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4">
<div className="mb-1 text-sm text-dark-400">
{t('admin.landings.stats.regularPurchases')}
</div>
<div className="text-lg font-medium text-dark-200">{stats.total_regular}</div>
</div>
<div className="col-span-2 rounded-xl border border-dark-700 bg-dark-800 p-4 sm:col-span-1">
<div className="mb-1 text-sm text-dark-400">{t('admin.landings.stats.funnel')}</div>
<div className="text-lg font-medium text-dark-200">
{stats.total_created}{' '}
<span className="text-sm text-dark-500">{t('admin.landings.stats.created')}</span>
{' / '}
{stats.total_successful}{' '}
<span className="text-sm text-dark-500">{t('admin.landings.stats.successful')}</span>
</div>
</div>
</div>
{/* Gift vs Regular Donut */}
{stats.total_purchases > 0 && (
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4">
<h3 className="mb-4 font-medium text-dark-200">
{t('admin.landings.stats.giftBreakdown')}
</h3>
<div className="flex items-center justify-center gap-8">
<div className="relative">
<ResponsiveContainer width={160} height={160}>
<PieChart>
<Pie
data={donutData}
cx="50%"
cy="50%"
innerRadius={50}
outerRadius={70}
dataKey="value"
strokeWidth={0}
>
{donutData.map((entry, index) => (
<Cell key={index} fill={entry.color} />
))}
</Pie>
<Tooltip
contentStyle={{
backgroundColor: colors.tooltipBg,
border: `1px solid ${colors.tooltipBorder}`,
borderRadius: CHART_COMMON.TOOLTIP.BORDER_RADIUS,
fontSize: CHART_COMMON.TOOLTIP.FONT_SIZE,
}}
/>
</PieChart>
</ResponsiveContainer>
{/* Center text */}
<div className="absolute inset-0 flex items-center justify-center">
<span className="text-lg font-bold text-dark-100">{stats.total_purchases}</span>
</div>
</div>
<div className="space-y-3">
<div className="flex items-center gap-2">
<div
className="h-3 w-3 rounded-full"
style={{ backgroundColor: colors.referrals }}
/>
<span className="text-sm text-dark-300">
{t('admin.landings.stats.regular')}: {stats.total_regular}
</span>
</div>
<div className="flex items-center gap-2">
<div className="h-3 w-3 rounded-full" style={{ backgroundColor: GIFT_COLOR }} />
<span className="text-sm text-dark-300">
{t('admin.landings.stats.gifts')}: {stats.total_gifts}
</span>
</div>
</div>
</div>
</div>
)}
{/* Purchases List */}
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4">
{/* Header row: title + status filter */}
<div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<h3 className="font-medium text-dark-200">{t('admin.landings.purchases.title')}</h3>
<select
value={purchaseStatusFilter}
onChange={(e) => {
setPurchaseStatusFilter(e.target.value as PurchaseItemStatus | 'all');
setPurchaseOffset(0);
}}
className="rounded-lg border border-dark-600 bg-dark-900 px-3 py-1.5 text-sm text-dark-200 outline-none transition-colors focus:border-accent-500"
aria-label={t('admin.landings.purchases.allStatuses')}
>
{PURCHASE_STATUS_OPTIONS.map((opt) => (
<option key={opt} value={opt}>
{opt === 'all'
? t('admin.landings.purchases.allStatuses')
: t(`admin.landings.purchases.status_${opt}`)}
</option>
))}
</select>
</div>
{/* Content */}
{purchasesLoading ? (
<div className="flex items-center justify-center py-8">
<div className="h-6 w-6 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
</div>
) : purchaseItems.length === 0 ? (
<div className="py-8 text-center text-sm text-dark-500">
{t('admin.landings.purchases.noPurchases')}
</div>
) : (
<>
<div className="space-y-2">
{purchaseItems.map((item) => (
<PurchaseCard
key={item.id}
item={item}
formatPrice={(kopeks) =>
formatWithCurrency(kopeks / CHART_COMMON.KOPEKS_DIVISOR)
}
lang={i18n.language}
t={t}
/>
))}
</div>
{/* Pagination */}
{purchaseTotalPages > 1 && (
<div className="mt-4 flex flex-col items-center gap-2 sm:flex-row sm:justify-between">
<span className="text-xs text-dark-500">
{t('admin.landings.purchases.showing', {
from: purchaseOffset + 1,
to: Math.min(purchaseOffset + PURCHASES_PAGE_SIZE, purchaseTotal),
total: purchaseTotal,
})}
</span>
<div className="flex items-center gap-2">
<button
onClick={() =>
setPurchaseOffset((prev) => Math.max(0, prev - PURCHASES_PAGE_SIZE))
}
disabled={purchaseOffset === 0}
className="flex items-center gap-1 rounded-lg border border-dark-700 bg-dark-800 px-3 py-1.5 text-sm text-dark-300 transition-colors hover:border-dark-600 hover:text-dark-100 disabled:cursor-not-allowed disabled:opacity-40"
aria-label={t('admin.landings.purchases.prev')}
>
<ChevronLeftSmall />
<span className="hidden sm:inline">{t('admin.landings.purchases.prev')}</span>
</button>
<span className="px-2 text-xs text-dark-400">
{t('admin.landings.purchases.page', {
current: purchaseCurrentPage,
total: purchaseTotalPages,
})}
</span>
<button
onClick={() => setPurchaseOffset((prev) => prev + PURCHASES_PAGE_SIZE)}
disabled={purchaseOffset + PURCHASES_PAGE_SIZE >= purchaseTotal}
className="flex items-center gap-1 rounded-lg border border-dark-700 bg-dark-800 px-3 py-1.5 text-sm text-dark-300 transition-colors hover:border-dark-600 hover:text-dark-100 disabled:cursor-not-allowed disabled:opacity-40"
aria-label={t('admin.landings.purchases.next')}
>
<span className="hidden sm:inline">{t('admin.landings.purchases.next')}</span>
<ChevronRightSmall />
</button>
</div>
</div>
)}
</>
)}
</div>
</div>
</div>
);
}

View File

@@ -79,11 +79,22 @@ const CopyIcon = () => (
</svg>
);
const StatsChartIcon = () => (
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z"
/>
</svg>
);
// ============ Sortable Landing Card ============
interface SortableLandingCardProps {
landing: LandingListItem;
onEdit: () => void;
onStats: () => void;
onDelete: () => void;
onToggle: () => void;
onCopyUrl: () => void;
@@ -93,6 +104,7 @@ interface SortableLandingCardProps {
function SortableLandingCard({
landing,
onEdit,
onStats,
onDelete,
onToggle,
onCopyUrl,
@@ -168,7 +180,7 @@ function SortableLandingCard({
</div>
<div className="text-sm text-dark-400">
<span>
{landing.purchase_stats.total} {t('admin.landings.purchases')}
{landing.purchase_stats.total} {t('admin.landings.purchaseCount')}
</span>
</div>
</div>
@@ -182,6 +194,13 @@ function SortableLandingCard({
>
<CopyIcon />
</button>
<button
onClick={onStats}
className="rounded-lg bg-dark-700 p-2 text-dark-300 transition-colors hover:bg-dark-600 hover:text-dark-100"
title={t('admin.landings.statistics')}
>
<StatsChartIcon />
</button>
<button
onClick={onToggle}
className={cn(
@@ -237,6 +256,13 @@ function SortableLandingCard({
>
<CopyIcon />
</button>
<button
onClick={onStats}
className="rounded-lg bg-dark-700 p-2 text-dark-300 transition-colors hover:bg-dark-600 hover:text-dark-100"
title={t('admin.landings.statistics')}
>
<StatsChartIcon />
</button>
<button
onClick={onToggle}
className={cn(
@@ -472,6 +498,7 @@ export default function AdminLandings() {
key={landing.id}
landing={landing}
onEdit={() => navigate(`/admin/landings/${landing.id}/edit`)}
onStats={() => navigate(`/admin/landings/${landing.id}/stats`)}
onDelete={() => handleDelete(landing)}
onToggle={() => toggleMutation.mutate(landing.id)}
onCopyUrl={() => handleCopyUrl(landing.slug)}

View File

@@ -27,6 +27,10 @@ export const LINK_TELEGRAM_STATE_KEY = 'link_telegram_state';
/** Compact Telegram Login Widget for account linking (browser only). */
function TelegramLinkWidget() {
const containerRef = useRef<HTMLDivElement>(null);
const navigate = useNavigate();
const { showToast } = useToast();
const { t } = useTranslation();
const queryClient = useQueryClient();
const botUsername = import.meta.env.VITE_TELEGRAM_BOT_USERNAME || '';
useEffect(() => {
@@ -37,29 +41,53 @@ function TelegramLinkWidget() {
container.removeChild(container.firstChild);
}
// Generate CSRF state token and store in sessionStorage
const csrfState = crypto.randomUUID();
sessionStorage.setItem(LINK_TELEGRAM_STATE_KEY, csrfState);
const redirectUrl = `${window.location.origin}/auth/link/telegram/callback?csrf_state=${encodeURIComponent(csrfState)}`;
// Global callback invoked by the Telegram Login Widget
const callbackName = '__onTelegramLinkAuth';
(window as unknown as Record<string, unknown>)[callbackName] = async (
user: Record<string, unknown>,
) => {
try {
const response = await authApi.linkTelegram({
id: user.id as number,
first_name: user.first_name as string,
last_name: (user.last_name as string) || undefined,
username: (user.username as string) || undefined,
photo_url: (user.photo_url as string) || undefined,
auth_date: user.auth_date as number,
hash: user.hash as string,
});
if (response.merge_required && response.merge_token) {
navigate(`/merge/${response.merge_token}`, { replace: true });
} else {
queryClient.invalidateQueries({ queryKey: ['linked-providers'] });
showToast({ type: 'success', message: t('profile.accounts.linkSuccess') });
}
} catch (err: unknown) {
showToast({
type: 'error',
message: getErrorDetail(err) || t('profile.accounts.linkError'),
});
}
};
const script = document.createElement('script');
script.src = 'https://telegram.org/js/telegram-widget.js?23';
script.setAttribute('data-telegram-login', botUsername);
script.setAttribute('data-size', 'small');
script.setAttribute('data-radius', '8');
script.setAttribute('data-auth-url', redirectUrl);
script.setAttribute('data-onauth', `${callbackName}(user)`);
script.setAttribute('data-request-access', 'write');
script.async = true;
container.appendChild(script);
return () => {
delete (window as unknown as Record<string, unknown>)[callbackName];
while (container.firstChild) {
container.removeChild(container.firstChild);
}
};
}, [botUsername]);
}, [botUsername, navigate, showToast, t, queryClient]);
if (!botUsername) {
return null;

View File

@@ -12,6 +12,7 @@ import type {
LandingPaymentMethod,
PurchaseRequest,
} from '../api/landings';
import { StaticBackgroundRenderer } from '../components/backgrounds/BackgroundRenderer';
import LanguageSwitcher from '../components/LanguageSwitcher';
import { cn } from '../lib/utils';
import { getApiErrorMessage } from '../utils/api-error';
@@ -962,7 +963,8 @@ export default function QuickPurchase() {
const showTariffCards = visibleTariffs.length > 1;
return (
<div className="min-h-dvh overflow-x-hidden bg-dark-950">
<div className={cn('min-h-dvh overflow-x-hidden', !config.background_config && 'bg-dark-950')}>
{config.background_config && <StaticBackgroundRenderer config={config.background_config} />}
<div className="mx-auto max-w-5xl px-4 py-8 sm:px-6 lg:px-8">
{/* Language switcher */}
<div className="mb-4 flex justify-end">