353 lines
14 KiB
JavaScript
353 lines
14 KiB
JavaScript
"use strict";
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__importStar) || (function () {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
var ar = [];
|
|
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function (mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
})();
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.maskPublicId = maskPublicId;
|
|
exports.formatAmountRaw = formatAmountRaw;
|
|
exports.shouldUseSynthetic = shouldUseSynthetic;
|
|
exports.computeActivePlayersCount = computeActivePlayersCount;
|
|
exports.buildSyntheticActivityFromPersonas = buildSyntheticActivityFromPersonas;
|
|
exports.buildSyntheticWithdrawalsFromPersonas = buildSyntheticWithdrawalsFromPersonas;
|
|
exports.mergeFeedItems = mergeFeedItems;
|
|
exports.blendAndRotateFeedItems = blendAndRotateFeedItems;
|
|
exports.getDailyStats = getDailyStats;
|
|
exports.getActivityFeed = getActivityFeed;
|
|
exports.getWithdrawalFeed = getWithdrawalFeed;
|
|
exports.getLiveActivitySettingsAdmin = getLiveActivitySettingsAdmin;
|
|
exports.updateLiveActivitySettingsAdmin = updateLiveActivitySettingsAdmin;
|
|
exports.mapPersonaAdmin = mapPersonaAdmin;
|
|
exports.listPersonasAdmin = listPersonasAdmin;
|
|
exports.createPersonaAdmin = createPersonaAdmin;
|
|
exports.updatePersonaAdmin = updatePersonaAdmin;
|
|
exports.deletePersonaAdmin = deletePersonaAdmin;
|
|
exports.clearMarketingCache = clearMarketingCache;
|
|
const marketingRepository = __importStar(require("../repositories/marketingRepository"));
|
|
const settingsRepository = __importStar(require("../repositories/marketingLiveActivitySettingsRepository"));
|
|
const personaRepository = __importStar(require("../repositories/marketingPersonaRepository"));
|
|
const cache = new Map();
|
|
function cached(key, ttlMs, factory) {
|
|
const hit = cache.get(key);
|
|
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). */
|
|
function maskPublicId(raw) {
|
|
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) {
|
|
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. */
|
|
function formatAmountRaw(raw) {
|
|
const n = typeof raw === 'number' ? raw : Number(raw);
|
|
if (!Number.isFinite(n))
|
|
return '0';
|
|
return formatStakeDisplay(n / 1000000);
|
|
}
|
|
/** Faster slot so synthetic pool rotates ~every 10s server-side. */
|
|
function slotIndex(now = Date.now()) {
|
|
return Math.floor(now / 10000);
|
|
}
|
|
/** Whether Live Activity should merge / boost with synthetic personas. */
|
|
function shouldUseSynthetic(realActive, settings) {
|
|
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.
|
|
*/
|
|
function computeActivePlayersCount(realActive, settings, now = Date.now()) {
|
|
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). */
|
|
function buildSyntheticActivityFromPersonas(personas, count, now = Date.now()) {
|
|
if (count <= 0 || personas.length === 0)
|
|
return [];
|
|
const slot = slotIndex(now);
|
|
const start = (slot * 3) % personas.length;
|
|
const items = [];
|
|
const n = Math.min(count, personas.length);
|
|
const seen = new Set();
|
|
for (let i = 0; items.length < n && i < personas.length * 2; i++) {
|
|
const handle = personas[(start + i) % personas.length].public_id;
|
|
if (seen.has(handle))
|
|
continue;
|
|
seen.add(handle);
|
|
items.push({
|
|
id: `syn-act-${slot}-${items.length}`,
|
|
publicId: handle,
|
|
kind: 'bet',
|
|
amountLabel: '0',
|
|
statusLabel: 'Playing',
|
|
createdAt: new Date(now - items.length * 20000).toISOString(),
|
|
synthetic: true,
|
|
});
|
|
}
|
|
return items;
|
|
}
|
|
function buildSyntheticWithdrawalsFromPersonas(personas, count, amounts, now = Date.now()) {
|
|
if (count <= 0 || personas.length === 0 || amounts.length === 0)
|
|
return [];
|
|
const slot = slotIndex(now);
|
|
const items = [];
|
|
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 * 90000).toISOString(),
|
|
synthetic: true,
|
|
});
|
|
}
|
|
return items;
|
|
}
|
|
/** Merge real first, pad with synthetic; de-dupe by publicId. */
|
|
function mergeFeedItems(real, synthetic, target) {
|
|
const out = [];
|
|
const seen = new Set();
|
|
const push = (item) => {
|
|
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.
|
|
*/
|
|
function blendAndRotateFeedItems(real, synthetic, target, now = Date.now()) {
|
|
const pool = [];
|
|
const seen = new Set();
|
|
const push = (item) => {
|
|
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 = [];
|
|
for (let i = 0; i < n; i++) {
|
|
out.push(pool[(start + i) % pool.length]);
|
|
}
|
|
return out;
|
|
}
|
|
function mapRealPlaying(row) {
|
|
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) {
|
|
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() {
|
|
return cached('live-activity-settings', 12000, () => settingsRepository.getLiveActivitySettings());
|
|
}
|
|
async function loadActivePersonasCached(ttlMs, limit) {
|
|
return cached(`active-personas:${limit}`, ttlMs, () => personaRepository.listActivePersonas(Math.max(limit, 100)));
|
|
}
|
|
async function getDailyStats() {
|
|
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',
|
|
};
|
|
});
|
|
}
|
|
async function getActivityFeed() {
|
|
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,
|
|
};
|
|
});
|
|
}
|
|
async function getWithdrawalFeed() {
|
|
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). */
|
|
async function getLiveActivitySettingsAdmin() {
|
|
return settingsRepository.getLiveActivitySettings();
|
|
}
|
|
async function updateLiveActivitySettingsAdmin(patch) {
|
|
const updated = await settingsRepository.updateLiveActivitySettings(patch);
|
|
clearMarketingCache();
|
|
return updated;
|
|
}
|
|
function mapPersonaAdmin(row) {
|
|
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(),
|
|
};
|
|
}
|
|
async function listPersonasAdmin() {
|
|
const rows = await personaRepository.listPersonas();
|
|
return rows.map(mapPersonaAdmin);
|
|
}
|
|
async function createPersonaAdmin(input) {
|
|
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);
|
|
}
|
|
async function updatePersonaAdmin(id, input) {
|
|
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);
|
|
}
|
|
async function deletePersonaAdmin(id) {
|
|
const ok = await personaRepository.deletePersona(id);
|
|
if (!ok)
|
|
throw new Error('Persona not found');
|
|
clearMarketingCache();
|
|
}
|
|
/** Test helper / admin: clear in-memory cache. */
|
|
function clearMarketingCache() {
|
|
cache.clear();
|
|
}
|
|
//# sourceMappingURL=marketingService.js.map
|