-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromo-message.js
More file actions
172 lines (154 loc) · 6.41 KB
/
promo-message.js
File metadata and controls
172 lines (154 loc) · 6.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
const fs = require('fs');
const path = require('path');
const PROMO_MESSAGE_FILE = path.join(__dirname, 'data', 'promo_message.json');
const PROMO_MANAGER_DB_FILE = path.join(__dirname, 'data', 'promo-manager-db.json');
const FALLBACK_PROMO_MESSAGE = 'Your promo is ready — tap below to claim.';
const PROMO_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
const promoCache = {
active_new_user_promo: { value: null, fetchedAt: 0, signature: null },
active_existing_user_promo: { value: null, fetchedAt: 0, signature: null },
};
function normalizePromoAudience(audience) {
return String(audience || 'new_user').trim().toLowerCase() === 'existing_user'
? 'existing_user'
: 'new_user';
}
function getPromoCacheKey(audience) {
return normalizePromoAudience(audience) === 'existing_user'
? 'active_existing_user_promo'
: 'active_new_user_promo';
}
function parsePromoAmount(value) {
if (Number.isFinite(Number(value)) && Number(value) > 0) return Number(value);
const match = String(value || '').match(/(\d+(?:\.\d+)?)\s*SC/i);
return match ? Number(match[1]) : null;
}
function normalizePromoRecord(raw, idHint = null) {
if (!raw || typeof raw !== 'object') return null;
const promoId = Number(raw.promo_id) || Number(raw.id) || Number(idHint || 0);
if (!promoId) return null;
const requirement = String(raw.requirement_type || '').trim().toLowerCase();
const audience = requirement === 'existing_user_with_wager'
? 'existing_user'
: (raw.new_user_only ? 'new_user' : raw.existing_user_only ? 'existing_user' : requirement === 'existing_user' ? 'existing_user' : 'new_user');
const amount = parsePromoAmount(raw.amountSC ?? raw.amount ?? raw.bonus_amount_sc ?? raw.description ?? raw.notes);
return {
promo_id: promoId,
code: String(raw.code_or_link || raw.code || '').trim(),
amount,
audience,
status: String(raw.status || 'active').trim().toLowerCase(),
created_at: Number(raw.created_at) || Number(raw.createdAt) || Date.now(),
updated_at: Number(raw.updated_at) || Number(raw.updatedAt) || Date.now(),
priority: Number(raw.priority) || 0,
description: String(raw.description || raw.notes || '').trim(),
casino_base_url: String(raw.casino_base_url || '').trim(),
name: String(raw.name || `Promo #${promoId}`).trim(),
source: 'promo_manager_db',
};
}
function readPromoDbPromos() {
try {
if (!fs.existsSync(PROMO_MANAGER_DB_FILE)) return [];
const parsed = JSON.parse(fs.readFileSync(PROMO_MANAGER_DB_FILE, 'utf8'));
const promos = Array.isArray(parsed && parsed.promos) ? parsed.promos : [];
return promos.map((promo, idx) => normalizePromoRecord(promo, idx + 1)).filter(Boolean);
} catch (_err) {
return [];
}
}
function selectActivePromo(promos, audience) {
const normalizedAudience = normalizePromoAudience(audience);
return promos
.filter((promo) => promo.status === 'active' && promo.audience === normalizedAudience && promo.code)
.sort((a, b) => (Number(b.priority) || 0) - (Number(a.priority) || 0)
|| (Number(b.created_at) || 0) - (Number(a.created_at) || 0)
|| (Number(b.promo_id) || 0) - (Number(a.promo_id) || 0))[0] || null;
}
function logPromoEvent(logger, level, msg, extra = {}) {
if (!logger) return;
if (typeof logger[level] === 'function') logger[level]('promo.cache', msg, extra);
else if (typeof logger.info === 'function') logger.info('promo.cache', msg, extra);
}
function getActivePromoFromDb(audience = 'new_user', { forceRefresh = false, logger = null } = {}) {
const cacheKey = getPromoCacheKey(audience);
const cacheEntry = promoCache[cacheKey];
const now = Date.now();
if (!forceRefresh && cacheEntry.fetchedAt && (now - cacheEntry.fetchedAt) < PROMO_CACHE_TTL_MS) {
return cacheEntry.value;
}
const previousSignature = cacheEntry.signature;
const promo = selectActivePromo(readPromoDbPromos(), audience);
cacheEntry.value = promo;
cacheEntry.fetchedAt = now;
cacheEntry.signature = promo ? `${promo.promo_id}:${promo.code}:${promo.amount || ''}:${promo.updated_at}` : 'none';
logPromoEvent(logger, 'info', 'Promo cache refreshed', { cacheKey, promoId: promo && promo.promo_id, audience: normalizePromoAudience(audience) });
if (previousSignature && previousSignature !== cacheEntry.signature) {
logPromoEvent(logger, 'info', 'Promo cache changed', {
cacheKey,
previousSignature,
nextSignature: cacheEntry.signature,
});
}
if (!promo) {
logPromoEvent(logger, 'warn', 'Promo cache fallback: no active promo found', { cacheKey, audience: normalizePromoAudience(audience) });
}
return promo;
}
function invalidateActivePromoCache(audience = null, { logger = null, reason = 'manual' } = {}) {
const keys = audience
? [getPromoCacheKey(audience)]
: ['active_new_user_promo', 'active_existing_user_promo'];
for (const key of keys) {
promoCache[key].value = null;
promoCache[key].fetchedAt = 0;
promoCache[key].signature = null;
logPromoEvent(logger, 'info', 'Promo cache invalidated', { cacheKey: key, reason });
}
}
function readPromoMessageFile() {
try {
if (!fs.existsSync(PROMO_MESSAGE_FILE)) return null;
const parsed = JSON.parse(fs.readFileSync(PROMO_MESSAGE_FILE, 'utf8'));
const value = String(parsed && parsed.message || '').trim();
return value || null;
} catch (_err) {
return null;
}
}
function getPromoMessage({ audience = 'new_user', forceRefresh = false, logger = null } = {}) {
const promo = getActivePromoFromDb(audience, { forceRefresh, logger });
if (promo) {
const amountText = promo.amount ? `${promo.amount} SC` : 'SC';
return `${promo.name}: use ${promo.code} to claim ${amountText}.`;
}
return readPromoMessageFile()
|| String(process.env.DEFAULT_PROMO_MESSAGE || '').trim()
|| FALLBACK_PROMO_MESSAGE;
}
function setPromoMessage(message) {
const clean = String(message || '').trim();
if (!clean) throw new Error('Promo message cannot be empty.');
fs.mkdirSync(path.dirname(PROMO_MESSAGE_FILE), { recursive: true });
fs.writeFileSync(
PROMO_MESSAGE_FILE,
`${JSON.stringify({ message: clean, updatedAt: new Date().toISOString() }, null, 2)}\n`,
'utf8',
);
return clean;
}
module.exports = {
FALLBACK_PROMO_MESSAGE,
PROMO_CACHE_TTL_MS,
PROMO_MANAGER_DB_FILE,
PROMO_MESSAGE_FILE,
getActivePromoFromDb,
getPromoCacheKey,
getPromoMessage,
invalidateActivePromoCache,
normalizePromoAudience,
parsePromoAmount,
readPromoDbPromos,
selectActivePromo,
setPromoMessage,
};