diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index 7e0832bf..562d11d5 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -2791,6 +2791,8 @@ CREATE TABLE IF NOT EXISTS marketing_live_activity_settings ( 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), + max_synthetic_withdrawals INT NOT NULL DEFAULT 12 CHECK (max_synthetic_withdrawals >= 0 AND max_synthetic_withdrawals <= 100), + synthetic_withdrawal_amounts INT[] NOT NULL DEFAULT ARRAY[20,35,50,80,100,120,200,250,300,450,500,800], updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); @@ -2798,6 +2800,29 @@ INSERT INTO marketing_live_activity_settings (id) VALUES (1) ON CONFLICT (id) DO NOTHING; +-- V2: withdrawal feed plafond + configurable amounts (idempotent for existing installs) +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'marketing_live_activity_settings' + AND column_name = 'max_synthetic_withdrawals' + ) THEN + ALTER TABLE marketing_live_activity_settings + ADD COLUMN max_synthetic_withdrawals INT NOT NULL DEFAULT 12 + CHECK (max_synthetic_withdrawals >= 0 AND max_synthetic_withdrawals <= 100); + END IF; + IF NOT EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'marketing_live_activity_settings' + AND column_name = 'synthetic_withdrawal_amounts' + ) THEN + ALTER TABLE marketing_live_activity_settings + ADD COLUMN synthetic_withdrawal_amounts INT[] NOT NULL + DEFAULT ARRAY[20,35,50,80,100,120,200,250,300,450,500,800]; + END IF; +END $$; + INSERT INTO marketing_personas (public_id, is_active, sort_order) VALUES ('7a***k2', TRUE, 1), diff --git a/backend/src/repositories/marketingLiveActivitySettingsRepository.ts b/backend/src/repositories/marketingLiveActivitySettingsRepository.ts index ee155085..4744b51b 100644 --- a/backend/src/repositories/marketingLiveActivitySettingsRepository.ts +++ b/backend/src/repositories/marketingLiveActivitySettingsRepository.ts @@ -1,5 +1,9 @@ import { query } from '../db/connection'; +export const DEFAULT_SYNTHETIC_WITHDRAWAL_AMOUNTS = [ + 20, 35, 50, 80, 100, 120, 200, 250, 300, 450, 500, 800, +] as const; + export type MarketingLiveActivitySettingsRow = { id: number; enabled: boolean; @@ -11,6 +15,8 @@ export type MarketingLiveActivitySettingsRow = { client_refresh_seconds: number; list_rotate_seconds: number; cache_ttl_seconds: number; + max_synthetic_withdrawals: number; + synthetic_withdrawal_amounts: number[] | string | null; updated_at: Date; }; @@ -24,6 +30,8 @@ export type MarketingLiveActivitySettings = { clientRefreshSeconds: number; listRotateSeconds: number; cacheTtlSeconds: number; + maxSyntheticWithdrawals: number; + syntheticWithdrawalAmounts: number[]; updatedAt: string; }; @@ -37,9 +45,29 @@ const DEFAULTS: Omit = { clientRefreshSeconds: 30, listRotateSeconds: 8, cacheTtlSeconds: 12, + maxSyntheticWithdrawals: 12, + syntheticWithdrawalAmounts: [...DEFAULT_SYNTHETIC_WITHDRAWAL_AMOUNTS], }; +function parseAmounts(raw: number[] | string | null | undefined): number[] { + if (Array.isArray(raw)) { + return raw.map((n) => Number(n)).filter((n) => Number.isFinite(n) && n > 0); + } + if (typeof raw === 'string') { + const trimmed = raw.trim(); + if (!trimmed) return [...DEFAULT_SYNTHETIC_WITHDRAWAL_AMOUNTS]; + // pg may return "{20,35}" style + const inner = trimmed.replace(/^\{|\}$/g, ''); + return inner + .split(',') + .map((s) => Number(s.trim())) + .filter((n) => Number.isFinite(n) && n > 0); + } + return [...DEFAULT_SYNTHETIC_WITHDRAWAL_AMOUNTS]; +} + function mapRow(row: MarketingLiveActivitySettingsRow): MarketingLiveActivitySettings { + const amounts = parseAmounts(row.synthetic_withdrawal_amounts); return { enabled: row.enabled, realActiveThreshold: Number(row.real_active_threshold) || DEFAULTS.realActiveThreshold, @@ -50,15 +78,20 @@ function mapRow(row: MarketingLiveActivitySettingsRow): MarketingLiveActivitySet clientRefreshSeconds: Number(row.client_refresh_seconds) || DEFAULTS.clientRefreshSeconds, listRotateSeconds: Number(row.list_rotate_seconds) || DEFAULTS.listRotateSeconds, cacheTtlSeconds: Number(row.cache_ttl_seconds) || DEFAULTS.cacheTtlSeconds, + maxSyntheticWithdrawals: Number(row.max_synthetic_withdrawals) || 0, + syntheticWithdrawalAmounts: + amounts.length > 0 ? amounts : [...DEFAULT_SYNTHETIC_WITHDRAWAL_AMOUNTS], updatedAt: row.updated_at.toISOString(), }; } +const SELECT_COLS = `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, max_synthetic_withdrawals, synthetic_withdrawal_amounts, updated_at`; + 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 + `SELECT ${SELECT_COLS} FROM marketing_live_activity_settings WHERE id = 1` ); if (!rows[0]) { @@ -77,6 +110,8 @@ export type LiveActivitySettingsPatch = Partial<{ clientRefreshSeconds: number; listRotateSeconds: number; cacheTtlSeconds: number; + maxSyntheticWithdrawals: number; + syntheticWithdrawalAmounts: number[]; }>; export async function updateLiveActivitySettings( @@ -93,8 +128,15 @@ export async function updateLiveActivitySettings( clientRefreshSeconds: patch.clientRefreshSeconds ?? current.clientRefreshSeconds, listRotateSeconds: patch.listRotateSeconds ?? current.listRotateSeconds, cacheTtlSeconds: patch.cacheTtlSeconds ?? current.cacheTtlSeconds, + maxSyntheticWithdrawals: patch.maxSyntheticWithdrawals ?? current.maxSyntheticWithdrawals, + syntheticWithdrawalAmounts: + patch.syntheticWithdrawalAmounts ?? current.syntheticWithdrawalAmounts, }; + if (!Array.isArray(next.syntheticWithdrawalAmounts) || next.syntheticWithdrawalAmounts.length === 0) { + throw new Error('syntheticWithdrawalAmounts must be a non-empty list of positive numbers'); + } + const rows = await query( `UPDATE marketing_live_activity_settings SET enabled = $1, @@ -106,11 +148,11 @@ export async function updateLiveActivitySettings( client_refresh_seconds = $7, list_rotate_seconds = $8, cache_ttl_seconds = $9, + max_synthetic_withdrawals = $10, + synthetic_withdrawal_amounts = $11::int[], 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`, + RETURNING ${SELECT_COLS}`, [ next.enabled, next.realActiveThreshold, @@ -121,6 +163,8 @@ export async function updateLiveActivitySettings( next.clientRefreshSeconds, next.listRotateSeconds, next.cacheTtlSeconds, + next.maxSyntheticWithdrawals, + next.syntheticWithdrawalAmounts, ] ); if (!rows[0]) { diff --git a/backend/src/services/marketingService.ts b/backend/src/services/marketingService.ts index f66403d5..fd87a0d7 100644 --- a/backend/src/services/marketingService.ts +++ b/backend/src/services/marketingService.ts @@ -72,8 +72,6 @@ export type MarketingActivityFeed = { syntheticEnabled: boolean; }; -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. */ function slotIndex(now = Date.now()): number { return Math.floor(now / 10_000); @@ -135,14 +133,15 @@ export function buildSyntheticActivityFromPersonas( export function buildSyntheticWithdrawalsFromPersonas( personas: Array>, count: number, + amounts: number[], now = Date.now() ): MarketingWithdrawalItem[] { - if (count <= 0 || personas.length === 0) return []; + if (count <= 0 || personas.length === 0 || amounts.length === 0) return []; const slot = slotIndex(now); const items: MarketingWithdrawalItem[] = []; for (let i = 0; i < count; i++) { const idx = (slot + i * 2) % personas.length; - const amount = SYNTHETIC_WITHDRAWALS[(slot + i * 5) % SYNTHETIC_WITHDRAWALS.length]; + const amount = amounts[(slot + i * 5) % amounts.length]; items.push({ id: `syn-wd-${slot}-${i}`, publicId: personas[idx].public_id, @@ -260,16 +259,22 @@ export async function getWithdrawalFeed(): Promise<{ items: MarketingWithdrawalI const settings = await loadSettingsCached(); const ttlMs = settings.cacheTtlSeconds * 1000; return cached('withdrawal-feed', ttlMs, async () => { + const pad = settings.maxSyntheticWithdrawals; const [rows, realActive, personas] = await Promise.all([ marketingRepository.listRecentRealWithdrawals(8), marketingRepository.countRecentDistinctPlayers(settings.activeWindowMinutes), - loadActivePersonasCached(ttlMs, settings.maxSyntheticEntries), + loadActivePersonasCached(ttlMs, Math.max(pad, settings.maxSyntheticEntries)), ]); const real = rows.map(mapRealWithdrawal); const useSynthetic = shouldUseSynthetic(realActive, settings); - if (!useSynthetic) return { items: real }; - const synthetic = buildSyntheticWithdrawalsFromPersonas(personas, 12); - return { items: mergeFeedItems(real, synthetic, 12) }; + if (!useSynthetic || pad <= 0) return { items: real }; + const synthetic = buildSyntheticWithdrawalsFromPersonas( + personas, + pad, + settings.syntheticWithdrawalAmounts + ); + const feedTarget = real.length + pad; + return { items: mergeFeedItems(real, synthetic, feedTarget) }; }); } diff --git a/backend/src/tests/marketingService.test.ts b/backend/src/tests/marketingService.test.ts index 46728fda..e24d26f1 100644 --- a/backend/src/tests/marketingService.test.ts +++ b/backend/src/tests/marketingService.test.ts @@ -124,10 +124,23 @@ describe('marketingService helpers', () => { assert.equal(new Set(items.map((i) => i.publicId)).size, items.length); }); - test('synthetic withdrawals pad feed from personas', () => { - const items = buildSyntheticWithdrawalsFromPersonas(personas, 12, 1_700_000_000_000); - assert.equal(items.length, 12); + test('synthetic withdrawals pad feed from personas with configurable amounts', () => { + const amounts = [20, 50, 100]; + const items = buildSyntheticWithdrawalsFromPersonas(personas, 6, amounts, 1_700_000_000_000); + assert.equal(items.length, 6); assert.ok(items.every((i) => i.statusLabel === 'Completed')); + assert.ok(items.every((i) => amounts.includes(Number(i.amountLabel)))); + }); + + test('synthetic withdrawals respect zero plafond and empty amounts', () => { + assert.deepEqual( + buildSyntheticWithdrawalsFromPersonas(personas, 0, [20, 50], 1_700_000_000_000), + [] + ); + assert.deepEqual( + buildSyntheticWithdrawalsFromPersonas(personas, 5, [], 1_700_000_000_000), + [] + ); }); test('merge with empty real still fills from synthetic', () => { diff --git a/backend/src/validation/adminResourceSchemas.ts b/backend/src/validation/adminResourceSchemas.ts index 5781bd3f..ebc546e0 100644 --- a/backend/src/validation/adminResourceSchemas.ts +++ b/backend/src/validation/adminResourceSchemas.ts @@ -243,6 +243,12 @@ export const marketingLiveActivitySettingsBodySchema = atLeastOneField( 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(), + maxSyntheticWithdrawals: z.number().int().min(0).max(100).optional(), + syntheticWithdrawalAmounts: z + .array(z.number().int().positive().max(1_000_000_000)) + .min(1) + .max(50) + .optional(), }) ); diff --git a/prediqo_web/src/features/marketing/MarketingAdminPage.tsx b/prediqo_web/src/features/marketing/MarketingAdminPage.tsx index cf6f8778..5655fdd3 100644 --- a/prediqo_web/src/features/marketing/MarketingAdminPage.tsx +++ b/prediqo_web/src/features/marketing/MarketingAdminPage.tsx @@ -39,9 +39,25 @@ type LiveActivitySettings = { clientRefreshSeconds: number; listRotateSeconds: number; cacheTtlSeconds: number; + maxSyntheticWithdrawals: number; + syntheticWithdrawalAmounts: number[]; updatedAt: string; }; +function amountsEqual(a: number[] | undefined, b: number[] | undefined): boolean { + if (!a || !b || a.length !== b.length) return false; + return a.every((v, i) => v === b[i]); +} + +function parseAmountsInput(raw: string): number[] { + return raw + .split(/[,\s]+/) + .map((s) => s.trim()) + .filter(Boolean) + .map((s) => Number(s)) + .filter((n) => Number.isFinite(n) && n > 0); +} + type Persona = { id: string; publicId: string; @@ -55,6 +71,7 @@ export function MarketingAdminPage() { const { t } = useTranslation(); const qc = useQueryClient(); const [form, setForm] = useState(null); + const [amountsText, setAmountsText] = useState(''); const [newPublicId, setNewPublicId] = useState(''); const [newSortOrder, setNewSortOrder] = useState(0); @@ -77,7 +94,17 @@ export function MarketingAdminPage() { }); useEffect(() => { - if (settingsQuery.data) setForm(settingsQuery.data); + if (settingsQuery.data) { + const data = { + ...settingsQuery.data, + maxSyntheticWithdrawals: settingsQuery.data.maxSyntheticWithdrawals ?? 12, + syntheticWithdrawalAmounts: settingsQuery.data.syntheticWithdrawalAmounts?.length + ? settingsQuery.data.syntheticWithdrawalAmounts + : [20, 35, 50, 80, 100, 120, 200, 250, 300, 450, 500, 800], + }; + setForm(data); + setAmountsText(data.syntheticWithdrawalAmounts.join(', ')); + } }, [settingsQuery.data]); const saveMut = useMutation({ @@ -135,6 +162,7 @@ export function MarketingAdminPage() { }, }); + const parsedAmounts = parseAmountsInput(amountsText); const dirty = !!form && !!settingsQuery.data && @@ -146,7 +174,9 @@ export function MarketingAdminPage() { form.feedRealFetch !== settingsQuery.data.feedRealFetch || form.clientRefreshSeconds !== settingsQuery.data.clientRefreshSeconds || form.listRotateSeconds !== settingsQuery.data.listRotateSeconds || - form.cacheTtlSeconds !== settingsQuery.data.cacheTtlSeconds); + form.cacheTtlSeconds !== settingsQuery.data.cacheTtlSeconds || + form.maxSyntheticWithdrawals !== settingsQuery.data.maxSyntheticWithdrawals || + !amountsEqual(parsedAmounts, settingsQuery.data.syntheticWithdrawalAmounts)); if (settingsQuery.isLoading || !form) { return {t('admin.marketing.loading')}; @@ -255,6 +285,32 @@ export function MarketingAdminPage() { fullWidth /> + + + {t('admin.marketing.withdrawalsSection')} + + + + setForm({ ...form, maxSyntheticWithdrawals: Number(e.target.value) || 0 }) + } + helperText={t('admin.marketing.maxSyntheticWithdrawalsHelper')} + fullWidth + /> + setAmountsText(e.target.value)} + helperText={t('admin.marketing.syntheticWithdrawalAmountsHelper')} + fullWidth + multiline + minRows={2} + /> + + {saveMut.isError && ( {(saveMut.error as { response?: { data?: { error?: string } } })?.response?.data @@ -268,8 +324,9 @@ export function MarketingAdminPage() { diff --git a/prediqo_web/src/shared/i18n/locales/en.ts b/prediqo_web/src/shared/i18n/locales/en.ts index d19b4dbd..abb56d38 100644 --- a/prediqo_web/src/shared/i18n/locales/en.ts +++ b/prediqo_web/src/shared/i18n/locales/en.ts @@ -2180,6 +2180,13 @@ export const en = { listRotateSeconds: 'List rotate (seconds)', listRotateSecondsHelper: 'Local UI rotation interval (5–60)', activeWindowMinutes: 'Active window (minutes)', + withdrawalsSection: 'Synthetic withdrawals', + maxSyntheticWithdrawals: 'Max synthetic withdrawals', + maxSyntheticWithdrawalsHelper: + 'Cap of fictive rows added to the withdrawals feed (0–100). Same enable/threshold as Live Activity.', + syntheticWithdrawalAmounts: 'Withdrawal amounts', + syntheticWithdrawalAmountsHelper: + 'Comma-separated display amounts (e.g. 20, 35, 50, 100). Rotated across active personas.', save: 'Save settings', saving: 'Saving…', saved: 'Settings saved.', diff --git a/prediqo_web/src/shared/i18n/locales/fr.ts b/prediqo_web/src/shared/i18n/locales/fr.ts index f02039e1..cdfc305f 100644 --- a/prediqo_web/src/shared/i18n/locales/fr.ts +++ b/prediqo_web/src/shared/i18n/locales/fr.ts @@ -2200,6 +2200,13 @@ export const fr = { listRotateSeconds: 'Rotation liste (secondes)', listRotateSecondsHelper: 'Intervalle de rotation UI locale (5–60)', activeWindowMinutes: 'Fenêtre active (minutes)', + withdrawalsSection: 'Retraits synthétiques', + maxSyntheticWithdrawals: 'Max retraits synthétiques', + maxSyntheticWithdrawalsHelper: + 'Plafond de lignes fictives ajoutées au feed retraits (0–100). Même activation/seuil que Live Activity.', + syntheticWithdrawalAmounts: 'Montants de retraits', + syntheticWithdrawalAmountsHelper: + 'Montants affichés séparés par des virgules (ex. 20, 35, 50, 100). Rotation sur les personas actifs.', save: 'Enregistrer les paramètres', saving: 'Enregistrement…', saved: 'Paramètres enregistrés.',