games_app/backend/src/services/marketingService.ts

393 lines
13 KiB
TypeScript

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';
type CacheEntry<T> = { at: number; value: T; ttlMs: number };
const cache = new Map<string, CacheEntry<unknown>>();
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 < hit.ttlMs) return Promise.resolve(hit.value);
return factory().then((value) => {
cache.set(key, { at: Date.now(), value, ttlMs });
return value;
});
}
/** Mask UUID/user id to short public handle (privacy). */
export function maskPublicId(raw: string): string {
const cleaned = raw.replace(/[^a-zA-Z0-9]/g, '');
if (cleaned.length < 4) return `${cleaned}***`;
return `${cleaned.slice(0, 2)}***${cleaned.slice(-2)}`;
}
function formatStakeDisplay(raw: string | number): string {
const n = typeof raw === 'number' ? raw : Number(raw);
if (!Number.isFinite(n)) return '0';
if (n >= 1000) return n.toFixed(0);
if (n >= 1) return n.toFixed(2);
return n.toFixed(4);
}
/** Format wallet raw bigint (6 decimals USDT-like) for display. */
export function formatAmountRaw(raw: string | number): string {
const n = typeof raw === 'number' ? raw : Number(raw);
if (!Number.isFinite(n)) return '0';
return formatStakeDisplay(n / 1_000_000);
}
export type MarketingActivityItem = {
id: string;
publicId: string;
kind: 'bet';
amountLabel: string;
statusLabel: 'Playing';
createdAt: string;
synthetic: boolean;
};
export type MarketingWithdrawalItem = {
id: string;
publicId: string;
amountLabel: string;
statusLabel: string;
createdAt: string;
synthetic: boolean;
};
export type MarketingDailyStats = {
uniquePlayersToday: number;
totalParticipationsToday: number;
day: string;
timezone: 'UTC';
};
export type MarketingActivityFeed = {
items: MarketingActivityItem[];
activePlayersCount: number;
clientRefreshSeconds: number;
listRotateSeconds: number;
syntheticEnabled: boolean;
};
/** Faster slot so synthetic pool rotates ~every 10s server-side. */
function slotIndex(now = Date.now()): number {
return Math.floor(now / 10_000);
}
/** 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 → lively band below display target
* (varies over time so marketing does not look stuck); otherwise real-only.
*/
export function computeActivePlayersCount(
realActive: number,
settings: Pick<
MarketingLiveActivitySettings,
'enabled' | 'realActiveThreshold' | 'displayActiveTarget' | 'displayActiveSpread'
>,
now = Date.now()
): number {
if (!shouldUseSynthetic(realActive, settings)) return realActive;
const target = Math.max(1, settings.displayActiveTarget);
const spread = Math.max(0, settings.displayActiveSpread);
// Band [target - spread, target], never below realActive.
const low = Math.max(realActive, target - spread);
const high = Math.max(low, target);
const range = high - low;
if (range <= 0) return high;
return low + (slotIndex(now) % (range + 1));
}
/** 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) % personas.length;
const items: MarketingActivityItem[] = [];
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}-${items.length}`,
publicId: handle,
kind: 'bet',
amountLabel: '0',
statusLabel: 'Playing',
createdAt: new Date(now - items.length * 20_000).toISOString(),
synthetic: true,
});
}
return items;
}
export function buildSyntheticWithdrawalsFromPersonas(
personas: Array<Pick<MarketingPersonaRow, 'public_id'>>,
count: number,
amounts: number[],
now = Date.now()
): MarketingWithdrawalItem[] {
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 = amounts[(slot + i * 5) % amounts.length];
items.push({
id: `syn-wd-${slot}-${i}`,
publicId: personas[idx].public_id,
amountLabel: formatStakeDisplay(amount),
statusLabel: 'Completed',
createdAt: new Date(now - i * 90_000).toISOString(),
synthetic: true,
});
}
return items;
}
/** Merge real first, pad with synthetic; de-dupe by publicId. */
export function mergeFeedItems<T extends { id: string; publicId?: string }>(
real: T[],
synthetic: T[],
target: number
): T[] {
const out: T[] = [];
const seen = new Set<string>();
const push = (item: T) => {
const key = item.publicId ?? item.id;
if (seen.has(key)) return;
seen.add(key);
out.push(item);
};
for (const r of real) {
if (out.length >= target) break;
push(r);
}
for (const s of synthetic) {
if (out.length >= target) break;
push(s);
}
return out;
}
/**
* Withdrawals feed: treat real + synthetic the same — one de-duped pool,
* time-rotated so neither sticks permanently at the top.
*/
export function blendAndRotateFeedItems<T extends { id: string; publicId?: string }>(
real: T[],
synthetic: T[],
target: number,
now = Date.now()
): T[] {
const pool: T[] = [];
const seen = new Set<string>();
const push = (item: T) => {
const key = item.publicId ?? item.id;
if (seen.has(key)) return;
seen.add(key);
pool.push(item);
};
for (const r of real) push(r);
for (const s of synthetic) push(s);
if (pool.length === 0 || target <= 0) return [];
const slot = slotIndex(now);
const start = slot % pool.length;
const n = Math.min(target, pool.length);
const out: T[] = [];
for (let i = 0; i < n; i++) {
out.push(pool[(start + i) % pool.length]);
}
return out;
}
function mapRealPlaying(row: marketingRepository.RealActivityRow): MarketingActivityItem {
return {
id: row.id,
publicId: maskPublicId(row.user_id),
kind: 'bet',
amountLabel: '0',
statusLabel: 'Playing',
createdAt: row.created_at.toISOString(),
synthetic: false,
};
}
function mapRealWithdrawal(row: marketingRepository.RealWithdrawalRow): MarketingWithdrawalItem {
return {
id: row.id,
publicId: maskPublicId(row.user_id),
amountLabel: formatAmountRaw(row.amount),
statusLabel: 'Completed',
createdAt: row.created_at.toISOString(),
synthetic: false,
};
}
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> {
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' as const,
};
});
}
export async function getActivityFeed(): Promise<MarketingActivityFeed> {
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 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, settings),
clientRefreshSeconds: settings.clientRefreshSeconds,
listRotateSeconds: settings.listRotateSeconds,
syntheticEnabled: useSynthetic,
};
});
}
export async function getWithdrawalFeed(): Promise<{ items: MarketingWithdrawalItem[] }> {
const settings = await loadSettingsCached();
const ttlMs = settings.cacheTtlSeconds * 1000;
return cached('withdrawal-feed', ttlMs, async () => {
const pad = settings.maxSyntheticWithdrawals;
const realFetch = Math.max(8, pad);
const displayTarget = Math.max(pad > 0 ? pad : 8, 8);
const [rows, realActive, personas] = await Promise.all([
marketingRepository.listRecentRealWithdrawals(
realFetch,
settings.withdrawalRealWindowHours
),
marketingRepository.countRecentDistinctPlayers(settings.activeWindowMinutes),
loadActivePersonasCached(ttlMs, Math.max(pad, settings.maxSyntheticEntries)),
]);
const real = rows.map(mapRealWithdrawal);
const useSynthetic = shouldUseSynthetic(realActive, settings);
const synthetic =
useSynthetic && pad > 0
? buildSyntheticWithdrawalsFromPersonas(
personas,
pad,
settings.syntheticWithdrawalAmounts
)
: [];
// Same presentation for real + synthetic: shared rotating pool (no sticky real-first).
return {
items: blendAndRotateFeedItems(real, synthetic, displayTarget),
};
});
}
/** 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();
}