Files
gameno-api/components/settings/messagingFlags.js
T
kavehhn 4ad5630cb7 fix: clarify why SMS delivery is skipped when a channel gate is off
Surface env vs dashboard disable reasons in SMS logs so password reset and other sends are easier to diagnose when only one layer is enabled.
2026-08-16 13:30:51 +03:30

83 lines
2.0 KiB
JavaScript

'use strict';
const config = require('../../config/config');
const logger = require('../../utils/logger');
const { Setting, SETTINGS_KEY } = require('./settingModel');
const {
isDbChannelEnabled,
isEnvChannelEnabled,
toPublicMessaging
} = require('../../utils/messagingChannels');
let cache = null;
let cacheAt = 0;
const CACHE_TTL_MS = 10000;
const readDbFlags = (doc) => ({
smsEnabled: doc?.smsEnabled,
emailEnabled: doc?.emailEnabled,
botEnabled: doc?.botEnabled
});
const getDbMessagingFlags = async () => {
const now = Date.now();
if (cache && (now - cacheAt) < CACHE_TTL_MS) return cache;
const doc = await Setting.findOne({ key: SETTINGS_KEY })
.select('smsEnabled emailEnabled botEnabled')
.lean();
cache = readDbFlags(doc);
cacheAt = now;
return cache;
};
const invalidateMessagingCache = () => {
cache = null;
cacheAt = 0;
};
const getMessagingChannelState = async (channel) => {
const envEnabled = isEnvChannelEnabled(channel, config);
if (!envEnabled) {
return {
enabled: false,
envEnabled: false,
dbEnabled: null,
blockReason: 'env_disabled'
};
}
try {
const db = await getDbMessagingFlags();
const dbEnabled = isDbChannelEnabled(channel, db);
return {
enabled: dbEnabled,
envEnabled: true,
dbEnabled,
blockReason: dbEnabled ? null : 'dashboard_disabled'
};
} catch (err) {
logger.warn(`[Messaging] Failed to read settings for ${channel}, using env only: ${err.message}`);
return {
enabled: true,
envEnabled: true,
dbEnabled: null,
blockReason: null
};
}
};
const isMessagingChannelEnabled = async (channel) => {
const state = await getMessagingChannelState(channel);
return state.enabled;
};
const getPublicMessaging = (doc) => toPublicMessaging(readDbFlags(doc), config);
module.exports = {
getMessagingChannelState,
isMessagingChannelEnabled,
invalidateMessagingCache,
getPublicMessaging,
getDbMessagingFlags
};