After persist the live activity data for welcome
This commit is contained in:
parent
d02e0d281b
commit
110c1c3e83
@ -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<void> {
|
||||
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<void> {
|
||||
try {
|
||||
const settings = await marketingService.updateLiveActivitySettingsAdmin(
|
||||
req.body as Record<string, unknown>
|
||||
);
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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<MarketingLiveActivitySettings, 'updatedAt'> = {
|
||||
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<MarketingLiveActivitySettings> {
|
||||
const rows = await query<MarketingLiveActivitySettingsRow[]>(
|
||||
`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<MarketingLiveActivitySettings> {
|
||||
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<MarketingLiveActivitySettingsRow[]>(
|
||||
`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]);
|
||||
}
|
||||
100
backend/src/repositories/marketingPersonaRepository.ts
Normal file
100
backend/src/repositories/marketingPersonaRepository.ts
Normal file
@ -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<MarketingPersonaRow[]> {
|
||||
return query<MarketingPersonaRow[]>(
|
||||
`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<MarketingPersonaRow[]> {
|
||||
return query<MarketingPersonaRow[]>(
|
||||
`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<MarketingPersonaRow | null> {
|
||||
const rows = await query<MarketingPersonaRow[]>(
|
||||
`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<MarketingPersonaRow> {
|
||||
const rows = await query<MarketingPersonaRow[]>(
|
||||
`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<MarketingPersonaRow | null> {
|
||||
const existing = await getPersonaById(id);
|
||||
if (!existing) return null;
|
||||
|
||||
const rows = await query<MarketingPersonaRow[]>(
|
||||
`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<boolean> {
|
||||
const rows = await query<{ id: string }[]>(
|
||||
`DELETE FROM marketing_personas WHERE id = $1 RETURNING id`,
|
||||
[id]
|
||||
);
|
||||
return rows.length > 0;
|
||||
}
|
||||
@ -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);
|
||||
|
||||
@ -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<T> = { at: number; value: T };
|
||||
type CacheEntry<T> = { at: number; value: T; ttlMs: number };
|
||||
const cache = new Map<string, CacheEntry<unknown>>();
|
||||
|
||||
function cached<T>(key: string, factory: () => Promise<T>): Promise<T> {
|
||||
function cached<T>(key: string, ttlMs: number, factory: () => Promise<T>): Promise<T> {
|
||||
const hit = cache.get(key) as CacheEntry<T> | 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<MarketingLiveActivitySettings, 'enabled' | 'realActiveThreshold'>
|
||||
): 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<Pick<MarketingPersonaRow, 'public_id'>>,
|
||||
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<string>();
|
||||
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<Pick<MarketingPersonaRow, 'public_id'>>,
|
||||
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<T extends { id: string; publicId?: string }>(
|
||||
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<MarketingLiveActivitySettings> {
|
||||
return cached('live-activity-settings', 12_000, () => settingsRepository.getLiveActivitySettings());
|
||||
}
|
||||
|
||||
async function loadActivePersonasCached(
|
||||
ttlMs: number,
|
||||
limit: number
|
||||
): Promise<MarketingPersonaRow[]> {
|
||||
return cached(`active-personas:${limit}`, ttlMs, () =>
|
||||
personaRepository.listActivePersonas(Math.max(limit, 100))
|
||||
);
|
||||
}
|
||||
|
||||
export async function getDailyStats(): Promise<MarketingDailyStats> {
|
||||
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<MarketingActivityFeed> {
|
||||
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<MarketingLiveActivitySettings> {
|
||||
return settingsRepository.getLiveActivitySettings();
|
||||
}
|
||||
|
||||
export async function updateLiveActivitySettingsAdmin(
|
||||
patch: settingsRepository.LiveActivitySettingsPatch
|
||||
): Promise<MarketingLiveActivitySettings> {
|
||||
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<void> {
|
||||
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();
|
||||
}
|
||||
|
||||
@ -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)));
|
||||
});
|
||||
});
|
||||
|
||||
@ -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(
|
||||
|
||||
@ -61,10 +61,18 @@ class MarketingActivityFeed {
|
||||
const MarketingActivityFeed({
|
||||
required this.items,
|
||||
required this.activePlayersCount,
|
||||
this.clientRefreshSeconds,
|
||||
this.listRotateSeconds,
|
||||
this.syntheticEnabled,
|
||||
});
|
||||
|
||||
final List<MarketingActivityItem> 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<String, dynamic> 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -44,7 +44,7 @@ class _Store<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<Map<String, dynamic>>('/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<String, dynamic>.from(data));
|
||||
if (feed.items.isEmpty) return marketingFallbackActivityFeed();
|
||||
return feed;
|
||||
if (data is! Map) return emptyMarketingActivityFeed;
|
||||
return MarketingActivityFeed.fromJson(Map<String, dynamic>.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>()
|
||||
.map((e) => MarketingWithdrawalItem.fromJson(Map<String, dynamic>.from(e)))
|
||||
.toList();
|
||||
} catch (_) {
|
||||
return marketingFallbackWithdrawals();
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -37,10 +37,9 @@ class WelcomeScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _WelcomeScreenState extends State<WelcomeScreen> {
|
||||
/// 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<WelcomeScreen> {
|
||||
int _activePlayersCount = 0;
|
||||
int _activityGeneration = 0;
|
||||
final Set<String> _recentlyShownIds = {};
|
||||
int _pollSeconds = _defaultPollSeconds;
|
||||
int _rotateSeconds = _defaultRotateSeconds;
|
||||
|
||||
bool _adsLoading = true;
|
||||
bool _gamesLoading = true;
|
||||
@ -69,6 +70,39 @@ class _WelcomeScreenState extends State<WelcomeScreen> {
|
||||
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<WelcomeScreen> {
|
||||
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<WelcomeScreen> {
|
||||
}
|
||||
}
|
||||
_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<WelcomeScreen> {
|
||||
Future<void> _loadActivity({bool force = false}) {
|
||||
if (!sl.isRegistered<MarketingRepository>()) {
|
||||
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<WelcomeScreen> {
|
||||
_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<WelcomeScreen> {
|
||||
Future<void> _loadWithdrawals({bool force = false}) {
|
||||
if (!sl.isRegistered<MarketingRepository>()) {
|
||||
setState(() {
|
||||
_withdrawals = marketingFallbackWithdrawals();
|
||||
_withdrawals = const [];
|
||||
_withdrawalsLoading = false;
|
||||
});
|
||||
return Future.value();
|
||||
@ -281,12 +306,8 @@ class _WelcomeScreenState extends State<WelcomeScreen> {
|
||||
});
|
||||
} 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 =
|
||||
|
||||
@ -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<MarketingActivityItem> marketingFallbackActivity([DateTime? now]) {
|
||||
final slot = _slot(now);
|
||||
final t = now ?? DateTime.now().toUtc();
|
||||
final used = <String>{};
|
||||
final out = <MarketingActivityItem>[];
|
||||
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<MarketingWithdrawalItem> 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<MarketingActivityItem> rotateActivityWindow({
|
||||
|
||||
@ -550,6 +550,8 @@ class FakeMarketingRepository implements MarketingRepository {
|
||||
Future<MarketingActivityFeed> getActivityFeed({bool force = false}) async =>
|
||||
const MarketingActivityFeed(
|
||||
activePlayersCount: 250,
|
||||
clientRefreshSeconds: 30,
|
||||
listRotateSeconds: 8,
|
||||
items: [
|
||||
MarketingActivityItem(
|
||||
id: 'a1',
|
||||
|
||||
@ -265,11 +265,9 @@ void main() {
|
||||
if (sl.isRegistered<AppConfig>()) 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());
|
||||
|
||||
@ -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: <TestWalletAdminPage /> },
|
||||
{ path: 'admin/share-cards', element: <ShareCardsAdminPage /> },
|
||||
{ path: 'admin/solo-encouragement', element: <SoloEncouragementAdminPage /> },
|
||||
{ path: 'admin/marketing', element: <MarketingAdminPage /> },
|
||||
{ path: 'admin/countries', element: <CountriesAdminPage /> },
|
||||
{ path: 'admin/network', element: <NetworkStatusPage /> },
|
||||
{ path: 'admin/rbac', element: <RoleManagementPage /> },
|
||||
|
||||
402
prediqo_web/src/features/marketing/MarketingAdminPage.tsx
Normal file
402
prediqo_web/src/features/marketing/MarketingAdminPage.tsx
Normal file
@ -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<LiveActivitySettings | null>(null);
|
||||
const [newPublicId, setNewPublicId] = useState('');
|
||||
const [newSortOrder, setNewSortOrder] = useState(0);
|
||||
|
||||
const settingsQuery = useQuery({
|
||||
queryKey: ['admin-marketing-settings'],
|
||||
queryFn: async () => {
|
||||
const res = await api.get<LiveActivitySettings>(
|
||||
'/api/v1/admin/marketing/live-activity-settings'
|
||||
);
|
||||
return res.data;
|
||||
},
|
||||
});
|
||||
|
||||
const personasQuery = useQuery({
|
||||
queryKey: ['admin-marketing-personas'],
|
||||
queryFn: async () => {
|
||||
const res = await api.get<Persona[]>('/api/v1/admin/marketing/personas');
|
||||
return res.data;
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (settingsQuery.data) setForm(settingsQuery.data);
|
||||
}, [settingsQuery.data]);
|
||||
|
||||
const saveMut = useMutation({
|
||||
mutationFn: async (body: Partial<LiveActivitySettings>) => {
|
||||
const res = await api.patch<LiveActivitySettings>(
|
||||
'/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<Persona>('/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<Persona> }) => {
|
||||
const res = await api.patch<Persona>(
|
||||
`/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 <Typography sx={{ p: 2 }}>{t('admin.marketing.loading')}</Typography>;
|
||||
}
|
||||
|
||||
if (settingsQuery.isError) {
|
||||
return (
|
||||
<Alert severity="error" sx={{ m: 2 }}>
|
||||
{t('admin.marketing.loadFailed')}
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<Stack spacing={0.75} sx={{ mb: 2.5 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<CampaignRoundedIcon color="primary" />
|
||||
<Typography variant="h4" sx={{ fontWeight: 900 }}>
|
||||
{t('admin.marketing.title')}
|
||||
</Typography>
|
||||
<Chip
|
||||
size="small"
|
||||
label={form.enabled ? t('admin.marketing.enabled') : t('admin.marketing.disabled')}
|
||||
color={form.enabled ? 'success' : 'default'}
|
||||
/>
|
||||
{dirty && (
|
||||
<Chip size="small" label={t('admin.marketing.unsaved')} color="warning" variant="outlined" />
|
||||
)}
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.7 }}>{t('admin.marketing.subtitle')}</Typography>
|
||||
</Stack>
|
||||
|
||||
<Card sx={{ mb: 2.5 }}>
|
||||
<CardContent>
|
||||
<Stack spacing={2}>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={form.enabled}
|
||||
onChange={(_, checked) => setForm({ ...form, enabled: checked })}
|
||||
/>
|
||||
}
|
||||
label={t('admin.marketing.enableFeature')}
|
||||
/>
|
||||
<Stack direction={{ xs: 'column', md: 'row' }} spacing={2}>
|
||||
<TextField
|
||||
label={t('admin.marketing.realActiveThreshold')}
|
||||
type="number"
|
||||
value={form.realActiveThreshold}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, realActiveThreshold: Number(e.target.value) || 0 })
|
||||
}
|
||||
helperText={t('admin.marketing.realActiveThresholdHelper')}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.marketing.displayActiveTarget')}
|
||||
type="number"
|
||||
value={form.displayActiveTarget}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, displayActiveTarget: Number(e.target.value) || 0 })
|
||||
}
|
||||
helperText={t('admin.marketing.displayActiveTargetHelper')}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.marketing.maxSyntheticEntries')}
|
||||
type="number"
|
||||
value={form.maxSyntheticEntries}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, maxSyntheticEntries: Number(e.target.value) || 0 })
|
||||
}
|
||||
helperText={t('admin.marketing.maxSyntheticEntriesHelper')}
|
||||
fullWidth
|
||||
/>
|
||||
</Stack>
|
||||
<Stack direction={{ xs: 'column', md: 'row' }} spacing={2}>
|
||||
<TextField
|
||||
label={t('admin.marketing.clientRefreshSeconds')}
|
||||
type="number"
|
||||
value={form.clientRefreshSeconds}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, clientRefreshSeconds: Number(e.target.value) || 0 })
|
||||
}
|
||||
helperText={t('admin.marketing.clientRefreshSecondsHelper')}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.marketing.listRotateSeconds')}
|
||||
type="number"
|
||||
value={form.listRotateSeconds}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, listRotateSeconds: Number(e.target.value) || 0 })
|
||||
}
|
||||
helperText={t('admin.marketing.listRotateSecondsHelper')}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.marketing.activeWindowMinutes')}
|
||||
type="number"
|
||||
value={form.activeWindowMinutes}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, activeWindowMinutes: Number(e.target.value) || 0 })
|
||||
}
|
||||
fullWidth
|
||||
/>
|
||||
</Stack>
|
||||
{saveMut.isError && (
|
||||
<Alert severity="error">
|
||||
{(saveMut.error as { response?: { data?: { error?: string } } })?.response?.data
|
||||
?.error ?? t('admin.marketing.saveFailed')}
|
||||
</Alert>
|
||||
)}
|
||||
{saveMut.isSuccess && !dirty && (
|
||||
<Alert severity="success">{t('admin.marketing.saved')}</Alert>
|
||||
)}
|
||||
{dirty && <Alert severity="warning">{t('admin.marketing.unsavedHint')}</Alert>}
|
||||
<Box>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={!dirty || saveMut.isPending}
|
||||
onClick={() =>
|
||||
saveMut.mutate({
|
||||
enabled: form.enabled,
|
||||
realActiveThreshold: form.realActiveThreshold,
|
||||
maxSyntheticEntries: form.maxSyntheticEntries,
|
||||
displayActiveTarget: form.displayActiveTarget,
|
||||
activeWindowMinutes: form.activeWindowMinutes,
|
||||
feedRealFetch: form.feedRealFetch,
|
||||
clientRefreshSeconds: form.clientRefreshSeconds,
|
||||
listRotateSeconds: form.listRotateSeconds,
|
||||
cacheTtlSeconds: form.cacheTtlSeconds,
|
||||
})
|
||||
}
|
||||
>
|
||||
{saveMut.isPending ? t('admin.marketing.saving') : t('admin.marketing.save')}
|
||||
</Button>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 1.5 }}>
|
||||
{t('admin.marketing.personas')}
|
||||
</Typography>
|
||||
<Card sx={{ mb: 2 }}>
|
||||
<CardContent>
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<TextField
|
||||
label={t('admin.marketing.publicId')}
|
||||
value={newPublicId}
|
||||
onChange={(e) => setNewPublicId(e.target.value)}
|
||||
placeholder="7a***k2"
|
||||
helperText={t('admin.marketing.publicIdHelper')}
|
||||
sx={{ minWidth: 180 }}
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.marketing.sortOrder')}
|
||||
type="number"
|
||||
value={newSortOrder}
|
||||
onChange={(e) => setNewSortOrder(Number(e.target.value) || 0)}
|
||||
sx={{ width: 120 }}
|
||||
/>
|
||||
<Button
|
||||
variant="outlined"
|
||||
startIcon={<AddRoundedIcon />}
|
||||
disabled={!newPublicId.trim() || createMut.isPending}
|
||||
onClick={() => createMut.mutate()}
|
||||
sx={{ mt: { sm: 1 } }}
|
||||
>
|
||||
{t('admin.marketing.addPersona')}
|
||||
</Button>
|
||||
</Stack>
|
||||
{createMut.isError && (
|
||||
<Alert severity="error" sx={{ mt: 1.5 }}>
|
||||
{(createMut.error as { response?: { data?: { error?: string } } })?.response?.data
|
||||
?.error ?? t('admin.marketing.saveFailed')}
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>{t('admin.marketing.publicId')}</TableCell>
|
||||
<TableCell>{t('admin.marketing.sortOrder')}</TableCell>
|
||||
<TableCell>{t('admin.marketing.active')}</TableCell>
|
||||
<TableCell align="right">{t('admin.marketing.actions')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{(personasQuery.data ?? []).map((p) => (
|
||||
<TableRow key={p.id}>
|
||||
<TableCell>
|
||||
<Typography sx={{ fontFamily: 'monospace' }}>{p.publicId}</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TextField
|
||||
type="number"
|
||||
size="small"
|
||||
value={p.sortOrder}
|
||||
onChange={(e) =>
|
||||
patchPersonaMut.mutate({
|
||||
id: p.id,
|
||||
patch: { sortOrder: Number(e.target.value) || 0 },
|
||||
})
|
||||
}
|
||||
sx={{ width: 88 }}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Switch
|
||||
checked={p.isActive}
|
||||
onChange={(_, checked) =>
|
||||
patchPersonaMut.mutate({ id: p.id, patch: { isActive: checked } })
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
<IconButton
|
||||
color="error"
|
||||
aria-label={t('admin.marketing.delete')}
|
||||
onClick={() => {
|
||||
if (window.confirm(t('admin.marketing.deleteConfirm'))) {
|
||||
deleteMut.mutate(p.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DeleteOutlineRoundedIcon />
|
||||
</IconButton>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{(personasQuery.data ?? []).length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4}>
|
||||
<Typography sx={{ opacity: 0.7, py: 2 }}>
|
||||
{t('admin.marketing.noPersonas')}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</ScrollableTable>
|
||||
</Card>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@ -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',
|
||||
|
||||
@ -69,6 +69,7 @@ export const ADMIN_PAGE_PERMISSIONS: Record<string, string> = {
|
||||
'/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<string, string> = {
|
||||
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',
|
||||
|
||||
@ -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',
|
||||
|
||||
@ -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é',
|
||||
|
||||
Loading…
Reference in New Issue
Block a user