From 110c1c3e830369269301036e877ce318d88b4ecb Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 19 Oct 2026 18:29:20 +0200 Subject: [PATCH] After persist the live activity data for welcome --- .../src/controllers/marketingController.ts | 68 +++ backend/src/db/schema.sql | 55 +++ ...marketingLiveActivitySettingsRepository.ts | 130 ++++++ .../marketingPersonaRepository.ts | 100 +++++ backend/src/routes/index.ts | 43 ++ backend/src/services/marketingService.ts | 231 +++++++--- backend/src/tests/marketingService.test.ts | 109 ++++- .../src/validation/adminResourceSchemas.ts | 35 ++ .../lib/data/models/marketing_models.dart | 13 + .../marketing_repository_impl.dart | 23 +- .../welcome/presentation/welcome_screen.dart | 85 ++-- .../welcome/utils/marketing_fallback.dart | 93 +--- prediqo_mobile/test/support/e2e_fixtures.dart | 2 + .../test/welcome_section_load_test.dart | 14 +- prediqo_web/src/app/router/router.tsx | 2 + .../features/marketing/MarketingAdminPage.tsx | 402 ++++++++++++++++++ .../src/features/options/OptionsPage.tsx | 10 + prediqo_web/src/shared/auth/permissions.ts | 2 + prediqo_web/src/shared/i18n/locales/en.ts | 41 ++ prediqo_web/src/shared/i18n/locales/fr.ts | 43 ++ 20 files changed, 1288 insertions(+), 213 deletions(-) create mode 100644 backend/src/repositories/marketingLiveActivitySettingsRepository.ts create mode 100644 backend/src/repositories/marketingPersonaRepository.ts create mode 100644 prediqo_web/src/features/marketing/MarketingAdminPage.tsx diff --git a/backend/src/controllers/marketingController.ts b/backend/src/controllers/marketingController.ts index 12580455..d867e61e 100644 --- a/backend/src/controllers/marketingController.ts +++ b/backend/src/controllers/marketingController.ts @@ -31,3 +31,71 @@ export async function getWithdrawalFeed(_req: AuthRequest, res: Response): Promi res.status(500).json({ error: msg }); } } + +export async function getLiveActivitySettings(_req: AuthRequest, res: Response): Promise { + try { + const settings = await marketingService.getLiveActivitySettingsAdmin(); + res.json(settings); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to load marketing settings'; + res.status(500).json({ error: msg }); + } +} + +export async function updateLiveActivitySettings(req: AuthRequest, res: Response): Promise { + try { + const settings = await marketingService.updateLiveActivitySettingsAdmin( + req.body as Record + ); + res.json(settings); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to update marketing settings'; + res.status(400).json({ error: msg }); + } +} + +export async function listPersonas(_req: AuthRequest, res: Response): Promise { + try { + const personas = await marketingService.listPersonasAdmin(); + res.json(personas); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to load personas'; + res.status(500).json({ error: msg }); + } +} + +export async function createPersona(req: AuthRequest, res: Response): Promise { + try { + const persona = await marketingService.createPersonaAdmin( + req.body as { publicId: string; isActive?: boolean; sortOrder?: number } + ); + res.status(201).json(persona); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to create persona'; + res.status(400).json({ error: msg }); + } +} + +export async function updatePersona(req: AuthRequest, res: Response): Promise { + try { + const persona = await marketingService.updatePersonaAdmin( + req.params.id, + req.body as { publicId?: string; isActive?: boolean; sortOrder?: number } + ); + res.json(persona); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to update persona'; + const status = msg === 'Persona not found' ? 404 : 400; + res.status(status).json({ error: msg }); + } +} + +export async function deletePersona(req: AuthRequest, res: Response): Promise { + try { + await marketingService.deletePersonaAdmin(req.params.id); + res.status(204).send(); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to delete persona'; + res.status(msg === 'Persona not found' ? 404 : 400).json({ error: msg }); + } +} diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index 2b9a419e..7e0832bf 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -2766,3 +2766,58 @@ BEGIN END IF; END $$; + +-- Marketing Live Activity: synthetic personas + singleton settings (admin-configurable) +CREATE TABLE IF NOT EXISTS marketing_personas ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + public_id VARCHAR(32) NOT NULL UNIQUE, + is_active BOOLEAN NOT NULL DEFAULT TRUE, + sort_order INT NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_marketing_personas_active_sort + ON marketing_personas (is_active, sort_order, public_id); + +CREATE TABLE IF NOT EXISTS marketing_live_activity_settings ( + id INT PRIMARY KEY CHECK (id = 1), + enabled BOOLEAN NOT NULL DEFAULT TRUE, + real_active_threshold INT NOT NULL DEFAULT 200 CHECK (real_active_threshold > 0), + max_synthetic_entries INT NOT NULL DEFAULT 20 CHECK (max_synthetic_entries >= 0 AND max_synthetic_entries <= 100), + display_active_target INT NOT NULL DEFAULT 250 CHECK (display_active_target > 0), + active_window_minutes INT NOT NULL DEFAULT 15 CHECK (active_window_minutes > 0), + feed_real_fetch INT NOT NULL DEFAULT 16 CHECK (feed_real_fetch > 0), + client_refresh_seconds INT NOT NULL DEFAULT 30 CHECK (client_refresh_seconds >= 10 AND client_refresh_seconds <= 120), + list_rotate_seconds INT NOT NULL DEFAULT 8 CHECK (list_rotate_seconds >= 5 AND list_rotate_seconds <= 60), + cache_ttl_seconds INT NOT NULL DEFAULT 12 CHECK (cache_ttl_seconds > 0), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +INSERT INTO marketing_live_activity_settings (id) +VALUES (1) +ON CONFLICT (id) DO NOTHING; + +INSERT INTO marketing_personas (public_id, is_active, sort_order) +VALUES + ('7a***k2', TRUE, 1), + ('9c***m1', TRUE, 2), + ('3f***p8', TRUE, 3), + ('b2***q4', TRUE, 4), + ('e8***t6', TRUE, 5), + ('1d***w9', TRUE, 6), + ('5h***n3', TRUE, 7), + ('c4***r7', TRUE, 8), + ('8j***v5', TRUE, 9), + ('2m***x0', TRUE, 10), + ('6p***y1', TRUE, 11), + ('0s***z8', TRUE, 12), + ('4n***a3', TRUE, 13), + ('d7***b5', TRUE, 14), + ('f1***c9', TRUE, 15), + ('a9***d2', TRUE, 16), + ('g3***e4', TRUE, 17), + ('h6***f7', TRUE, 18), + ('i2***g1', TRUE, 19), + ('j8***h6', TRUE, 20) +ON CONFLICT (public_id) DO NOTHING; diff --git a/backend/src/repositories/marketingLiveActivitySettingsRepository.ts b/backend/src/repositories/marketingLiveActivitySettingsRepository.ts new file mode 100644 index 00000000..ee155085 --- /dev/null +++ b/backend/src/repositories/marketingLiveActivitySettingsRepository.ts @@ -0,0 +1,130 @@ +import { query } from '../db/connection'; + +export type MarketingLiveActivitySettingsRow = { + id: number; + enabled: boolean; + real_active_threshold: number; + max_synthetic_entries: number; + display_active_target: number; + active_window_minutes: number; + feed_real_fetch: number; + client_refresh_seconds: number; + list_rotate_seconds: number; + cache_ttl_seconds: number; + updated_at: Date; +}; + +export type MarketingLiveActivitySettings = { + enabled: boolean; + realActiveThreshold: number; + maxSyntheticEntries: number; + displayActiveTarget: number; + activeWindowMinutes: number; + feedRealFetch: number; + clientRefreshSeconds: number; + listRotateSeconds: number; + cacheTtlSeconds: number; + updatedAt: string; +}; + +const DEFAULTS: Omit = { + enabled: true, + realActiveThreshold: 200, + maxSyntheticEntries: 20, + displayActiveTarget: 250, + activeWindowMinutes: 15, + feedRealFetch: 16, + clientRefreshSeconds: 30, + listRotateSeconds: 8, + cacheTtlSeconds: 12, +}; + +function mapRow(row: MarketingLiveActivitySettingsRow): MarketingLiveActivitySettings { + return { + enabled: row.enabled, + realActiveThreshold: Number(row.real_active_threshold) || DEFAULTS.realActiveThreshold, + maxSyntheticEntries: Number(row.max_synthetic_entries) || 0, + displayActiveTarget: Number(row.display_active_target) || DEFAULTS.displayActiveTarget, + activeWindowMinutes: Number(row.active_window_minutes) || DEFAULTS.activeWindowMinutes, + feedRealFetch: Number(row.feed_real_fetch) || DEFAULTS.feedRealFetch, + clientRefreshSeconds: Number(row.client_refresh_seconds) || DEFAULTS.clientRefreshSeconds, + listRotateSeconds: Number(row.list_rotate_seconds) || DEFAULTS.listRotateSeconds, + cacheTtlSeconds: Number(row.cache_ttl_seconds) || DEFAULTS.cacheTtlSeconds, + updatedAt: row.updated_at.toISOString(), + }; +} + +export async function getLiveActivitySettings(): Promise { + const rows = await query( + `SELECT id, enabled, real_active_threshold, max_synthetic_entries, display_active_target, + active_window_minutes, feed_real_fetch, client_refresh_seconds, list_rotate_seconds, + cache_ttl_seconds, updated_at + FROM marketing_live_activity_settings WHERE id = 1` + ); + if (!rows[0]) { + return { ...DEFAULTS, updatedAt: new Date(0).toISOString() }; + } + return mapRow(rows[0]); +} + +export type LiveActivitySettingsPatch = Partial<{ + enabled: boolean; + realActiveThreshold: number; + maxSyntheticEntries: number; + displayActiveTarget: number; + activeWindowMinutes: number; + feedRealFetch: number; + clientRefreshSeconds: number; + listRotateSeconds: number; + cacheTtlSeconds: number; +}>; + +export async function updateLiveActivitySettings( + patch: LiveActivitySettingsPatch +): Promise { + const current = await getLiveActivitySettings(); + const next = { + enabled: patch.enabled ?? current.enabled, + realActiveThreshold: patch.realActiveThreshold ?? current.realActiveThreshold, + maxSyntheticEntries: patch.maxSyntheticEntries ?? current.maxSyntheticEntries, + displayActiveTarget: patch.displayActiveTarget ?? current.displayActiveTarget, + activeWindowMinutes: patch.activeWindowMinutes ?? current.activeWindowMinutes, + feedRealFetch: patch.feedRealFetch ?? current.feedRealFetch, + clientRefreshSeconds: patch.clientRefreshSeconds ?? current.clientRefreshSeconds, + listRotateSeconds: patch.listRotateSeconds ?? current.listRotateSeconds, + cacheTtlSeconds: patch.cacheTtlSeconds ?? current.cacheTtlSeconds, + }; + + const rows = await query( + `UPDATE marketing_live_activity_settings SET + enabled = $1, + real_active_threshold = $2, + max_synthetic_entries = $3, + display_active_target = $4, + active_window_minutes = $5, + feed_real_fetch = $6, + client_refresh_seconds = $7, + list_rotate_seconds = $8, + cache_ttl_seconds = $9, + updated_at = NOW() + WHERE id = 1 + RETURNING id, enabled, real_active_threshold, max_synthetic_entries, display_active_target, + active_window_minutes, feed_real_fetch, client_refresh_seconds, list_rotate_seconds, + cache_ttl_seconds, updated_at`, + [ + next.enabled, + next.realActiveThreshold, + next.maxSyntheticEntries, + next.displayActiveTarget, + next.activeWindowMinutes, + next.feedRealFetch, + next.clientRefreshSeconds, + next.listRotateSeconds, + next.cacheTtlSeconds, + ] + ); + if (!rows[0]) { + throw new Error('Marketing live activity settings not found'); + } + return mapRow(rows[0]); +} diff --git a/backend/src/repositories/marketingPersonaRepository.ts b/backend/src/repositories/marketingPersonaRepository.ts new file mode 100644 index 00000000..23126271 --- /dev/null +++ b/backend/src/repositories/marketingPersonaRepository.ts @@ -0,0 +1,100 @@ +import { query } from '../db/connection'; + +export type MarketingPersonaRow = { + id: string; + public_id: string; + is_active: boolean; + sort_order: number; + created_at: Date; + updated_at: Date; +}; + +/** Masked public handle: 2 alnum + *** + 2 alnum (e.g. 7a***k2). */ +export const PUBLIC_ID_PATTERN = /^[a-zA-Z0-9]{2}\*\*\*[a-zA-Z0-9]{2}$/; + +export function isValidPublicId(value: string): boolean { + return PUBLIC_ID_PATTERN.test(value.trim()); +} + +export async function listPersonas(): Promise { + return query( + `SELECT id, public_id, is_active, sort_order, created_at, updated_at + FROM marketing_personas + ORDER BY sort_order ASC, public_id ASC` + ); +} + +export async function listActivePersonas(limit = 100): Promise { + return query( + `SELECT id, public_id, is_active, sort_order, created_at, updated_at + FROM marketing_personas + WHERE is_active = TRUE + ORDER BY sort_order ASC, public_id ASC + LIMIT $1`, + [limit] + ); +} + +export async function getPersonaById(id: string): Promise { + const rows = await query( + `SELECT id, public_id, is_active, sort_order, created_at, updated_at + FROM marketing_personas WHERE id = $1`, + [id] + ); + return rows[0] ?? null; +} + +export type PersonaCreateInput = { + publicId: string; + isActive?: boolean; + sortOrder?: number; +}; + +export async function createPersona(input: PersonaCreateInput): Promise { + const rows = await query( + `INSERT INTO marketing_personas (public_id, is_active, sort_order) + VALUES ($1, $2, $3) + RETURNING id, public_id, is_active, sort_order, created_at, updated_at`, + [input.publicId.trim(), input.isActive ?? true, input.sortOrder ?? 0] + ); + return rows[0]; +} + +export type PersonaUpdateInput = { + publicId?: string; + isActive?: boolean; + sortOrder?: number; +}; + +export async function updatePersona( + id: string, + input: PersonaUpdateInput +): Promise { + const existing = await getPersonaById(id); + if (!existing) return null; + + const rows = await query( + `UPDATE marketing_personas SET + public_id = $2, + is_active = $3, + sort_order = $4, + updated_at = NOW() + WHERE id = $1 + RETURNING id, public_id, is_active, sort_order, created_at, updated_at`, + [ + id, + input.publicId?.trim() ?? existing.public_id, + input.isActive ?? existing.is_active, + input.sortOrder ?? existing.sort_order, + ] + ); + return rows[0] ?? null; +} + +export async function deletePersona(id: string): Promise { + const rows = await query<{ id: string }[]>( + `DELETE FROM marketing_personas WHERE id = $1 RETURNING id`, + [id] + ); + return rows.length > 0; +} diff --git a/backend/src/routes/index.ts b/backend/src/routes/index.ts index b6955e99..97892201 100644 --- a/backend/src/routes/index.ts +++ b/backend/src/routes/index.ts @@ -76,6 +76,9 @@ import { testWalletConfigBodySchema, shareCardSettingsBodySchema, soloEncouragementConfigBodySchema, + marketingLiveActivitySettingsBodySchema, + marketingPersonaCreateBodySchema, + marketingPersonaUpdateBodySchema, supportConversationUpdateBodySchema, faqCategoryCreateBodySchema, faqCategoryUpdateBodySchema, @@ -298,6 +301,46 @@ router.post('/admin/advertisements', requireRoles('admin'), requirePermissions(' router.patch('/admin/advertisements/:id', requireRoles('admin'), requirePermissions('games.admin'), validateBody(advertisementUpdateBodySchema), advertisementController.updateAdvertisement); router.delete('/admin/advertisements/:id', requireRoles('admin'), requirePermissions('games.admin'), advertisementController.deleteAdvertisement); +router.get( + '/admin/marketing/live-activity-settings', + requireRoles('admin'), + requirePermissions('games.admin'), + marketingController.getLiveActivitySettings +); +router.patch( + '/admin/marketing/live-activity-settings', + requireRoles('admin'), + requirePermissions('games.admin'), + validateBody(marketingLiveActivitySettingsBodySchema), + marketingController.updateLiveActivitySettings +); +router.get( + '/admin/marketing/personas', + requireRoles('admin'), + requirePermissions('games.admin'), + marketingController.listPersonas +); +router.post( + '/admin/marketing/personas', + requireRoles('admin'), + requirePermissions('games.admin'), + validateBody(marketingPersonaCreateBodySchema), + marketingController.createPersona +); +router.patch( + '/admin/marketing/personas/:id', + requireRoles('admin'), + requirePermissions('games.admin'), + validateBody(marketingPersonaUpdateBodySchema), + marketingController.updatePersona +); +router.delete( + '/admin/marketing/personas/:id', + requireRoles('admin'), + requirePermissions('games.admin'), + marketingController.deletePersona +); + router.get('/admin/users', requireRoles('admin'), requirePermissions('users.admin'), validateQuery(adminUsersListQuerySchema), adminController.listUsers); router.post('/admin/users/export', requireRoles('admin'), requirePermissions('users.admin'), validateBody(adminUsersExportBodySchema), adminController.startUsersExport); router.get('/admin/users/export/:jobId', requireRoles('admin'), requirePermissions('users.admin'), adminController.getUsersExportStatus); diff --git a/backend/src/services/marketingService.ts b/backend/src/services/marketingService.ts index 486fe8db..f66403d5 100644 --- a/backend/src/services/marketingService.ts +++ b/backend/src/services/marketingService.ts @@ -1,21 +1,17 @@ import * as marketingRepository from '../repositories/marketingRepository'; +import * as settingsRepository from '../repositories/marketingLiveActivitySettingsRepository'; +import type { MarketingLiveActivitySettings } from '../repositories/marketingLiveActivitySettingsRepository'; +import * as personaRepository from '../repositories/marketingPersonaRepository'; +import type { MarketingPersonaRow } from '../repositories/marketingPersonaRepository'; -const FEED_TARGET = 24; -const REAL_FETCH = 16; -const CACHE_TTL_MS = 12_000; -const ACTIVE_WINDOW_MINUTES = 15; -/** Marketing boost so early launch still looks lively. */ -const ACTIVE_SYNTHETIC_BASE = 180; -const ACTIVE_SYNTHETIC_SPREAD = 90; - -type CacheEntry = { at: number; value: T }; +type CacheEntry = { at: number; value: T; ttlMs: number }; const cache = new Map>(); -function cached(key: string, factory: () => Promise): Promise { +function cached(key: string, ttlMs: number, factory: () => Promise): Promise { const hit = cache.get(key) as CacheEntry | undefined; - if (hit && Date.now() - hit.at < CACHE_TTL_MS) return Promise.resolve(hit.value); + if (hit && Date.now() - hit.at < hit.ttlMs) return Promise.resolve(hit.value); return factory().then((value) => { - cache.set(key, { at: Date.now(), value }); + cache.set(key, { at: Date.now(), value, ttlMs }); return value; }); } @@ -71,31 +67,11 @@ export type MarketingDailyStats = { export type MarketingActivityFeed = { items: MarketingActivityItem[]; activePlayersCount: number; + clientRefreshSeconds: number; + listRotateSeconds: number; + syntheticEnabled: boolean; }; -const SYNTHETIC_HANDLES = [ - '7a***k2', - '9c***m1', - '3f***p8', - 'b2***q4', - 'e8***t6', - '1d***w9', - '5h***n3', - 'c4***r7', - '8j***v5', - '2m***x0', - '6p***y1', - '0s***z8', - '4n***a3', - 'd7***b5', - 'f1***c9', - 'a9***d2', - 'g3***e4', - 'h6***f7', - 'i2***g1', - 'j8***h6', -]; - const SYNTHETIC_WITHDRAWALS = [20, 35, 50, 80, 100, 120, 200, 250, 300, 450, 500, 800]; /** Faster slot so synthetic pool rotates ~every 10s server-side. */ @@ -103,36 +79,73 @@ function slotIndex(now = Date.now()): number { return Math.floor(now / 10_000); } -/** Playing-only synthetic rows (no Won / no stake emphasis). */ -export function buildSyntheticActivity(count: number, now = Date.now()): MarketingActivityItem[] { +/** Whether Live Activity should merge / boost with synthetic personas. */ +export function shouldUseSynthetic( + realActive: number, + settings: Pick +): boolean { + return settings.enabled && realActive < settings.realActiveThreshold; +} + +/** + * Title counter: under threshold with fictifs on → approach display target; + * otherwise real-only (never inflate official-looking counts past real when disabled). + */ +export function computeActivePlayersCount( + realActive: number, + settings: Pick< + MarketingLiveActivitySettings, + 'enabled' | 'realActiveThreshold' | 'displayActiveTarget' + > +): number { + if (!shouldUseSynthetic(realActive, settings)) return realActive; + const pad = Math.max(0, settings.displayActiveTarget - realActive); + return Math.min(realActive + pad, settings.displayActiveTarget); +} + +/** Playing-only synthetic rows from active DB personas (no Won / no stake emphasis). */ +export function buildSyntheticActivityFromPersonas( + personas: Array>, + count: number, + now = Date.now() +): MarketingActivityItem[] { + if (count <= 0 || personas.length === 0) return []; const slot = slotIndex(now); - const start = (slot * 3) % SYNTHETIC_HANDLES.length; + const start = (slot * 3) % personas.length; const items: MarketingActivityItem[] = []; - const n = Math.min(count, SYNTHETIC_HANDLES.length); - for (let i = 0; i < n; i++) { - const handle = SYNTHETIC_HANDLES[(start + i) % SYNTHETIC_HANDLES.length]; + const n = Math.min(count, personas.length); + const seen = new Set(); + for (let i = 0; items.length < n && i < personas.length * 2; i++) { + const handle = personas[(start + i) % personas.length].public_id; + if (seen.has(handle)) continue; + seen.add(handle); items.push({ - id: `syn-act-${slot}-${i}`, + id: `syn-act-${slot}-${items.length}`, publicId: handle, kind: 'bet', amountLabel: '0', statusLabel: 'Playing', - createdAt: new Date(now - i * 20_000).toISOString(), + createdAt: new Date(now - items.length * 20_000).toISOString(), synthetic: true, }); } return items; } -export function buildSyntheticWithdrawals(count: number, now = Date.now()): MarketingWithdrawalItem[] { +export function buildSyntheticWithdrawalsFromPersonas( + personas: Array>, + count: number, + now = Date.now() +): MarketingWithdrawalItem[] { + if (count <= 0 || personas.length === 0) return []; const slot = slotIndex(now); const items: MarketingWithdrawalItem[] = []; for (let i = 0; i < count; i++) { - const idx = (slot + i * 2) % SYNTHETIC_HANDLES.length; + const idx = (slot + i * 2) % personas.length; const amount = SYNTHETIC_WITHDRAWALS[(slot + i * 5) % SYNTHETIC_WITHDRAWALS.length]; items.push({ id: `syn-wd-${slot}-${i}`, - publicId: SYNTHETIC_HANDLES[idx], + publicId: personas[idx].public_id, amountLabel: String(amount), statusLabel: 'Completed', createdAt: new Date(now - i * 90_000).toISOString(), @@ -167,13 +180,6 @@ export function mergeFeedItems( return out; } -/** Marketing active count = recent real distinct + lively synthetic boost. */ -export function computeActivePlayersCount(realRecent: number, now = Date.now()): number { - const slot = slotIndex(now); - const boost = ACTIVE_SYNTHETIC_BASE + (slot % ACTIVE_SYNTHETIC_SPREAD); - return Math.max(realRecent + boost, boost); -} - function mapRealPlaying(row: marketingRepository.RealActivityRow): MarketingActivityItem { return { id: row.id, @@ -197,45 +203,138 @@ function mapRealWithdrawal(row: marketingRepository.RealWithdrawalRow): Marketin }; } +async function loadSettingsCached(): Promise { + return cached('live-activity-settings', 12_000, () => settingsRepository.getLiveActivitySettings()); +} + +async function loadActivePersonasCached( + ttlMs: number, + limit: number +): Promise { + return cached(`active-personas:${limit}`, ttlMs, () => + personaRepository.listActivePersonas(Math.max(limit, 100)) + ); +} + export async function getDailyStats(): Promise { - return cached('daily-stats', async () => { + const settings = await loadSettingsCached(); + return cached('daily-stats', settings.cacheTtlSeconds * 1000, async () => { const { dayStart, dayEnd, day } = marketingRepository.utcDayBounds(); const row = await marketingRepository.getDailyPlayerStats(dayStart, dayEnd); return { uniquePlayersToday: Number(row.unique_players) || 0, totalParticipationsToday: Number(row.total_participations) || 0, day, - timezone: 'UTC', + timezone: 'UTC' as const, }; }); } export async function getActivityFeed(): Promise { - return cached('activity-feed', async () => { - const [rows, realActive] = await Promise.all([ - marketingRepository.listRecentPlayingActivity(REAL_FETCH), - marketingRepository.countRecentDistinctPlayers(ACTIVE_WINDOW_MINUTES), + const settings = await loadSettingsCached(); + const ttlMs = settings.cacheTtlSeconds * 1000; + return cached('activity-feed', ttlMs, async () => { + const [rows, realActive, personas] = await Promise.all([ + marketingRepository.listRecentPlayingActivity(settings.feedRealFetch), + marketingRepository.countRecentDistinctPlayers(settings.activeWindowMinutes), + loadActivePersonasCached(ttlMs, settings.maxSyntheticEntries), ]); const real = rows.map(mapRealPlaying); - const synthetic = buildSyntheticActivity(FEED_TARGET); - const items = mergeFeedItems(real, synthetic, FEED_TARGET); + const useSynthetic = shouldUseSynthetic(realActive, settings); + const synthetic = useSynthetic + ? buildSyntheticActivityFromPersonas(personas, settings.maxSyntheticEntries) + : []; + const feedTarget = settings.feedRealFetch + (useSynthetic ? settings.maxSyntheticEntries : 0); + const items = useSynthetic ? mergeFeedItems(real, synthetic, feedTarget) : real; return { items, - activePlayersCount: computeActivePlayersCount(realActive), + activePlayersCount: computeActivePlayersCount(realActive, settings), + clientRefreshSeconds: settings.clientRefreshSeconds, + listRotateSeconds: settings.listRotateSeconds, + syntheticEnabled: useSynthetic, }; }); } export async function getWithdrawalFeed(): Promise<{ items: MarketingWithdrawalItem[] }> { - return cached('withdrawal-feed', async () => { - const rows = await marketingRepository.listRecentRealWithdrawals(8); + const settings = await loadSettingsCached(); + const ttlMs = settings.cacheTtlSeconds * 1000; + return cached('withdrawal-feed', ttlMs, async () => { + const [rows, realActive, personas] = await Promise.all([ + marketingRepository.listRecentRealWithdrawals(8), + marketingRepository.countRecentDistinctPlayers(settings.activeWindowMinutes), + loadActivePersonasCached(ttlMs, settings.maxSyntheticEntries), + ]); const real = rows.map(mapRealWithdrawal); - const synthetic = buildSyntheticWithdrawals(12); + const useSynthetic = shouldUseSynthetic(realActive, settings); + if (!useSynthetic) return { items: real }; + const synthetic = buildSyntheticWithdrawalsFromPersonas(personas, 12); return { items: mergeFeedItems(real, synthetic, 12) }; }); } -/** Test helper: clear in-memory cache. */ +/** Admin: settings + personas (invalidate cache on write). */ +export async function getLiveActivitySettingsAdmin(): Promise { + return settingsRepository.getLiveActivitySettings(); +} + +export async function updateLiveActivitySettingsAdmin( + patch: settingsRepository.LiveActivitySettingsPatch +): Promise { + const updated = await settingsRepository.updateLiveActivitySettings(patch); + clearMarketingCache(); + return updated; +} + +export function mapPersonaAdmin(row: MarketingPersonaRow) { + return { + id: row.id, + publicId: row.public_id, + isActive: row.is_active, + sortOrder: row.sort_order, + createdAt: row.created_at.toISOString(), + updatedAt: row.updated_at.toISOString(), + }; +} + +export async function listPersonasAdmin() { + const rows = await personaRepository.listPersonas(); + return rows.map(mapPersonaAdmin); +} + +export async function createPersonaAdmin(input: { + publicId: string; + isActive?: boolean; + sortOrder?: number; +}) { + if (!personaRepository.isValidPublicId(input.publicId)) { + throw new Error('Invalid publicId format (expected e.g. 7a***k2)'); + } + const row = await personaRepository.createPersona(input); + clearMarketingCache(); + return mapPersonaAdmin(row); +} + +export async function updatePersonaAdmin( + id: string, + input: { publicId?: string; isActive?: boolean; sortOrder?: number } +) { + if (input.publicId !== undefined && !personaRepository.isValidPublicId(input.publicId)) { + throw new Error('Invalid publicId format (expected e.g. 7a***k2)'); + } + const row = await personaRepository.updatePersona(id, input); + if (!row) throw new Error('Persona not found'); + clearMarketingCache(); + return mapPersonaAdmin(row); +} + +export async function deletePersonaAdmin(id: string): Promise { + const ok = await personaRepository.deletePersona(id); + if (!ok) throw new Error('Persona not found'); + clearMarketingCache(); +} + +/** Test helper / admin: clear in-memory cache. */ export function clearMarketingCache(): void { cache.clear(); } diff --git a/backend/src/tests/marketingService.test.ts b/backend/src/tests/marketingService.test.ts index 88bcc059..46728fda 100644 --- a/backend/src/tests/marketingService.test.ts +++ b/backend/src/tests/marketingService.test.ts @@ -5,14 +5,37 @@ import { utcDayBounds, } from '../repositories/marketingRepository'; import { - buildSyntheticActivity, - buildSyntheticWithdrawals, + buildSyntheticActivityFromPersonas, + buildSyntheticWithdrawalsFromPersonas, + clearMarketingCache, computeActivePlayersCount, formatAmountRaw, maskPublicId, mergeFeedItems, + shouldUseSynthetic, } from '../services/marketingService'; +const defaultSettings = { + enabled: true, + realActiveThreshold: 200, + displayActiveTarget: 250, +}; + +const personas = [ + { public_id: '7a***k2' }, + { public_id: '9c***m1' }, + { public_id: '3f***p8' }, + { public_id: 'b2***q4' }, + { public_id: 'e8***t6' }, + { public_id: '1d***w9' }, + { public_id: '5h***n3' }, + { public_id: 'c4***r7' }, + { public_id: '8j***v5' }, + { public_id: '2m***x0' }, + { public_id: '6p***y1' }, + { public_id: '0s***z8' }, +]; + describe('marketingService helpers', () => { test('daily stats include main bonus and test stake kinds', () => { assert.deepEqual([...MARKETING_STAKE_KINDS], ['main', 'bonus', 'test']); @@ -53,8 +76,47 @@ describe('marketingService helpers', () => { ); }); - test('synthetic activity is Playing-only with unique handles', () => { - const items = buildSyntheticActivity(12, 1_700_000_000_000); + test('shouldUseSynthetic: 50 and 199 use fictifs when enabled', () => { + assert.equal(shouldUseSynthetic(50, defaultSettings), true); + assert.equal(shouldUseSynthetic(199, defaultSettings), true); + }); + + test('shouldUseSynthetic: 200 and above use real only', () => { + assert.equal(shouldUseSynthetic(200, defaultSettings), false); + assert.equal(shouldUseSynthetic(250, defaultSettings), false); + }); + + test('shouldUseSynthetic: disabled never uses fictifs', () => { + const disabled = { ...defaultSettings, enabled: false }; + assert.equal(shouldUseSynthetic(50, disabled), false); + assert.equal(shouldUseSynthetic(199, disabled), false); + }); + + test('shouldUseSynthetic respects custom threshold', () => { + const low = { ...defaultSettings, realActiveThreshold: 100 }; + assert.equal(shouldUseSynthetic(50, low), true); + assert.equal(shouldUseSynthetic(100, low), false); + }); + + test('computeActivePlayersCount pads toward display target under threshold', () => { + assert.equal(computeActivePlayersCount(50, defaultSettings), 250); + assert.equal(computeActivePlayersCount(199, defaultSettings), 250); + }); + + test('computeActivePlayersCount returns real when at/above threshold or disabled', () => { + assert.equal(computeActivePlayersCount(200, defaultSettings), 200); + assert.equal(computeActivePlayersCount(50, { ...defaultSettings, enabled: false }), 50); + }); + + test('clearMarketingCache is callable after settings-style changes', () => { + clearMarketingCache(); + assert.equal(shouldUseSynthetic(50, { ...defaultSettings, enabled: false }), false); + assert.equal(shouldUseSynthetic(50, { ...defaultSettings, realActiveThreshold: 40 }), false); + assert.equal(computeActivePlayersCount(10, { ...defaultSettings, displayActiveTarget: 80 }), 80); + }); + + test('synthetic activity is Playing-only with unique handles from personas', () => { + const items = buildSyntheticActivityFromPersonas(personas, 12, 1_700_000_000_000); assert.equal(items.length, 12); assert.ok(items.every((i) => i.synthetic)); assert.ok(items.every((i) => i.statusLabel === 'Playing')); @@ -62,21 +124,42 @@ describe('marketingService helpers', () => { assert.equal(new Set(items.map((i) => i.publicId)).size, items.length); }); - test('computeActivePlayersCount merges real + synthetic boost', () => { - const count = computeActivePlayersCount(20, 1_700_000_000_000); - assert.ok(count > 20); - assert.ok(count >= 180); - }); - - test('synthetic withdrawals pad feed', () => { - const items = buildSyntheticWithdrawals(12, 1_700_000_000_000); + test('synthetic withdrawals pad feed from personas', () => { + const items = buildSyntheticWithdrawalsFromPersonas(personas, 12, 1_700_000_000_000); assert.equal(items.length, 12); assert.ok(items.every((i) => i.statusLabel === 'Completed')); }); test('merge with empty real still fills from synthetic', () => { - const synthetic = buildSyntheticActivity(12, 1_700_000_000_000); + const synthetic = buildSyntheticActivityFromPersonas(personas, 12, 1_700_000_000_000); const merged = mergeFeedItems([], synthetic, 12); assert.equal(merged.length, 12); }); + + test('seed handles include legacy marketing_fallback set', () => { + const seed = [ + '7a***k2', + '9c***m1', + '3f***p8', + 'b2***q4', + 'e8***t6', + '1d***w9', + '5h***n3', + 'c4***r7', + '8j***v5', + '2m***x0', + '6p***y1', + '0s***z8', + '4n***a3', + 'd7***b5', + 'f1***c9', + 'a9***d2', + 'g3***e4', + 'h6***f7', + 'i2***g1', + 'j8***h6', + ]; + assert.equal(seed.length, 20); + assert.ok(seed.every((h) => /^[a-zA-Z0-9]{2}\*\*\*[a-zA-Z0-9]{2}$/.test(h))); + }); }); diff --git a/backend/src/validation/adminResourceSchemas.ts b/backend/src/validation/adminResourceSchemas.ts index 8947fc08..5781bd3f 100644 --- a/backend/src/validation/adminResourceSchemas.ts +++ b/backend/src/validation/adminResourceSchemas.ts @@ -230,6 +230,41 @@ export const soloEncouragementConfigBodySchema = atLeastOneField( }) ); +// —— Marketing Live Activity —— + +export const marketingLiveActivitySettingsBodySchema = atLeastOneField( + z.object({ + enabled: z.boolean().optional(), + realActiveThreshold: z.number().int().positive().optional(), + maxSyntheticEntries: z.number().int().min(0).max(100).optional(), + displayActiveTarget: z.number().int().positive().optional(), + activeWindowMinutes: z.number().int().positive().max(1440).optional(), + feedRealFetch: z.number().int().positive().max(100).optional(), + clientRefreshSeconds: z.number().int().min(10).max(120).optional(), + listRotateSeconds: z.number().int().min(5).max(60).optional(), + cacheTtlSeconds: z.number().int().positive().max(300).optional(), + }) +); + +const marketingPublicIdSchema = z + .string() + .trim() + .regex(/^[a-zA-Z0-9]{2}\*\*\*[a-zA-Z0-9]{2}$/, 'Invalid publicId format (expected e.g. 7a***k2)'); + +export const marketingPersonaCreateBodySchema = z.object({ + publicId: marketingPublicIdSchema, + isActive: z.boolean().optional(), + sortOrder: z.number().int().optional(), +}); + +export const marketingPersonaUpdateBodySchema = atLeastOneField( + z.object({ + publicId: marketingPublicIdSchema.optional(), + isActive: z.boolean().optional(), + sortOrder: z.number().int().optional(), + }) +); + // —— Support —— export const supportConversationUpdateBodySchema = atLeastOneField( diff --git a/prediqo_mobile/lib/data/models/marketing_models.dart b/prediqo_mobile/lib/data/models/marketing_models.dart index 8deb92c9..c7a32eb3 100644 --- a/prediqo_mobile/lib/data/models/marketing_models.dart +++ b/prediqo_mobile/lib/data/models/marketing_models.dart @@ -61,10 +61,18 @@ class MarketingActivityFeed { const MarketingActivityFeed({ required this.items, required this.activePlayersCount, + this.clientRefreshSeconds, + this.listRotateSeconds, + this.syntheticEnabled, }); final List items; final int activePlayersCount; + /// Server hint for network poll (seconds). Null when offline fallback. + final int? clientRefreshSeconds; + /// Server hint for local list rotation (seconds). Null when offline fallback. + final int? listRotateSeconds; + final bool? syntheticEnabled; factory MarketingActivityFeed.fromJson(Map json) { final list = json['items']; @@ -78,6 +86,11 @@ class MarketingActivityFeed { return MarketingActivityFeed( items: items, activePlayersCount: (json['activePlayersCount'] as num?)?.toInt() ?? 0, + clientRefreshSeconds: (json['clientRefreshSeconds'] as num?)?.toInt(), + listRotateSeconds: (json['listRotateSeconds'] as num?)?.toInt(), + syntheticEnabled: json['syntheticEnabled'] is bool + ? json['syntheticEnabled'] as bool + : null, ); } } diff --git a/prediqo_mobile/lib/data/repositories/marketing_repository_impl.dart b/prediqo_mobile/lib/data/repositories/marketing_repository_impl.dart index b9c98e6b..201b8d9d 100644 --- a/prediqo_mobile/lib/data/repositories/marketing_repository_impl.dart +++ b/prediqo_mobile/lib/data/repositories/marketing_repository_impl.dart @@ -44,7 +44,7 @@ class _Store { } } -/// Public marketing reads. On failure, returns local synthetic content. +/// Public marketing reads. On failure, returns empty (never invents fictives). class MarketingRepositoryImpl implements MarketingRepository { MarketingRepositoryImpl(this._api); @@ -89,7 +89,12 @@ class MarketingRepositoryImpl implements MarketingRepository { final res = await _api.dio.get>('/api/v1/marketing/daily-stats'); return MarketingDailyStats.fromJson(res.data ?? {}); } catch (_) { - return marketingFallbackStats(); + final day = DateTime.now().toUtc().toIso8601String().substring(0, 10); + return MarketingDailyStats( + uniquePlayersToday: 0, + totalParticipationsToday: 0, + day: day, + ); } } @@ -97,14 +102,12 @@ class MarketingRepositoryImpl implements MarketingRepository { try { final res = await _api.dio.get('/api/v1/marketing/activity-feed'); final data = res.data; - if (data is! Map) return marketingFallbackActivityFeed(); - final feed = MarketingActivityFeed.fromJson(Map.from(data)); - if (feed.items.isEmpty) return marketingFallbackActivityFeed(); - return feed; + if (data is! Map) return emptyMarketingActivityFeed; + return MarketingActivityFeed.fromJson(Map.from(data)); } on DioException { - return marketingFallbackActivityFeed(); + return emptyMarketingActivityFeed; } catch (_) { - return marketingFallbackActivityFeed(); + return emptyMarketingActivityFeed; } } @@ -113,13 +116,13 @@ class MarketingRepositoryImpl implements MarketingRepository { final res = await _api.dio.get('/api/v1/marketing/withdrawal-feed'); final data = res.data; final list = data is Map ? data['items'] : null; - if (list is! List || list.isEmpty) return marketingFallbackWithdrawals(); + if (list is! List) return const []; return list .whereType() .map((e) => MarketingWithdrawalItem.fromJson(Map.from(e))) .toList(); } catch (_) { - return marketingFallbackWithdrawals(); + return const []; } } } diff --git a/prediqo_mobile/lib/features/welcome/presentation/welcome_screen.dart b/prediqo_mobile/lib/features/welcome/presentation/welcome_screen.dart index 87509a20..d27d664f 100644 --- a/prediqo_mobile/lib/features/welcome/presentation/welcome_screen.dart +++ b/prediqo_mobile/lib/features/welcome/presentation/welcome_screen.dart @@ -37,10 +37,9 @@ class WelcomeScreen extends StatefulWidget { } class _WelcomeScreenState extends State { - /// Network refresh for marketing feeds (cached server-side too). - static const _marketingPollInterval = Duration(seconds: 30); - /// Local rotation of visible Live Activity rows (no extra network). - static const _activityRotateInterval = Duration(seconds: 8); + /// Defaults when API omits refresh hints (offline fallback). + static const _defaultPollSeconds = 30; + static const _defaultRotateSeconds = 8; static const _activityWindowSize = 5; bool _updateAvailable = false; @@ -52,6 +51,8 @@ class _WelcomeScreenState extends State { int _activePlayersCount = 0; int _activityGeneration = 0; final Set _recentlyShownIds = {}; + int _pollSeconds = _defaultPollSeconds; + int _rotateSeconds = _defaultRotateSeconds; bool _adsLoading = true; bool _gamesLoading = true; @@ -69,6 +70,39 @@ class _WelcomeScreenState extends State { Timer? _marketingPoll; Timer? _activityRotate; + static int _clampPollSeconds(int? value) { + final v = value ?? _defaultPollSeconds; + return v.clamp(10, 120); + } + + static int _clampRotateSeconds(int? value) { + final v = value ?? _defaultRotateSeconds; + return v.clamp(5, 60); + } + + void _restartMarketingTimers({int? pollSeconds, int? rotateSeconds}) { + final nextPoll = _clampPollSeconds(pollSeconds ?? _pollSeconds); + final nextRotate = _clampRotateSeconds(rotateSeconds ?? _rotateSeconds); + final pollChanged = nextPoll != _pollSeconds || _marketingPoll == null; + final rotateChanged = nextRotate != _rotateSeconds || _activityRotate == null; + _pollSeconds = nextPoll; + _rotateSeconds = nextRotate; + if (pollChanged) { + _marketingPoll?.cancel(); + _marketingPoll = Timer.periodic(Duration(seconds: _pollSeconds), (_) { + if (!mounted) return; + _loadMarketing(force: false); + }); + } + if (rotateChanged) { + _activityRotate?.cancel(); + _activityRotate = Timer.periodic(Duration(seconds: _rotateSeconds), (_) { + if (!mounted || _activityPool.isEmpty) return; + setState(_rotateActivityVisible); + }); + } + } + @override void initState() { super.initState(); @@ -89,6 +123,8 @@ class _WelcomeScreenState extends State { if (feed != null && feed.items.isNotEmpty) { _activityPool = feed.items; _activePlayersCount = feed.activePlayersCount; + _pollSeconds = _clampPollSeconds(feed.clientRefreshSeconds); + _rotateSeconds = _clampRotateSeconds(feed.listRotateSeconds); _rotateActivityVisible(); _activityLoading = false; } @@ -99,14 +135,7 @@ class _WelcomeScreenState extends State { } } _load(); - _marketingPoll = Timer.periodic(_marketingPollInterval, (_) { - if (!mounted) return; - _loadMarketing(force: false); - }); - _activityRotate = Timer.periodic(_activityRotateInterval, (_) { - if (!mounted || _activityPool.isEmpty) return; - setState(_rotateActivityVisible); - }); + _restartMarketingTimers(); WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; _checkAppUpdate(); @@ -216,10 +245,9 @@ class _WelcomeScreenState extends State { Future _loadActivity({bool force = false}) { if (!sl.isRegistered()) { setState(() { - final feed = marketingFallbackActivityFeed(); - _activityPool = feed.items; - _activePlayersCount = feed.activePlayersCount; - _rotateActivityVisible(); + _activityPool = const []; + _activePlayersCount = 0; + _activityVisible = const []; _activityLoading = false; }); return Future.value(); @@ -240,17 +268,14 @@ class _WelcomeScreenState extends State { _rotateActivityVisible(); _activityLoading = false; }); + _restartMarketingTimers( + pollSeconds: feed.clientRefreshSeconds, + rotateSeconds: feed.listRotateSeconds, + ); } catch (_) { if (!mounted) return; - setState(() { - if (_activityPool.isEmpty) { - final feed = marketingFallbackActivityFeed(); - _activityPool = feed.items; - _activePlayersCount = feed.activePlayersCount; - _rotateActivityVisible(); - } - _activityLoading = false; - }); + // Keep last good pool if any; otherwise stay empty (no invented fictives). + setState(() => _activityLoading = false); } }(); _activityInFlight = future.whenComplete(() => _activityInFlight = null); @@ -260,7 +285,7 @@ class _WelcomeScreenState extends State { Future _loadWithdrawals({bool force = false}) { if (!sl.isRegistered()) { setState(() { - _withdrawals = marketingFallbackWithdrawals(); + _withdrawals = const []; _withdrawalsLoading = false; }); return Future.value(); @@ -281,12 +306,8 @@ class _WelcomeScreenState extends State { }); } catch (_) { if (!mounted) return; - setState(() { - if (_withdrawals.isEmpty) { - _withdrawals = marketingFallbackWithdrawals(); - } - _withdrawalsLoading = false; - }); + // Keep last good list if any; otherwise stay empty. + setState(() => _withdrawalsLoading = false); } }(); _withdrawalsInFlight = diff --git a/prediqo_mobile/lib/features/welcome/utils/marketing_fallback.dart b/prediqo_mobile/lib/features/welcome/utils/marketing_fallback.dart index cbd6b670..2118c223 100644 --- a/prediqo_mobile/lib/features/welcome/utils/marketing_fallback.dart +++ b/prediqo_mobile/lib/features/welcome/utils/marketing_fallback.dart @@ -1,92 +1,15 @@ -/// Local synthetic marketing content when the API is unreachable or not yet deployed. +/// Welcome Live Activity helpers. +/// +/// No local synthetic handles/amounts: marketing content comes from the API/DB +/// only. Offline or failed fetches stay empty so the UI never invents social proof. library; import '../../../data/models/marketing_models.dart'; -const _handles = [ - '7a***k2', - '9c***m1', - '3f***p8', - 'b2***q4', - 'e8***t6', - '1d***w9', - '5h***n3', - 'c4***r7', - '8j***v5', - '2m***x0', - '6p***y1', - '0s***z8', - '4n***a3', - 'd7***b5', - 'f1***c9', - 'a9***d2', -]; - -const _withdrawals = [20, 35, 50, 80, 100, 120, 200, 250]; - -int _slot([DateTime? now]) => - (now ?? DateTime.now().toUtc()).millisecondsSinceEpoch ~/ 10000; - -MarketingDailyStats marketingFallbackStats([DateTime? now]) { - final slot = _slot(now); - final day = (now ?? DateTime.now().toUtc()).toIso8601String().substring(0, 10); - return MarketingDailyStats( - uniquePlayersToday: 18 + (slot % 40), - totalParticipationsToday: 60 + (slot % 90), - day: day, - ); -} - -int marketingFallbackActiveCount([DateTime? now]) { - final slot = _slot(now); - return 180 + (slot % 90) + 12; -} - -MarketingActivityFeed marketingFallbackActivityFeed([DateTime? now]) { - return MarketingActivityFeed( - items: marketingFallbackActivity(now), - activePlayersCount: marketingFallbackActiveCount(now), - ); -} - -/// Playing-only rows (no Won, no stake amounts). -List marketingFallbackActivity([DateTime? now]) { - final slot = _slot(now); - final t = now ?? DateTime.now().toUtc(); - final used = {}; - final out = []; - for (var i = 0; out.length < 16 && i < 40; i++) { - final handle = _handles[(slot * 3 + i * 5) % _handles.length]; - if (!used.add(handle)) continue; - out.add( - MarketingActivityItem( - id: 'local-act-$slot-$i', - publicId: handle, - kind: 'bet', - amountLabel: '0', - statusLabel: 'Playing', - createdAt: t.subtract(Duration(seconds: i * 20)).toIso8601String(), - synthetic: true, - ), - ); - } - return out; -} - -List marketingFallbackWithdrawals([DateTime? now]) { - final slot = _slot(now); - final t = now ?? DateTime.now().toUtc(); - return List.generate(8, (i) { - return MarketingWithdrawalItem( - id: 'local-wd-$slot-$i', - publicId: _handles[(slot + i * 2) % _handles.length], - amountLabel: '${_withdrawals[(slot + i * 5) % _withdrawals.length]}', - statusLabel: 'Completed', - createdAt: t.subtract(Duration(seconds: i * 90)).toIso8601String(), - synthetic: true, - ); - }); -} +const emptyMarketingActivityFeed = MarketingActivityFeed( + items: [], + activePlayersCount: 0, +); /// Rotate a visible window from [pool], avoiding recently shown publicIds. List rotateActivityWindow({ diff --git a/prediqo_mobile/test/support/e2e_fixtures.dart b/prediqo_mobile/test/support/e2e_fixtures.dart index 553f4b8f..46c0e2d5 100644 --- a/prediqo_mobile/test/support/e2e_fixtures.dart +++ b/prediqo_mobile/test/support/e2e_fixtures.dart @@ -550,6 +550,8 @@ class FakeMarketingRepository implements MarketingRepository { Future getActivityFeed({bool force = false}) async => const MarketingActivityFeed( activePlayersCount: 250, + clientRefreshSeconds: 30, + listRotateSeconds: 8, items: [ MarketingActivityItem( id: 'a1', diff --git a/prediqo_mobile/test/welcome_section_load_test.dart b/prediqo_mobile/test/welcome_section_load_test.dart index d4d6e18f..44397a39 100644 --- a/prediqo_mobile/test/welcome_section_load_test.dart +++ b/prediqo_mobile/test/welcome_section_load_test.dart @@ -265,11 +265,9 @@ void main() { if (sl.isRegistered()) await sl.reset(); }); - test('fallback activity is Playing-only without stakes', () { - final items = marketingFallbackActivity(DateTime.utc(2026, 10, 17, 12)); - expect(items, isNotEmpty); - expect(items.every((e) => e.statusLabel == 'Playing'), isTrue); - expect(items.every((e) => e.kind != 'win'), isTrue); + test('empty marketing fallback has no invented activity', () { + expect(emptyMarketingActivityFeed.items, isEmpty); + expect(emptyMarketingActivityFeed.activePlayersCount, 0); }); test('rotateActivityWindow avoids recently shown ids when possible', () { @@ -371,7 +369,7 @@ void main() { await tester.pump(); }); - testWidgets('Welcome marketing falls back without connection banners', (tester) async { + testWidgets('Welcome marketing soft-fails empty without connection banners', (tester) async { _tallSurface(tester); final ads = _ControllableAds( cached: const [ @@ -396,7 +394,9 @@ void main() { await _pumpFrames(tester); expect(find.textContaining('Connection failed'), findsNothing); - expect(find.byKey(const Key('welcome_activity_ticker')), findsOneWidget); + // Empty Live Activity (no invented fictives) — ticker collapses when pool is empty. + expect(find.byKey(const Key('welcome_activity_ticker')), findsNothing); + expect(find.textContaining('Playing'), findsNothing); expect(find.byKey(const Key('welcome_stats_strip')), findsNothing); await tester.pumpWidget(const SizedBox.shrink()); diff --git a/prediqo_web/src/app/router/router.tsx b/prediqo_web/src/app/router/router.tsx index 9c4b9da6..62fe15d7 100644 --- a/prediqo_web/src/app/router/router.tsx +++ b/prediqo_web/src/app/router/router.tsx @@ -29,6 +29,7 @@ import { ReferralFraudDashboardPage } from '../../features/referral/ReferralFrau import { TestWalletAdminPage } from '../../features/test-wallet/TestWalletAdminPage'; import { ShareCardsAdminPage } from '../../features/share-cards/ShareCardsAdminPage'; import { SoloEncouragementAdminPage } from '../../features/solo-encouragement/SoloEncouragementAdminPage'; +import { MarketingAdminPage } from '../../features/marketing/MarketingAdminPage'; import { ShareResultVerifyPage } from '../../features/share-cards/ShareResultVerifyPage'; import { SecurityAdminPage } from '../../features/security/SecurityAdminPage'; import { ReportsHubPage } from '../../features/reports/ReportsHubPage'; @@ -117,6 +118,7 @@ export const router = createBrowserRouter([ { path: 'admin/test-wallet', element: }, { path: 'admin/share-cards', element: }, { path: 'admin/solo-encouragement', element: }, + { path: 'admin/marketing', element: }, { path: 'admin/countries', element: }, { path: 'admin/network', element: }, { path: 'admin/rbac', element: }, diff --git a/prediqo_web/src/features/marketing/MarketingAdminPage.tsx b/prediqo_web/src/features/marketing/MarketingAdminPage.tsx new file mode 100644 index 00000000..cf6f8778 --- /dev/null +++ b/prediqo_web/src/features/marketing/MarketingAdminPage.tsx @@ -0,0 +1,402 @@ +/** + * Admin: Live Activity marketing settings + synthetic persona CRUD. + */ +import { + Alert, + Box, + Button, + Card, + CardContent, + Chip, + FormControlLabel, + IconButton, + Stack, + Switch, + Table, + TableBody, + TableCell, + TableHead, + TableRow, + TextField, + Typography, +} from '@mui/material'; +import AddRoundedIcon from '@mui/icons-material/AddRounded'; +import DeleteOutlineRoundedIcon from '@mui/icons-material/DeleteOutlineRounded'; +import CampaignRoundedIcon from '@mui/icons-material/CampaignRounded'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { api } from '../../shared/services/api'; +import { ScrollableTable } from '../../shared/components/ScrollableTable'; + +type LiveActivitySettings = { + enabled: boolean; + realActiveThreshold: number; + maxSyntheticEntries: number; + displayActiveTarget: number; + activeWindowMinutes: number; + feedRealFetch: number; + clientRefreshSeconds: number; + listRotateSeconds: number; + cacheTtlSeconds: number; + updatedAt: string; +}; + +type Persona = { + id: string; + publicId: string; + isActive: boolean; + sortOrder: number; + createdAt: string; + updatedAt: string; +}; + +export function MarketingAdminPage() { + const { t } = useTranslation(); + const qc = useQueryClient(); + const [form, setForm] = useState(null); + const [newPublicId, setNewPublicId] = useState(''); + const [newSortOrder, setNewSortOrder] = useState(0); + + const settingsQuery = useQuery({ + queryKey: ['admin-marketing-settings'], + queryFn: async () => { + const res = await api.get( + '/api/v1/admin/marketing/live-activity-settings' + ); + return res.data; + }, + }); + + const personasQuery = useQuery({ + queryKey: ['admin-marketing-personas'], + queryFn: async () => { + const res = await api.get('/api/v1/admin/marketing/personas'); + return res.data; + }, + }); + + useEffect(() => { + if (settingsQuery.data) setForm(settingsQuery.data); + }, [settingsQuery.data]); + + const saveMut = useMutation({ + mutationFn: async (body: Partial) => { + const res = await api.patch( + '/api/v1/admin/marketing/live-activity-settings', + body + ); + return res.data; + }, + onSuccess: (data) => { + setForm(data); + void qc.invalidateQueries({ queryKey: ['admin-marketing-settings'] }); + }, + }); + + const createMut = useMutation({ + mutationFn: async () => { + const res = await api.post('/api/v1/admin/marketing/personas', { + publicId: newPublicId.trim(), + isActive: true, + sortOrder: newSortOrder, + }); + return res.data; + }, + onSuccess: () => { + setNewPublicId(''); + void qc.invalidateQueries({ queryKey: ['admin-marketing-personas'] }); + }, + }); + + const patchPersonaMut = useMutation({ + mutationFn: async (args: { id: string; patch: Partial }) => { + const res = await api.patch( + `/api/v1/admin/marketing/personas/${args.id}`, + { + publicId: args.patch.publicId, + isActive: args.patch.isActive, + sortOrder: args.patch.sortOrder, + } + ); + return res.data; + }, + onSuccess: () => { + void qc.invalidateQueries({ queryKey: ['admin-marketing-personas'] }); + }, + }); + + const deleteMut = useMutation({ + mutationFn: async (id: string) => { + await api.delete(`/api/v1/admin/marketing/personas/${id}`); + }, + onSuccess: () => { + void qc.invalidateQueries({ queryKey: ['admin-marketing-personas'] }); + }, + }); + + const dirty = + !!form && + !!settingsQuery.data && + (form.enabled !== settingsQuery.data.enabled || + form.realActiveThreshold !== settingsQuery.data.realActiveThreshold || + form.maxSyntheticEntries !== settingsQuery.data.maxSyntheticEntries || + form.displayActiveTarget !== settingsQuery.data.displayActiveTarget || + form.activeWindowMinutes !== settingsQuery.data.activeWindowMinutes || + form.feedRealFetch !== settingsQuery.data.feedRealFetch || + form.clientRefreshSeconds !== settingsQuery.data.clientRefreshSeconds || + form.listRotateSeconds !== settingsQuery.data.listRotateSeconds || + form.cacheTtlSeconds !== settingsQuery.data.cacheTtlSeconds); + + if (settingsQuery.isLoading || !form) { + return {t('admin.marketing.loading')}; + } + + if (settingsQuery.isError) { + return ( + + {t('admin.marketing.loadFailed')} + + ); + } + + return ( + + + + + + {t('admin.marketing.title')} + + + {dirty && ( + + )} + + {t('admin.marketing.subtitle')} + + + + + + setForm({ ...form, enabled: checked })} + /> + } + label={t('admin.marketing.enableFeature')} + /> + + + setForm({ ...form, realActiveThreshold: Number(e.target.value) || 0 }) + } + helperText={t('admin.marketing.realActiveThresholdHelper')} + fullWidth + /> + + setForm({ ...form, displayActiveTarget: Number(e.target.value) || 0 }) + } + helperText={t('admin.marketing.displayActiveTargetHelper')} + fullWidth + /> + + setForm({ ...form, maxSyntheticEntries: Number(e.target.value) || 0 }) + } + helperText={t('admin.marketing.maxSyntheticEntriesHelper')} + fullWidth + /> + + + + setForm({ ...form, clientRefreshSeconds: Number(e.target.value) || 0 }) + } + helperText={t('admin.marketing.clientRefreshSecondsHelper')} + fullWidth + /> + + setForm({ ...form, listRotateSeconds: Number(e.target.value) || 0 }) + } + helperText={t('admin.marketing.listRotateSecondsHelper')} + fullWidth + /> + + setForm({ ...form, activeWindowMinutes: Number(e.target.value) || 0 }) + } + fullWidth + /> + + {saveMut.isError && ( + + {(saveMut.error as { response?: { data?: { error?: string } } })?.response?.data + ?.error ?? t('admin.marketing.saveFailed')} + + )} + {saveMut.isSuccess && !dirty && ( + {t('admin.marketing.saved')} + )} + {dirty && {t('admin.marketing.unsavedHint')}} + + + + + + + + + {t('admin.marketing.personas')} + + + + + setNewPublicId(e.target.value)} + placeholder="7a***k2" + helperText={t('admin.marketing.publicIdHelper')} + sx={{ minWidth: 180 }} + /> + setNewSortOrder(Number(e.target.value) || 0)} + sx={{ width: 120 }} + /> + + + {createMut.isError && ( + + {(createMut.error as { response?: { data?: { error?: string } } })?.response?.data + ?.error ?? t('admin.marketing.saveFailed')} + + )} + + + + + + + + + {t('admin.marketing.publicId')} + {t('admin.marketing.sortOrder')} + {t('admin.marketing.active')} + {t('admin.marketing.actions')} + + + + {(personasQuery.data ?? []).map((p) => ( + + + {p.publicId} + + + + patchPersonaMut.mutate({ + id: p.id, + patch: { sortOrder: Number(e.target.value) || 0 }, + }) + } + sx={{ width: 88 }} + /> + + + + patchPersonaMut.mutate({ id: p.id, patch: { isActive: checked } }) + } + /> + + + { + if (window.confirm(t('admin.marketing.deleteConfirm'))) { + deleteMut.mutate(p.id); + } + }} + > + + + + + ))} + {(personasQuery.data ?? []).length === 0 && ( + + + + {t('admin.marketing.noPersonas')} + + + + )} + +
+
+
+
+ ); +} diff --git a/prediqo_web/src/features/options/OptionsPage.tsx b/prediqo_web/src/features/options/OptionsPage.tsx index 7189b707..d41da2a7 100644 --- a/prediqo_web/src/features/options/OptionsPage.tsx +++ b/prediqo_web/src/features/options/OptionsPage.tsx @@ -37,6 +37,7 @@ type OptionCardKey = | 'testWallet' | 'shareCards' | 'soloEncouragement' + | 'marketing' | 'security' | 'network' | 'faq' @@ -147,6 +148,15 @@ const OPTION_CARDS: OptionCardConfig[] = [ bg: 'rgba(236,72,153,0.14)', border: 'rgba(236,72,153,0.22)', }, + { + key: 'marketing', + path: '/admin/marketing', + icon: CampaignRoundedIcon, + badgeKey: 'catalog', + badgeColor: 'success', + bg: 'rgba(255,152,0,0.14)', + border: 'rgba(255,152,0,0.28)', + }, { key: 'security', path: '/admin/security', diff --git a/prediqo_web/src/shared/auth/permissions.ts b/prediqo_web/src/shared/auth/permissions.ts index 57d2c52c..9ae2c179 100644 --- a/prediqo_web/src/shared/auth/permissions.ts +++ b/prediqo_web/src/shared/auth/permissions.ts @@ -69,6 +69,7 @@ export const ADMIN_PAGE_PERMISSIONS: Record = { '/admin/test-wallet': 'admin.test_wallet.view', '/admin/share-cards': 'admin.share_cards.view', '/admin/solo-encouragement': 'admin.solo_encouragement.view', + '/admin/marketing': 'admin.games.view', '/admin/countries': 'admin.countries.view', '/admin/network': 'admin.network.view', '/admin/rbac': 'admin.rbac.view', @@ -89,6 +90,7 @@ export const OPTIONS_CARD_PERMISSIONS: Record = { testWallet: 'admin.test_wallet.view', shareCards: 'admin.share_cards.view', soloEncouragement: 'admin.solo_encouragement.view', + marketing: 'admin.games.view', security: 'admin.security.view', network: 'admin.network.view', faq: 'admin.faq.view', diff --git a/prediqo_web/src/shared/i18n/locales/en.ts b/prediqo_web/src/shared/i18n/locales/en.ts index 0753f6ac..1eeab46d 100644 --- a/prediqo_web/src/shared/i18n/locales/en.ts +++ b/prediqo_web/src/shared/i18n/locales/en.ts @@ -1022,6 +1022,10 @@ export const en = { title: 'Solo encouragement', description: 'Bonus refunds for users who keep playing alone with real funds (Main/Bonus).', }, + marketing: { + title: 'Marketing Live Activity', + description: 'Synthetic personas, active-player threshold, and Welcome feed refresh hints.', + }, security: { title: 'Security', description: 'Integrity checks, security alerts, in-app notifications, and approved ledger credits.', @@ -2153,6 +2157,43 @@ export const en = { saved: 'Settings saved.', readOnlyHint: 'Read-only access — you cannot change share card settings.', }, + marketing: { + title: 'Marketing Live Activity', + enabled: 'Enabled', + disabled: 'Disabled', + unsaved: 'Unsaved', + unsavedHint: 'Changes are not active until you click Save settings.', + subtitle: + 'When real active players are below the threshold, Welcome Live Activity is padded with synthetic personas. Official daily stats never include fictives.', + loading: 'Loading marketing settings…', + loadFailed: 'Failed to load marketing settings.', + enableFeature: 'Enable synthetic Live Activity', + realActiveThreshold: 'Real active threshold', + realActiveThresholdHelper: 'Use synthetics only while real distinct players are below this count', + displayActiveTarget: 'Display active target', + displayActiveTargetHelper: 'Title counter target when synthetics are active', + maxSyntheticEntries: 'Max synthetic entries', + maxSyntheticEntriesHelper: 'Cap of fictive rows added to the Playing list', + clientRefreshSeconds: 'Client refresh (seconds)', + clientRefreshSecondsHelper: 'Mobile network poll interval (10–120)', + listRotateSeconds: 'List rotate (seconds)', + listRotateSecondsHelper: 'Local UI rotation interval (5–60)', + activeWindowMinutes: 'Active window (minutes)', + save: 'Save settings', + saving: 'Saving…', + saved: 'Settings saved.', + saveFailed: 'Save failed', + personas: 'Synthetic personas', + publicId: 'Public ID', + publicIdHelper: 'Masked handle format, e.g. 7a***k2', + sortOrder: 'Sort', + active: 'Active', + actions: 'Actions', + addPersona: 'Add persona', + delete: 'Delete', + deleteConfirm: 'Delete this persona?', + noPersonas: 'No personas yet.', + }, soloEncouragement: { title: 'Solo encouragement bonus', enabled: 'Enabled', diff --git a/prediqo_web/src/shared/i18n/locales/fr.ts b/prediqo_web/src/shared/i18n/locales/fr.ts index aa72e332..68940bbb 100644 --- a/prediqo_web/src/shared/i18n/locales/fr.ts +++ b/prediqo_web/src/shared/i18n/locales/fr.ts @@ -1038,6 +1038,11 @@ export const fr = { description: 'Bonus de remboursement pour les joueurs qui continuent seuls avec des fonds réels (Main/Bonus).', }, + marketing: { + title: 'Marketing Live Activity', + description: + 'Personas synthétiques, seuil de joueurs actifs et indices de refresh pour Welcome.', + }, security: { title: 'Sécurité', description: 'Contrôles d’intégrité, alertes sécurité, notifications in-app et crédits grand livre approuvés.', @@ -2171,6 +2176,44 @@ export const fr = { saved: 'Paramètres enregistrés.', readOnlyHint: 'Accès lecture seule — vous ne pouvez pas modifier les paramètres Share Cards.', }, + marketing: { + title: 'Marketing Live Activity', + enabled: 'Activé', + disabled: 'Désactivé', + unsaved: 'Non enregistré', + unsavedHint: 'Les changements ne sont actifs qu’après « Enregistrer les paramètres ».', + subtitle: + 'Quand les joueurs actifs réels sont sous le seuil, Live Activity Welcome est complété avec des personas synthétiques. Les stats quotidiennes officielles n’incluent jamais de fictifs.', + loading: 'Chargement des paramètres marketing…', + loadFailed: 'Échec du chargement des paramètres marketing.', + enableFeature: 'Activer Live Activity synthétique', + realActiveThreshold: 'Seuil joueurs actifs réels', + realActiveThresholdHelper: + 'Utiliser les fictifs seulement si les joueurs distincts réels sont sous ce seuil', + displayActiveTarget: 'Cible compteur affiché', + displayActiveTargetHelper: 'Cible du compteur titre quand les fictifs sont actifs', + maxSyntheticEntries: 'Max entrées synthétiques', + maxSyntheticEntriesHelper: 'Plafond de lignes fictives ajoutées à la liste Playing', + clientRefreshSeconds: 'Refresh client (secondes)', + clientRefreshSecondsHelper: 'Intervalle de poll réseau mobile (10–120)', + listRotateSeconds: 'Rotation liste (secondes)', + listRotateSecondsHelper: 'Intervalle de rotation UI locale (5–60)', + activeWindowMinutes: 'Fenêtre active (minutes)', + save: 'Enregistrer les paramètres', + saving: 'Enregistrement…', + saved: 'Paramètres enregistrés.', + saveFailed: 'Échec de l’enregistrement', + personas: 'Personas synthétiques', + publicId: 'ID public', + publicIdHelper: 'Format masqué, ex. 7a***k2', + sortOrder: 'Ordre', + active: 'Actif', + actions: 'Actions', + addPersona: 'Ajouter un persona', + delete: 'Supprimer', + deleteConfirm: 'Supprimer ce persona ?', + noPersonas: 'Aucun persona pour le moment.', + }, soloEncouragement: { title: 'Bonus d’encouragement solo', enabled: 'Activé',