Compare commits
2 Commits
pre-mvp-st
...
1a46fb696a
| Author | SHA1 | Date | |
|---|---|---|---|
| 1a46fb696a | |||
| 636348d824 |
@@ -45,7 +45,9 @@
|
|||||||
"Bash(curl -sI http://100.114.205.53:12752/api/notifications/alerts)",
|
"Bash(curl -sI http://100.114.205.53:12752/api/notifications/alerts)",
|
||||||
"Bash(git log *)",
|
"Bash(git log *)",
|
||||||
"Bash(curl *)",
|
"Bash(curl *)",
|
||||||
"Bash(docker inspect *)"
|
"Bash(docker inspect *)",
|
||||||
|
"Bash(git -C /opt/broccolini-bot tag)",
|
||||||
|
"Bash(git -C /opt/broccolini-bot branch)"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
48
.env.example
48
.env.example
@@ -112,16 +112,10 @@ PRIORITY_MEDIUM_EMOJI=🟡
|
|||||||
PRIORITY_LOW_EMOJI=🟢
|
PRIORITY_LOW_EMOJI=🟢
|
||||||
|
|
||||||
# --- Claiming ---
|
# --- Claiming ---
|
||||||
CLAIM_TIMEOUT_ENABLED=false
|
|
||||||
CLAIM_TIMEOUT_HOURS=48
|
|
||||||
AUTO_UNCLAIM_ENABLED=false
|
AUTO_UNCLAIM_ENABLED=false
|
||||||
AUTO_UNCLAIM_AFTER_HOURS=24
|
AUTO_UNCLAIM_AFTER_HOURS=24
|
||||||
ALLOW_CLAIM_OVERWRITE=false
|
ALLOW_CLAIM_OVERWRITE=false
|
||||||
STAFF_EMOJIS=224692549225283584:🍅 # userId:emoji pairs, comma-separated
|
ADMIN_ID= # Discord user ID of the bot admin (for Gmail OAuth failure DMs)
|
||||||
CLAIMER_EMOJI_FALLBACK=🎫 # fallback if claimer has no entry in STAFF_EMOJIS
|
|
||||||
ADMIN_ID= # Discord user ID of the bot admin (for /staffnotification)
|
|
||||||
STAFF_NOTIFICATION_CATEGORY_ID= # Category for staff notification channels (created by /notification add)
|
|
||||||
UNCLAIMED_REMINDER_THRESHOLDS=1,2,4 # Comma-separated hour thresholds for unclaimed ticket alerts
|
|
||||||
FORCE_CLOSE_TIMER_SECONDS=60 # Seconds to wait before force-closing a ticket (default 60)
|
FORCE_CLOSE_TIMER_SECONDS=60 # Seconds to wait before force-closing a ticket (default 60)
|
||||||
GMAIL_POLL_INTERVAL_SECONDS=30 # Gmail poll interval in seconds (default 30)
|
GMAIL_POLL_INTERVAL_SECONDS=30 # Gmail poll interval in seconds (default 30)
|
||||||
GMAIL_LOG_CHANNEL_ID= # Channel for Gmail poll activity logs
|
GMAIL_LOG_CHANNEL_ID= # Channel for Gmail poll activity logs
|
||||||
@@ -130,46 +124,6 @@ RENAME_LOG_CHANNEL_ID= # Channel for channel rename queue log
|
|||||||
SECURITY_LOG_CHANNEL_ID= # Channel for security/audit logs
|
SECURITY_LOG_CHANNEL_ID= # Channel for security/audit logs
|
||||||
SYSTEM_LOG_CHANNEL_ID= # Channel for bot lifecycle logs (startup, shutdown, DB events)
|
SYSTEM_LOG_CHANNEL_ID= # Channel for bot lifecycle logs (startup, shutdown, DB events)
|
||||||
|
|
||||||
# --- Pattern detection ---
|
|
||||||
USER_PATTERNS_CHANNEL_ID= # Channel for repeat-user pattern alerts
|
|
||||||
GAME_PATTERNS_CHANNEL_ID= # Channel for game-specific pattern alerts
|
|
||||||
TAG_PATTERNS_CHANNEL_ID= # Channel for ticket tag pattern alerts
|
|
||||||
ESCALATION_PATTERNS_CHANNEL_ID= # Channel for escalation pattern alerts
|
|
||||||
STAFF_PATTERNS_CHANNEL_ID= # Channel for staff workload pattern alerts
|
|
||||||
COMBINED_PATTERNS_CHANNEL_ID= # Channel for combined/cross-cutting pattern alerts
|
|
||||||
PATTERN_USER_TICKET_THRESHOLD=3 # Tickets per user before alerting
|
|
||||||
PATTERN_GAME_TICKET_THRESHOLD=10 # Tickets per game before alerting
|
|
||||||
PATTERN_STAFF_STALE_PING_THRESHOLD=5 # Stale pings before alerting
|
|
||||||
PATTERN_ESCALATION_THRESHOLD=3 # Escalations before alerting
|
|
||||||
PATTERN_RAPID_CLOSE_SECONDS=120 # Seconds; closes faster than this are flagged
|
|
||||||
PATTERN_UNCLAIMED_HOURS=4 # Hours unclaimed before flagging
|
|
||||||
PATTERN_CHECK_INTERVAL_MINUTES=30 # Minutes between pattern check runs
|
|
||||||
|
|
||||||
# --- Surge & chat alerts ---
|
|
||||||
ALL_STAFF_CHANNEL_ID= # Channel for staff surge alerts
|
|
||||||
ALL_STAFF_CHAT_ALERT_CHANNEL_ID= # Channel for chat monitoring alerts
|
|
||||||
SURGE_ROLE_ID= # Role to ping on surge alerts
|
|
||||||
SURGE_TICKET_COUNT=10 # Ticket count to trigger surge
|
|
||||||
SURGE_TICKET_WINDOW_MINUTES=30 # Window for ticket surge
|
|
||||||
SURGE_GAME_TICKET_COUNT=5 # Per-game ticket count for surge
|
|
||||||
SURGE_GAME_TICKET_WINDOW_MINUTES=30 # Window for game surge
|
|
||||||
SURGE_STALE_COUNT=8 # Stale tickets to trigger alert
|
|
||||||
SURGE_STALE_HOURS=2 # Hours before ticket is stale
|
|
||||||
SURGE_NEEDS_RESPONSE_COUNT=5 # Tickets awaiting response to trigger alert
|
|
||||||
SURGE_NEEDS_RESPONSE_HOURS=1 # Hours awaiting response
|
|
||||||
SURGE_UNCLAIMED_COUNT=5 # Unclaimed tickets for surge alert
|
|
||||||
SURGE_UNCLAIMED_MINUTES=30 # Minutes unclaimed before counting
|
|
||||||
SURGE_TIER3_UNCLAIMED_MINUTES=15 # Minutes before tier 3 unclaimed alert
|
|
||||||
SURGE_COOLDOWN_MINUTES=60 # Cooldown between surge alerts
|
|
||||||
CHAT_ALERT_CHANNEL_IDS= # Comma-separated channel IDs to monitor
|
|
||||||
CHAT_ALERT_MESSAGE_COUNT=5 # Unresponded messages to trigger alert
|
|
||||||
CHAT_ALERT_HOURS_WITHOUT_RESPONSE=2 # Hours without staff response to alert
|
|
||||||
CHAT_ALERT_COOLDOWN_MINUTES=60 # Cooldown between chat alerts
|
|
||||||
STAFF_IDS= # Comma-separated Discord user IDs of all staff members
|
|
||||||
SURGE_NO_STAFF_COOLDOWN_MINUTES=30 # Cooldown between zero-staff alerts
|
|
||||||
SURGE_NO_STAFF_OPEN_TICKET_THRESHOLD=3 # Min open tickets before alerting
|
|
||||||
STAFF_DND_COUNTS_AS_AVAILABLE=false # Whether DND status counts as available
|
|
||||||
|
|
||||||
# --- Staff threads ---
|
# --- Staff threads ---
|
||||||
STAFF_THREAD_ENABLED=false # Create a private staff thread on each ticket channel
|
STAFF_THREAD_ENABLED=false # Create a private staff thread on each ticket channel
|
||||||
STAFF_THREAD_NAME=Staff Discussion # Name of the private thread
|
STAFF_THREAD_NAME=Staff Discussion # Name of the private thread
|
||||||
|
|||||||
@@ -107,8 +107,6 @@ PRIORITY_MEDIUM_EMOJI=🟡
|
|||||||
PRIORITY_LOW_EMOJI=🟢
|
PRIORITY_LOW_EMOJI=🟢
|
||||||
|
|
||||||
# --- Claiming ---
|
# --- Claiming ---
|
||||||
CLAIM_TIMEOUT_ENABLED=false
|
|
||||||
CLAIM_TIMEOUT_HOURS=48
|
|
||||||
AUTO_UNCLAIM_ENABLED=false
|
AUTO_UNCLAIM_ENABLED=false
|
||||||
AUTO_UNCLAIM_AFTER_HOURS=24
|
AUTO_UNCLAIM_AFTER_HOURS=24
|
||||||
ALLOW_CLAIM_OVERWRITE=false
|
ALLOW_CLAIM_OVERWRITE=false
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ const { handleDiscordReply } = require('./handlers/messages');
|
|||||||
// Services & jobs
|
// Services & jobs
|
||||||
const { sendTicketClosedEmail } = require('./services/gmail');
|
const { sendTicketClosedEmail } = require('./services/gmail');
|
||||||
const { checkAutoClose, checkAutoUnclaim, reconcileDeletedTicketChannels, resumePendingDeletes } = require('./services/tickets');
|
const { checkAutoClose, checkAutoUnclaim, reconcileDeletedTicketChannels, resumePendingDeletes } = require('./services/tickets');
|
||||||
const { notifyAllStaffUnclaimed } = require('./services/staffNotifications');
|
|
||||||
const { registerCommands } = require('./commands/register');
|
const { registerCommands } = require('./commands/register');
|
||||||
const bosscordRoutes = require('./routes/bosscord');
|
const bosscordRoutes = require('./routes/bosscord');
|
||||||
const { setBot } = require('./api/bosscordClient');
|
const { setBot } = require('./api/bosscordClient');
|
||||||
@@ -202,15 +201,6 @@ client.on('interactionCreate', async interaction => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
client.on('messageCreate', async msg => {
|
client.on('messageCreate', async msg => {
|
||||||
// Track staff last-seen for zero-staff detection fallback
|
|
||||||
if (!msg.author.bot && CONFIG.STAFF_IDS.includes(msg.author.id)) {
|
|
||||||
const { updateStaffLastSeen } = require('./services/patternStore');
|
|
||||||
updateStaffLastSeen(msg.author.id);
|
|
||||||
}
|
|
||||||
// Chat channel monitoring
|
|
||||||
const { handleChatMessage } = require('./services/chatAlertChecker');
|
|
||||||
await handleChatMessage(msg, client).catch(() => {});
|
|
||||||
// Existing ticket reply handler
|
|
||||||
await handleDiscordReply(msg);
|
await handleDiscordReply(msg);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -262,47 +252,21 @@ client.once('ready', async () => {
|
|||||||
console.log('✓ Auto-close enabled: checking every hour');
|
console.log('✓ Auto-close enabled: checking every hour');
|
||||||
}
|
}
|
||||||
|
|
||||||
trackInterval(setInterval(() => notifyAllStaffUnclaimed(client).catch(e => console.error('notifyAllStaffUnclaimed:', e)), 30 * 60 * 1000));
|
|
||||||
notifyAllStaffUnclaimed(client).catch(e => console.error('notifyAllStaffUnclaimed:', e));
|
|
||||||
console.log('✓ Staff unclaimed reminders: checking every 30 minutes');
|
|
||||||
|
|
||||||
if (CONFIG.AUTO_UNCLAIM_ENABLED) {
|
if (CONFIG.AUTO_UNCLAIM_ENABLED) {
|
||||||
trackInterval(setInterval(() => checkAutoUnclaim(client), 60 * 60 * 1000));
|
trackInterval(setInterval(() => checkAutoUnclaim(client), 60 * 60 * 1000));
|
||||||
checkAutoUnclaim(client);
|
checkAutoUnclaim(client);
|
||||||
console.log('✓ Auto-unclaim enabled: checking every hour');
|
console.log('✓ Auto-unclaim enabled: checking every hour');
|
||||||
}
|
}
|
||||||
|
|
||||||
const { runPatternChecks } = require('./services/patternChecker');
|
|
||||||
const { scheduleResets } = require('./services/patternStore');
|
|
||||||
scheduleResets();
|
|
||||||
trackInterval(setInterval(() => runPatternChecks(client).catch(e => console.error('runPatternChecks:', e)), CONFIG.PATTERN_CHECK_INTERVAL_MINUTES * 60 * 1000));
|
|
||||||
console.log(`✓ Pattern checks: every ${CONFIG.PATTERN_CHECK_INTERVAL_MINUTES} minutes`);
|
|
||||||
|
|
||||||
const { runSurgeChecks } = require('./services/surgeChecker');
|
|
||||||
trackInterval(setInterval(() => runSurgeChecks(client).catch(e => console.error('runSurgeChecks:', e)), 5 * 60 * 1000));
|
|
||||||
setTimeout(() => runSurgeChecks(client).catch(e => console.error('runSurgeChecks:', e)), 30000);
|
|
||||||
console.log('✓ Surge checks: every 5 minutes');
|
|
||||||
|
|
||||||
const { initChatMonitoring, runChatAlertChecks } = require('./services/chatAlertChecker');
|
|
||||||
initChatMonitoring(client);
|
|
||||||
trackInterval(setInterval(() => runChatAlertChecks(client).catch(e => console.error('runChatAlertChecks:', e)), 5 * 60 * 1000));
|
|
||||||
console.log('✓ Chat alert monitoring: every 5 minutes');
|
|
||||||
|
|
||||||
reconcileDeletedTicketChannels(client).catch(e => console.error('reconcileDeletedTicketChannels:', e));
|
reconcileDeletedTicketChannels(client).catch(e => console.error('reconcileDeletedTicketChannels:', e));
|
||||||
trackInterval(setInterval(() => reconcileDeletedTicketChannels(client).catch(e => console.error('reconcileDeletedTicketChannels:', e)), 60 * 60 * 1000));
|
trackInterval(setInterval(() => reconcileDeletedTicketChannels(client).catch(e => console.error('reconcileDeletedTicketChannels:', e)), 60 * 60 * 1000));
|
||||||
resumePendingDeletes(client).catch(e => console.error('resumePendingDeletes:', e));
|
resumePendingDeletes(client).catch(e => console.error('resumePendingDeletes:', e));
|
||||||
console.log('✓ Reconcile deleted ticket channels: every 1 hour');
|
console.log('✓ Reconcile deleted ticket channels: every 1 hour');
|
||||||
|
|
||||||
// Start in-memory Map sweeps (per-module) — keeps long-running processes bounded.
|
// Start in-memory Map sweeps (per-module) — keeps long-running processes bounded.
|
||||||
require('./services/patternStore').startSweeps(trackInterval);
|
|
||||||
require('./services/staffNotifications').startSweeps(trackInterval);
|
|
||||||
require('./services/tickets').startTicketsSweeps(trackInterval);
|
require('./services/tickets').startTicketsSweeps(trackInterval);
|
||||||
console.log('✓ Memory sweeps registered: every 6 hours (unref\'d)');
|
console.log('✓ Memory sweeps registered: every 6 hours (unref\'d)');
|
||||||
|
|
||||||
if (!CONFIG.STAFF_IDS.length) {
|
|
||||||
console.warn('[surgeChecker] STAFF_IDS is not set — zero-staff detection disabled.');
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('✓ Discord bot ready. Tag:', client.user.tag);
|
console.log('✓ Discord bot ready. Tag:', client.user.tag);
|
||||||
|
|
||||||
logSystem('Bot online', [
|
logSystem('Bot online', [
|
||||||
@@ -310,7 +274,6 @@ client.once('ready', async () => {
|
|||||||
{ name: 'Poll interval', value: `${CONFIG.GMAIL_POLL_INTERVAL_MS / 1000}s` },
|
{ name: 'Poll interval', value: `${CONFIG.GMAIL_POLL_INTERVAL_MS / 1000}s` },
|
||||||
{ name: 'Auto-close', value: CONFIG.AUTO_CLOSE_ENABLED ? `enabled (${CONFIG.AUTO_CLOSE_AFTER_HOURS}h)` : 'disabled' },
|
{ name: 'Auto-close', value: CONFIG.AUTO_CLOSE_ENABLED ? `enabled (${CONFIG.AUTO_CLOSE_AFTER_HOURS}h)` : 'disabled' },
|
||||||
{ name: 'Auto-unclaim', value: CONFIG.AUTO_UNCLAIM_ENABLED ? `enabled (${CONFIG.AUTO_UNCLAIM_AFTER_HOURS}h)` : 'disabled' },
|
{ name: 'Auto-unclaim', value: CONFIG.AUTO_UNCLAIM_ENABLED ? `enabled (${CONFIG.AUTO_UNCLAIM_AFTER_HOURS}h)` : 'disabled' },
|
||||||
{ name: 'Claim timeout', value: CONFIG.CLAIM_TIMEOUT_ENABLED ? `enabled (${CONFIG.CLAIM_TIMEOUT_HOURS}h)` : 'disabled' },
|
|
||||||
{ name: 'Gmail log', value: CONFIG.GMAIL_LOG_CHANNEL_ID ? 'configured' : 'not configured' },
|
{ name: 'Gmail log', value: CONFIG.GMAIL_LOG_CHANNEL_ID ? 'configured' : 'not configured' },
|
||||||
{ name: 'Automation log', value: CONFIG.AUTOMATION_LOG_CHANNEL_ID ? 'configured' : 'not configured' },
|
{ name: 'Automation log', value: CONFIG.AUTOMATION_LOG_CHANNEL_ID ? 'configured' : 'not configured' },
|
||||||
{ name: 'Staff threads', value: CONFIG.STAFF_THREAD_ENABLED ? `enabled (name: "${CONFIG.STAFF_THREAD_NAME}")` : 'disabled' },
|
{ name: 'Staff threads', value: CONFIG.STAFF_THREAD_ENABLED ? `enabled (name: "${CONFIG.STAFF_THREAD_NAME}")` : 'disabled' },
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ const {
|
|||||||
ContextMenuCommandBuilder,
|
ContextMenuCommandBuilder,
|
||||||
ApplicationCommandType
|
ApplicationCommandType
|
||||||
} = require('discord.js');
|
} = require('discord.js');
|
||||||
const { CONFIG, TICKET_TAGS } = require('../config');
|
const { CONFIG } = require('../config');
|
||||||
|
|
||||||
async function registerCommands() {
|
async function registerCommands() {
|
||||||
if (!CONFIG.CLIENT_ID || !CONFIG.DISCORD_GUILD_ID) return;
|
if (!CONFIG.CLIENT_ID || !CONFIG.DISCORD_GUILD_ID) return;
|
||||||
@@ -22,7 +22,7 @@ async function registerCommands() {
|
|||||||
const commands = [
|
const commands = [
|
||||||
new SlashCommandBuilder()
|
new SlashCommandBuilder()
|
||||||
.setName('escalate')
|
.setName('escalate')
|
||||||
.setDescription('Escalate this ticket to tier 2 or tier 3')
|
.setDescription('Escalate this ticket to tier 2 or tier 3 (always unclaims)')
|
||||||
.setContexts([InteractionContextType.Guild])
|
.setContexts([InteractionContextType.Guild])
|
||||||
.setIntegrationTypes([ApplicationIntegrationType.GuildInstall])
|
.setIntegrationTypes([ApplicationIntegrationType.GuildInstall])
|
||||||
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages)
|
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages)
|
||||||
@@ -35,16 +35,6 @@ async function registerCommands() {
|
|||||||
{ name: 'Tier 2', value: '2' },
|
{ name: 'Tier 2', value: '2' },
|
||||||
{ name: 'Tier 3', value: '3' }
|
{ name: 'Tier 3', value: '3' }
|
||||||
)
|
)
|
||||||
)
|
|
||||||
.addStringOption(opt =>
|
|
||||||
opt
|
|
||||||
.setName('action')
|
|
||||||
.setDescription('Unclaim ticket or keep current claimer')
|
|
||||||
.setRequired(true)
|
|
||||||
.addChoices(
|
|
||||||
{ name: 'Unclaim', value: 'unclaim' },
|
|
||||||
{ name: 'Keep', value: 'keep' }
|
|
||||||
)
|
|
||||||
),
|
),
|
||||||
|
|
||||||
new SlashCommandBuilder()
|
new SlashCommandBuilder()
|
||||||
@@ -128,19 +118,6 @@ async function registerCommands() {
|
|||||||
.setRequired(true)
|
.setRequired(true)
|
||||||
),
|
),
|
||||||
|
|
||||||
new SlashCommandBuilder()
|
|
||||||
.setName('tag')
|
|
||||||
.setDescription('Set ticket category (dropdown)')
|
|
||||||
.setContexts([InteractionContextType.Guild])
|
|
||||||
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages)
|
|
||||||
.addStringOption(o =>
|
|
||||||
o
|
|
||||||
.setName('category')
|
|
||||||
.setDescription('Ticket category tag')
|
|
||||||
.setRequired(true)
|
|
||||||
.addChoices(...(TICKET_TAGS || []).map(({ value, emoji, name }) => ({ name: `${emoji} ${name}`, value })))
|
|
||||||
),
|
|
||||||
|
|
||||||
new SlashCommandBuilder()
|
new SlashCommandBuilder()
|
||||||
.setName('response')
|
.setName('response')
|
||||||
.setDescription('Saved response tags (custom templates)')
|
.setDescription('Saved response tags (custom templates)')
|
||||||
@@ -332,25 +309,6 @@ async function registerCommands() {
|
|||||||
.setRequired(false)
|
.setRequired(false)
|
||||||
),
|
),
|
||||||
|
|
||||||
new SlashCommandBuilder()
|
|
||||||
.setName('priority')
|
|
||||||
.setDescription('Set the priority of this ticket')
|
|
||||||
.setContexts([InteractionContextType.Guild])
|
|
||||||
.setIntegrationTypes([ApplicationIntegrationType.GuildInstall])
|
|
||||||
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages)
|
|
||||||
.addStringOption(opt =>
|
|
||||||
opt
|
|
||||||
.setName('level')
|
|
||||||
.setDescription('Priority level')
|
|
||||||
.setRequired(true)
|
|
||||||
.addChoices(
|
|
||||||
{ name: '🟢 Low', value: 'low' },
|
|
||||||
{ name: '🟡 Normal', value: 'normal' },
|
|
||||||
{ name: '🟠 Medium', value: 'medium' },
|
|
||||||
{ name: '🔴 High', value: 'high' }
|
|
||||||
)
|
|
||||||
),
|
|
||||||
|
|
||||||
new SlashCommandBuilder()
|
new SlashCommandBuilder()
|
||||||
.setName('search')
|
.setName('search')
|
||||||
.setDescription('Search for tickets')
|
.setDescription('Search for tickets')
|
||||||
@@ -384,52 +342,6 @@ async function registerCommands() {
|
|||||||
.setIntegrationTypes([ApplicationIntegrationType.GuildInstall])
|
.setIntegrationTypes([ApplicationIntegrationType.GuildInstall])
|
||||||
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
|
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
|
||||||
|
|
||||||
new SlashCommandBuilder()
|
|
||||||
.setName('notification')
|
|
||||||
.setDescription('Manage your staff notification settings')
|
|
||||||
.setContexts([InteractionContextType.Guild])
|
|
||||||
.setIntegrationTypes([ApplicationIntegrationType.GuildInstall])
|
|
||||||
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages)
|
|
||||||
.addSubcommand(sub =>
|
|
||||||
sub
|
|
||||||
.setName('set')
|
|
||||||
.setDescription('Set your notification cooldown (hours between alerts per ticket)')
|
|
||||||
.addIntegerOption(opt =>
|
|
||||||
opt
|
|
||||||
.setName('hours')
|
|
||||||
.setDescription('Cooldown in hours (1–6)')
|
|
||||||
.setMinValue(1)
|
|
||||||
.setMaxValue(6)
|
|
||||||
.setRequired(true)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.addSubcommand(sub =>
|
|
||||||
sub
|
|
||||||
.setName('add')
|
|
||||||
.setDescription('Create a notification channel for a staff member')
|
|
||||||
.addUserOption(opt =>
|
|
||||||
opt.setName('member').setDescription('Staff member').setRequired(true)
|
|
||||||
)
|
|
||||||
),
|
|
||||||
|
|
||||||
new SlashCommandBuilder()
|
|
||||||
.setName('staffnotification')
|
|
||||||
.setDescription('Override notification cooldown for another staff member (admin only)')
|
|
||||||
.setContexts([InteractionContextType.Guild])
|
|
||||||
.setIntegrationTypes([ApplicationIntegrationType.GuildInstall])
|
|
||||||
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
|
|
||||||
.addUserOption(opt =>
|
|
||||||
opt.setName('member').setDescription('Staff member').setRequired(true)
|
|
||||||
)
|
|
||||||
.addIntegerOption(opt =>
|
|
||||||
opt
|
|
||||||
.setName('hours')
|
|
||||||
.setDescription('Cooldown in hours (1–6)')
|
|
||||||
.setMinValue(1)
|
|
||||||
.setMaxValue(6)
|
|
||||||
.setRequired(true)
|
|
||||||
),
|
|
||||||
|
|
||||||
new SlashCommandBuilder()
|
new SlashCommandBuilder()
|
||||||
.setName('closetimer')
|
.setName('closetimer')
|
||||||
.setDescription('Set the force-close countdown duration')
|
.setDescription('Set the force-close countdown duration')
|
||||||
|
|||||||
156
config.js
156
config.js
@@ -30,88 +30,11 @@ if (!envPath) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const DEFAULT_NOTIFICATION_THRESHOLDS = {
|
|
||||||
// patternChecker - age-based (time since condition first became true)
|
|
||||||
user_tickets: ['15m', '30m', '1h', '3h'],
|
|
||||||
user_reopen: ['1h', '4h', '1d'],
|
|
||||||
user_crossgame: ['1h', '1d'],
|
|
||||||
game_surge: ['15m', '30m', '1h'],
|
|
||||||
game_backlog: ['30m', '1h', '3h', '6h'],
|
|
||||||
game_resolution: ['1d'],
|
|
||||||
game_spike: ['15m', '30m'],
|
|
||||||
tag_top: ['1h', '6h', '1d'],
|
|
||||||
tag_escalation: ['1h', '6h', '1d'],
|
|
||||||
untagged_closes: ['1h', '1d'],
|
|
||||||
tag_game_corr: ['1d'],
|
|
||||||
user_esc: ['1h', '6h', '1d'],
|
|
||||||
game_esc_rate: ['1d'],
|
|
||||||
rapid_t2_t3: ['3', '5', '10', '15', '20', '30', '50'], // count-based milestones, not time
|
|
||||||
staff_no_close: ['1h', '3h'],
|
|
||||||
staff_overloaded: ['1h', '3h', '6h'],
|
|
||||||
staff_stale: ['1h', '3h'],
|
|
||||||
staff_transfer_rate: ['1h', '1d'],
|
|
||||||
staff_esc: ['1h', '6h', '1d'],
|
|
||||||
staff_game_esc: ['1d'],
|
|
||||||
game_tag_spike: ['1h', '6h'],
|
|
||||||
overnight_gap: ['1d'],
|
|
||||||
staff_always_esc: ['1d'],
|
|
||||||
// surgeChecker - cooldown-escalating (repeat alerts spaced further apart)
|
|
||||||
surge_tickets: ['10m', '30m', '1h', '2h', '3h'],
|
|
||||||
surge_game: ['10m', '30m', '1h', '2h'],
|
|
||||||
surge_stale: ['30m', '1h', '2h', '4h'],
|
|
||||||
surge_needs_response: ['15m', '30m', '1h', '3h'],
|
|
||||||
surge_unclaimed: ['15m', '30m', '1h', '2h', '4h'],
|
|
||||||
surge_tier3_unclaimed: ['10m', '15m', '30m', '1h', '2h'],
|
|
||||||
surge_no_staff: ['10m', '20m', '30m', '1h'],
|
|
||||||
// staffNotifications - age-based per ticket (hours)
|
|
||||||
unclaimed_reminder: ['1h', '2h', '4h', '8h', '1d'],
|
|
||||||
// chatAlertChecker - cooldown-escalating
|
|
||||||
chat_messages: ['15m', '30m', '1h', '3h'],
|
|
||||||
chat_time: ['30m', '1h', '2h', '4h']
|
|
||||||
};
|
|
||||||
|
|
||||||
function toInt(v, fallback) {
|
function toInt(v, fallback) {
|
||||||
const n = parseInt(v, 10);
|
const n = parseInt(v, 10);
|
||||||
return Number.isFinite(n) ? n : fallback;
|
return Number.isFinite(n) ? n : fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseThresholdString(str) {
|
|
||||||
const value = String(str || '').trim();
|
|
||||||
if (!value) return NaN;
|
|
||||||
|
|
||||||
// Integers without a unit are raw count milestones.
|
|
||||||
if (/^\d+$/.test(value)) return parseInt(value, 10);
|
|
||||||
|
|
||||||
let totalMs = 0;
|
|
||||||
const re = /(\d+)([mhd])/g;
|
|
||||||
let match;
|
|
||||||
let consumed = '';
|
|
||||||
while ((match = re.exec(value)) !== null) {
|
|
||||||
const amount = parseInt(match[1], 10);
|
|
||||||
const unit = match[2];
|
|
||||||
consumed += match[0];
|
|
||||||
if (unit === 'm') totalMs += amount * 60 * 1000;
|
|
||||||
else if (unit === 'h') totalMs += amount * 60 * 60 * 1000;
|
|
||||||
else if (unit === 'd') totalMs += amount * 24 * 60 * 60 * 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!consumed || consumed !== value) return NaN;
|
|
||||||
return totalMs;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseNotificationThresholdsJson(raw) {
|
|
||||||
if (!raw || !String(raw).trim()) return DEFAULT_NOTIFICATION_THRESHOLDS;
|
|
||||||
try {
|
|
||||||
const parsedJson = JSON.parse(raw);
|
|
||||||
if (parsedJson && typeof parsedJson === 'object' && !Array.isArray(parsedJson)) {
|
|
||||||
return parsedJson;
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[config] Failed to parse NOTIFICATION_THRESHOLDS_JSON, using default:', err.message);
|
|
||||||
}
|
|
||||||
return DEFAULT_NOTIFICATION_THRESHOLDS;
|
|
||||||
}
|
|
||||||
|
|
||||||
const CONFIG = {
|
const CONFIG = {
|
||||||
DISCORD_TOKEN: (process.env.DISCORD_TOKEN || process.env.DISCORD_BOT_TOKEN || '').trim(),
|
DISCORD_TOKEN: (process.env.DISCORD_TOKEN || process.env.DISCORD_BOT_TOKEN || '').trim(),
|
||||||
DISCORD_GUILD_ID: process.env.DISCORD_GUILD_ID || null,
|
DISCORD_GUILD_ID: process.env.DISCORD_GUILD_ID || null,
|
||||||
@@ -181,8 +104,6 @@ const CONFIG = {
|
|||||||
PRIORITY_HIGH_EMOJI: process.env.PRIORITY_HIGH_EMOJI || '🔴',
|
PRIORITY_HIGH_EMOJI: process.env.PRIORITY_HIGH_EMOJI || '🔴',
|
||||||
PRIORITY_MEDIUM_EMOJI: process.env.PRIORITY_MEDIUM_EMOJI || '🟡',
|
PRIORITY_MEDIUM_EMOJI: process.env.PRIORITY_MEDIUM_EMOJI || '🟡',
|
||||||
PRIORITY_LOW_EMOJI: process.env.PRIORITY_LOW_EMOJI || '🟢',
|
PRIORITY_LOW_EMOJI: process.env.PRIORITY_LOW_EMOJI || '🟢',
|
||||||
CLAIM_TIMEOUT_ENABLED: process.env.CLAIM_TIMEOUT_ENABLED === 'true',
|
|
||||||
CLAIM_TIMEOUT_HOURS: toInt(process.env.CLAIM_TIMEOUT_HOURS, 48),
|
|
||||||
AUTO_UNCLAIM_ENABLED: process.env.AUTO_UNCLAIM_ENABLED === 'true',
|
AUTO_UNCLAIM_ENABLED: process.env.AUTO_UNCLAIM_ENABLED === 'true',
|
||||||
AUTO_UNCLAIM_AFTER_HOURS: toInt(process.env.AUTO_UNCLAIM_AFTER_HOURS, 24),
|
AUTO_UNCLAIM_AFTER_HOURS: toInt(process.env.AUTO_UNCLAIM_AFTER_HOURS, 24),
|
||||||
ALLOW_CLAIM_OVERWRITE: process.env.ALLOW_CLAIM_OVERWRITE === 'true',
|
ALLOW_CLAIM_OVERWRITE: process.env.ALLOW_CLAIM_OVERWRITE === 'true',
|
||||||
@@ -199,25 +120,7 @@ const CONFIG = {
|
|||||||
EMBED_COLOR_CLAIMED: toInt(process.env.EMBED_COLOR_CLAIMED, 0xFFFF00),
|
EMBED_COLOR_CLAIMED: toInt(process.env.EMBED_COLOR_CLAIMED, 0xFFFF00),
|
||||||
EMBED_COLOR_ESCALATED: toInt(process.env.EMBED_COLOR_ESCALATED, 0xFF6600),
|
EMBED_COLOR_ESCALATED: toInt(process.env.EMBED_COLOR_ESCALATED, 0xFF6600),
|
||||||
EMBED_COLOR_INFO: toInt(process.env.EMBED_COLOR_INFO, 0x1e2124),
|
EMBED_COLOR_INFO: toInt(process.env.EMBED_COLOR_INFO, 0x1e2124),
|
||||||
STAFF_CATEGORIES: new Map(), // deprecated – kept for staffChannel.js compat
|
|
||||||
STAFF_EMOJIS: (() => {
|
|
||||||
const raw = process.env.STAFF_EMOJIS;
|
|
||||||
const map = new Map();
|
|
||||||
if (!raw || !String(raw).trim()) return map;
|
|
||||||
for (const part of String(raw).split(',')) {
|
|
||||||
const seg = part.trim();
|
|
||||||
if (!seg) continue;
|
|
||||||
const idx = seg.indexOf(':');
|
|
||||||
if (idx === -1) continue;
|
|
||||||
const userId = seg.slice(0, idx).trim();
|
|
||||||
const emoji = seg.slice(idx + 1).trim();
|
|
||||||
if (userId && emoji) map.set(userId, emoji);
|
|
||||||
}
|
|
||||||
return map;
|
|
||||||
})(),
|
|
||||||
CLAIMER_EMOJI_FALLBACK: process.env.CLAIMER_EMOJI_FALLBACK || '🎫',
|
|
||||||
ADMIN_ID: process.env.ADMIN_ID || null,
|
ADMIN_ID: process.env.ADMIN_ID || null,
|
||||||
STAFF_NOTIFICATION_CATEGORY_ID: process.env.STAFF_NOTIFICATION_CATEGORY_ID || null,
|
|
||||||
FORCE_CLOSE_TIMER: toInt(process.env.FORCE_CLOSE_TIMER_SECONDS, 60),
|
FORCE_CLOSE_TIMER: toInt(process.env.FORCE_CLOSE_TIMER_SECONDS, 60),
|
||||||
GMAIL_POLL_INTERVAL_MS: toInt(process.env.GMAIL_POLL_INTERVAL_SECONDS, 30) * 1000,
|
GMAIL_POLL_INTERVAL_MS: toInt(process.env.GMAIL_POLL_INTERVAL_SECONDS, 30) * 1000,
|
||||||
GMAIL_LOG_CHANNEL_ID: process.env.GMAIL_LOG_CHANNEL_ID || null,
|
GMAIL_LOG_CHANNEL_ID: process.env.GMAIL_LOG_CHANNEL_ID || null,
|
||||||
@@ -225,42 +128,6 @@ const CONFIG = {
|
|||||||
RENAME_LOG_CHANNEL_ID: process.env.RENAME_LOG_CHANNEL_ID || null,
|
RENAME_LOG_CHANNEL_ID: process.env.RENAME_LOG_CHANNEL_ID || null,
|
||||||
SECURITY_LOG_CHANNEL_ID: process.env.SECURITY_LOG_CHANNEL_ID || null,
|
SECURITY_LOG_CHANNEL_ID: process.env.SECURITY_LOG_CHANNEL_ID || null,
|
||||||
SYSTEM_LOG_CHANNEL_ID: process.env.SYSTEM_LOG_CHANNEL_ID || null,
|
SYSTEM_LOG_CHANNEL_ID: process.env.SYSTEM_LOG_CHANNEL_ID || null,
|
||||||
USER_PATTERNS_CHANNEL_ID: process.env.USER_PATTERNS_CHANNEL_ID || null,
|
|
||||||
GAME_PATTERNS_CHANNEL_ID: process.env.GAME_PATTERNS_CHANNEL_ID || null,
|
|
||||||
TAG_PATTERNS_CHANNEL_ID: process.env.TAG_PATTERNS_CHANNEL_ID || null,
|
|
||||||
ESCALATION_PATTERNS_CHANNEL_ID: process.env.ESCALATION_PATTERNS_CHANNEL_ID || null,
|
|
||||||
STAFF_PATTERNS_CHANNEL_ID: process.env.STAFF_PATTERNS_CHANNEL_ID || null,
|
|
||||||
COMBINED_PATTERNS_CHANNEL_ID: process.env.COMBINED_PATTERNS_CHANNEL_ID || null,
|
|
||||||
PATTERN_USER_TICKET_THRESHOLD: toInt(process.env.PATTERN_USER_TICKET_THRESHOLD, 3),
|
|
||||||
PATTERN_GAME_TICKET_THRESHOLD: toInt(process.env.PATTERN_GAME_TICKET_THRESHOLD, 10),
|
|
||||||
PATTERN_STAFF_STALE_PING_THRESHOLD: toInt(process.env.PATTERN_STAFF_STALE_PING_THRESHOLD, 5),
|
|
||||||
PATTERN_ESCALATION_THRESHOLD: toInt(process.env.PATTERN_ESCALATION_THRESHOLD, 3),
|
|
||||||
PATTERN_RAPID_CLOSE_SECONDS: toInt(process.env.PATTERN_RAPID_CLOSE_SECONDS, 120),
|
|
||||||
PATTERN_UNCLAIMED_HOURS: toInt(process.env.PATTERN_UNCLAIMED_HOURS, 4),
|
|
||||||
PATTERN_CHECK_INTERVAL_MINUTES: toInt(process.env.PATTERN_CHECK_INTERVAL_MINUTES, 30),
|
|
||||||
ALL_STAFF_CHANNEL_ID: process.env.ALL_STAFF_CHANNEL_ID || null,
|
|
||||||
ALL_STAFF_CHAT_ALERT_CHANNEL_ID: process.env.ALL_STAFF_CHAT_ALERT_CHANNEL_ID || null,
|
|
||||||
SURGE_ROLE_ID: process.env.SURGE_ROLE_ID || null,
|
|
||||||
SURGE_TICKET_COUNT: toInt(process.env.SURGE_TICKET_COUNT, 10),
|
|
||||||
SURGE_TICKET_WINDOW_MINUTES: toInt(process.env.SURGE_TICKET_WINDOW_MINUTES, 30),
|
|
||||||
SURGE_GAME_TICKET_COUNT: toInt(process.env.SURGE_GAME_TICKET_COUNT, 5),
|
|
||||||
SURGE_GAME_TICKET_WINDOW_MINUTES: toInt(process.env.SURGE_GAME_TICKET_WINDOW_MINUTES, 30),
|
|
||||||
SURGE_STALE_COUNT: toInt(process.env.SURGE_STALE_COUNT, 8),
|
|
||||||
SURGE_STALE_HOURS: toInt(process.env.SURGE_STALE_HOURS, 2),
|
|
||||||
SURGE_NEEDS_RESPONSE_COUNT: toInt(process.env.SURGE_NEEDS_RESPONSE_COUNT, 5),
|
|
||||||
SURGE_NEEDS_RESPONSE_HOURS: toInt(process.env.SURGE_NEEDS_RESPONSE_HOURS, 1),
|
|
||||||
SURGE_UNCLAIMED_COUNT: toInt(process.env.SURGE_UNCLAIMED_COUNT, 5),
|
|
||||||
SURGE_UNCLAIMED_MINUTES: toInt(process.env.SURGE_UNCLAIMED_MINUTES, 30),
|
|
||||||
SURGE_TIER3_UNCLAIMED_MINUTES: toInt(process.env.SURGE_TIER3_UNCLAIMED_MINUTES, 15),
|
|
||||||
SURGE_COOLDOWN_MINUTES: toInt(process.env.SURGE_COOLDOWN_MINUTES, 60),
|
|
||||||
CHAT_ALERT_CHANNEL_IDS: (process.env.CHAT_ALERT_CHANNEL_IDS || '').split(',').filter(Boolean),
|
|
||||||
CHAT_ALERT_MESSAGE_COUNT: toInt(process.env.CHAT_ALERT_MESSAGE_COUNT, 5),
|
|
||||||
CHAT_ALERT_HOURS_WITHOUT_RESPONSE: toInt(process.env.CHAT_ALERT_HOURS_WITHOUT_RESPONSE, 2),
|
|
||||||
CHAT_ALERT_COOLDOWN_MINUTES: toInt(process.env.CHAT_ALERT_COOLDOWN_MINUTES, 60),
|
|
||||||
STAFF_IDS: (process.env.STAFF_IDS || '').split(',').map(s => s.trim()).filter(Boolean),
|
|
||||||
SURGE_NO_STAFF_COOLDOWN_MINUTES: toInt(process.env.SURGE_NO_STAFF_COOLDOWN_MINUTES, 30),
|
|
||||||
SURGE_NO_STAFF_OPEN_TICKET_THRESHOLD: toInt(process.env.SURGE_NO_STAFF_OPEN_TICKET_THRESHOLD, 3),
|
|
||||||
STAFF_DND_COUNTS_AS_AVAILABLE: process.env.STAFF_DND_COUNTS_AS_AVAILABLE === 'true',
|
|
||||||
STAFF_THREAD_ENABLED: process.env.STAFF_THREAD_ENABLED === 'true',
|
STAFF_THREAD_ENABLED: process.env.STAFF_THREAD_ENABLED === 'true',
|
||||||
STAFF_THREAD_NAME: process.env.STAFF_THREAD_NAME || 'Staff Discussion',
|
STAFF_THREAD_NAME: process.env.STAFF_THREAD_NAME || 'Staff Discussion',
|
||||||
STAFF_THREAD_AUTO_ADD_ROLE: process.env.STAFF_THREAD_AUTO_ADD_ROLE === 'true',
|
STAFF_THREAD_AUTO_ADD_ROLE: process.env.STAFF_THREAD_AUTO_ADD_ROLE === 'true',
|
||||||
@@ -273,28 +140,9 @@ const CONFIG = {
|
|||||||
SETTINGS_ADMIN_PASSWORD: process.env.SETTINGS_ADMIN_PASSWORD || null,
|
SETTINGS_ADMIN_PASSWORD: process.env.SETTINGS_ADMIN_PASSWORD || null,
|
||||||
SETTINGS_DOMAIN: process.env.SETTINGS_DOMAIN || 'tickets.indifferentketchup.com',
|
SETTINGS_DOMAIN: process.env.SETTINGS_DOMAIN || 'tickets.indifferentketchup.com',
|
||||||
INTERNAL_API_PORT: toInt(process.env.INTERNAL_API_PORT, 12753),
|
INTERNAL_API_PORT: toInt(process.env.INTERNAL_API_PORT, 12753),
|
||||||
INTERNAL_API_SECRET: process.env.INTERNAL_API_SECRET || null,
|
INTERNAL_API_SECRET: process.env.INTERNAL_API_SECRET || null
|
||||||
NOTIFICATION_THRESHOLDS: parseNotificationThresholdsJson(process.env.NOTIFICATION_THRESHOLDS_JSON),
|
|
||||||
UNCLAIMED_REMINDER_THRESHOLDS: (process.env.UNCLAIMED_REMINDER_THRESHOLDS || '1,2,4')
|
|
||||||
.split(',')
|
|
||||||
.map(s => parseInt(s.trim(), 10))
|
|
||||||
.filter(n => !isNaN(n) && n > 0)
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Ticket category tags for /tag set – [emoji] [label] in dropdown; priority emoji always first in channel name, then tag emoji. */
|
|
||||||
const TICKET_TAGS = [
|
|
||||||
{ value: 'server-down', emoji: '⬇️', name: 'Server Down' },
|
|
||||||
{ value: 'stuck-restarting', emoji: '⏳', name: 'Stuck Restarting' },
|
|
||||||
{ value: 'cant-connect', emoji: '📵', name: "Can't Connect" },
|
|
||||||
{ value: 'server-lag', emoji: '🐌', name: 'Server Lag' },
|
|
||||||
{ value: 'billing', emoji: '💳', name: 'Billing' },
|
|
||||||
{ value: 'refund-request', emoji: '💸', name: 'Refund Request' },
|
|
||||||
{ value: 'mod-help', emoji: '🔧', name: 'Mod Help' },
|
|
||||||
{ value: 'backup-restore', emoji: '💾', name: 'Backup Restore' },
|
|
||||||
{ value: 'world-save', emoji: '🌍', name: 'World / Save' },
|
|
||||||
{ value: 'server-config', emoji: '⚙️', name: 'Server Config' }
|
|
||||||
];
|
|
||||||
|
|
||||||
const GAME_NAMES = (CONFIG.GAME_LIST || '')
|
const GAME_NAMES = (CONFIG.GAME_LIST || '')
|
||||||
.split(',')
|
.split(',')
|
||||||
.map(g => g.trim())
|
.map(g => g.trim())
|
||||||
@@ -346,8 +194,6 @@ const GAME_NAME_TO_KEY = {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
CONFIG,
|
CONFIG,
|
||||||
parseThresholdString,
|
|
||||||
TICKET_TAGS,
|
|
||||||
GAME_NAMES,
|
GAME_NAMES,
|
||||||
GAME_ALIASES,
|
GAME_ALIASES,
|
||||||
GAME_NAME_TO_KEY
|
GAME_NAME_TO_KEY
|
||||||
|
|||||||
@@ -16,13 +16,13 @@ const {
|
|||||||
stripEmailQuotes,
|
stripEmailQuotes,
|
||||||
stripMobileFooter,
|
stripMobileFooter,
|
||||||
detectGame,
|
detectGame,
|
||||||
enforceEmbedLimit
|
enforceEmbedLimit,
|
||||||
|
sanitizeEmbedText
|
||||||
} = require('./utils');
|
} = require('./utils');
|
||||||
const { getGmailClient } = require('./services/gmail');
|
const { getGmailClient } = require('./services/gmail');
|
||||||
const { getNextTicketNumber, checkTicketLimits, getOrCreateTicketCategory, createEmailTicketAsThread, toDiscordSafeName, getSenderLocal } = require('./services/tickets');
|
const { getNextTicketNumber, checkTicketLimits, getOrCreateTicketCategory, createEmailTicketAsThread, toDiscordSafeName, getSenderLocal } = require('./services/tickets');
|
||||||
const { getEmailRouting } = require('./services/guildSettings');
|
const { getEmailRouting } = require('./services/guildSettings');
|
||||||
const { logError, logGmail, logAutomation } = require('./services/debugLog');
|
const { logError, logGmail, logAutomation } = require('./services/debugLog');
|
||||||
const { increment } = require('./services/patternStore');
|
|
||||||
const { enqueueSend } = require('./services/channelQueue');
|
const { enqueueSend } = require('./services/channelQueue');
|
||||||
|
|
||||||
const Ticket = mongoose.model('Ticket');
|
const Ticket = mongoose.model('Ticket');
|
||||||
@@ -253,10 +253,10 @@ async function poll(client) {
|
|||||||
const ticketInfoEmbed = new EmbedBuilder()
|
const ticketInfoEmbed = new EmbedBuilder()
|
||||||
.setColor(CONFIG.EMBED_COLOR_INFO)
|
.setColor(CONFIG.EMBED_COLOR_INFO)
|
||||||
.addFields(
|
.addFields(
|
||||||
{ name: 'Name', value: `\`${sName}\``, inline: false },
|
{ name: 'Name', value: `\`\`\`\n${sanitizeEmbedText(sName)}\n\`\`\``, inline: false },
|
||||||
{ name: 'Email', value: `\`${sEmail}\``, inline: false },
|
{ name: 'Email', value: `\`\`\`\n${sanitizeEmbedText(sEmail)}\n\`\`\``, inline: false },
|
||||||
{ name: 'Game', value: `\`${detectedGame}\``, inline: false },
|
{ name: 'Game', value: `\`\`\`\n${sanitizeEmbedText(detectedGame)}\n\`\`\``, inline: false },
|
||||||
{ name: 'Subject', value: `\`${subject || 'No subject'}\``, inline: false }
|
{ name: 'Subject', value: `\`\`\`\n${sanitizeEmbedText(subject) || 'No subject'}\n\`\`\``, inline: false }
|
||||||
);
|
);
|
||||||
|
|
||||||
enforceEmbedLimit([ticketInfoEmbed]);
|
enforceEmbedLimit([ticketInfoEmbed]);
|
||||||
@@ -347,12 +347,6 @@ async function poll(client) {
|
|||||||
));
|
));
|
||||||
totalProcessed++;
|
totalProcessed++;
|
||||||
logGmail(subject, sEmail, number, detectedGame).catch(() => {});
|
logGmail(subject, sEmail, number, detectedGame).catch(() => {});
|
||||||
increment('user_tickets', sEmail, 'today');
|
|
||||||
increment('user_tickets', sEmail, 'week');
|
|
||||||
if (detectedGame) {
|
|
||||||
increment('game_tickets', detectedGame, 'today');
|
|
||||||
increment('game_tickets', detectedGame, 'week');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
console.log('Archiving/reading Gmail message', msgRef.id);
|
console.log('Archiving/reading Gmail message', msgRef.id);
|
||||||
await gmail.users.messages.batchModify({
|
await gmail.users.messages.batchModify({
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ const { enqueueRename, enqueueSend } = require('../services/channelQueue');
|
|||||||
const { runEscalation, runDeescalation } = require('./commands');
|
const { runEscalation, runDeescalation } = require('./commands');
|
||||||
const { trackInteraction, trackError } = require('./analytics');
|
const { trackInteraction, trackError } = require('./analytics');
|
||||||
const { pendingCloses } = require('./pendingCloses');
|
const { pendingCloses } = require('./pendingCloses');
|
||||||
const { increment } = require('../services/patternStore');
|
|
||||||
const { logError, logSystem } = require('../services/debugLog');
|
const { logError, logSystem } = require('../services/debugLog');
|
||||||
|
|
||||||
const Ticket = mongoose.model('Ticket');
|
const Ticket = mongoose.model('Ticket');
|
||||||
@@ -342,11 +341,8 @@ async function handleClaim(interaction, ticket) {
|
|||||||
);
|
);
|
||||||
freshTicket.claimedBy = claimerLabel;
|
freshTicket.claimedBy = claimerLabel;
|
||||||
freshTicket.claimerId = interaction.user.id;
|
freshTicket.claimerId = interaction.user.id;
|
||||||
increment('staff_claims', interaction.user.id, 'today');
|
|
||||||
increment('staff_claims', interaction.user.id, 'week');
|
|
||||||
|
|
||||||
// Resolve claimerEmoji from STAFF_EMOJIS map (fallback to CLAIMER_EMOJI_FALLBACK)
|
const claimerEmoji = '🎫';
|
||||||
const claimerEmoji = CONFIG.STAFF_EMOJIS.get(interaction.user.id) || CONFIG.CLAIMER_EMOJI_FALLBACK;
|
|
||||||
const creatorNickname = await resolveCreatorNickname(guild, freshTicket);
|
const creatorNickname = await resolveCreatorNickname(guild, freshTicket);
|
||||||
|
|
||||||
const state = freshTicket.escalated ? 'escalated-claimed' : 'claimed';
|
const state = freshTicket.escalated ? 'escalated-claimed' : 'claimed';
|
||||||
@@ -385,11 +381,10 @@ async function handleClaim(interaction, ticket) {
|
|||||||
// Unclaim
|
// Unclaim
|
||||||
await Ticket.updateOne(
|
await Ticket.updateOne(
|
||||||
{ gmailThreadId: freshTicket.gmailThreadId },
|
{ gmailThreadId: freshTicket.gmailThreadId },
|
||||||
{ $set: { claimedBy: null, claimerId: null, staffChannelId: null } }
|
{ $set: { claimedBy: null, claimerId: null } }
|
||||||
);
|
);
|
||||||
freshTicket.claimedBy = null;
|
freshTicket.claimedBy = null;
|
||||||
freshTicket.claimerId = null;
|
freshTicket.claimerId = null;
|
||||||
freshTicket.staffChannelId = null;
|
|
||||||
|
|
||||||
const creatorNicknameUnclaim = await resolveCreatorNickname(guild, freshTicket);
|
const creatorNicknameUnclaim = await resolveCreatorNickname(guild, freshTicket);
|
||||||
const unclaimState = (freshTicket.escalationTier ?? 0) >= 1 ? 'escalated' : 'unclaimed';
|
const unclaimState = (freshTicket.escalationTier ?? 0) >= 1 ? 'escalated' : 'unclaimed';
|
||||||
@@ -425,10 +420,6 @@ async function handleClaim(interaction, ticket) {
|
|||||||
// --- CONFIRM CLOSE ---
|
// --- CONFIRM CLOSE ---
|
||||||
async function handleConfirmClose(interaction, ticket) {
|
async function handleConfirmClose(interaction, ticket) {
|
||||||
const closedAt = new Date();
|
const closedAt = new Date();
|
||||||
increment('staff_closes', interaction.user.id, 'today');
|
|
||||||
if (!ticket.ticketTag) {
|
|
||||||
increment('untagged_closes', 'total', 'today');
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
await interaction.update({ content: 'Archiving and closing...', components: [] });
|
await interaction.update({ content: 'Archiving and closing...', components: [] });
|
||||||
} catch {
|
} catch {
|
||||||
@@ -563,13 +554,6 @@ async function handleConfirmClose(interaction, ticket) {
|
|||||||
{ $set: { discordThreadId: null, status: 'closed' } }
|
{ $set: { discordThreadId: null, status: 'closed' } }
|
||||||
);
|
);
|
||||||
|
|
||||||
try {
|
|
||||||
const { deleteStaffChannel } = require('../services/staffChannel');
|
|
||||||
await deleteStaffChannel(interaction.guild, ticket.staffChannelId);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Delete staff channel (close):', e);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (transcriptMsg?.id) {
|
if (transcriptMsg?.id) {
|
||||||
await Transcript.create({
|
await Transcript.create({
|
||||||
gmailThreadId: ticket.gmailThreadId,
|
gmailThreadId: ticket.gmailThreadId,
|
||||||
@@ -746,13 +730,6 @@ async function handleTicketModal(interaction) {
|
|||||||
await pinMessage(welcomeMsg, interaction.client).catch(() => {});
|
await pinMessage(welcomeMsg, interaction.client).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
increment('user_tickets', interaction.user.id, 'today');
|
|
||||||
increment('user_tickets', interaction.user.id, 'week');
|
|
||||||
if (game) {
|
|
||||||
increment('game_tickets', game, 'today');
|
|
||||||
increment('game_tickets', game, 'week');
|
|
||||||
}
|
|
||||||
|
|
||||||
await interaction.deleteReply().catch(() => {});
|
await interaction.deleteReply().catch(() => {});
|
||||||
|
|
||||||
const logChan = await interaction.client.channels.fetch(CONFIG.LOG_CHAN).catch(() => null);
|
const logChan = await interaction.client.channels.fetch(CONFIG.LOG_CHAN).catch(() => null);
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ const {
|
|||||||
PermissionFlagsBits
|
PermissionFlagsBits
|
||||||
} = require('discord.js');
|
} = require('discord.js');
|
||||||
const { mongoose } = require('../db-connection');
|
const { mongoose } = require('../db-connection');
|
||||||
const { CONFIG, TICKET_TAGS } = require('../config');
|
const { CONFIG } = require('../config');
|
||||||
const { getPriorityEmoji, getPriorityColor, replaceVariables, escapeRegex } = require('../utils');
|
const { getPriorityEmoji, replaceVariables, escapeRegex } = require('../utils');
|
||||||
const { makeTicketName, resolveCreatorNickname, getSenderLocal, toDiscordSafeName, getOrCreateTicketCategory, createDiscordTicketAsThread, checkTicketCreationRateLimit } = require('../services/tickets');
|
const { makeTicketName, resolveCreatorNickname, getOrCreateTicketCategory, createDiscordTicketAsThread, checkTicketCreationRateLimit } = require('../services/tickets');
|
||||||
const { sendTicketNotificationEmail } = require('../services/gmail');
|
const { sendTicketNotificationEmail } = require('../services/gmail');
|
||||||
const { getTicketActionRow } = require('../utils/ticketComponents');
|
const { getTicketActionRow } = require('../utils/ticketComponents');
|
||||||
const { getEmailRouting } = require('../services/guildSettings');
|
const { getEmailRouting } = require('../services/guildSettings');
|
||||||
@@ -24,12 +24,10 @@ const { logTicketEvent, logSecurity, logError } = require('../services/debugLog'
|
|||||||
const { handleAccountInfoCommand } = require('./accountinfo');
|
const { handleAccountInfoCommand } = require('./accountinfo');
|
||||||
const { handleSetupCommand } = require('./setup');
|
const { handleSetupCommand } = require('./setup');
|
||||||
const { pendingCloses } = require('./pendingCloses');
|
const { pendingCloses } = require('./pendingCloses');
|
||||||
const { increment } = require('../services/patternStore');
|
|
||||||
|
|
||||||
const Ticket = mongoose.model('Ticket');
|
const Ticket = mongoose.model('Ticket');
|
||||||
const Tag = mongoose.model('Tag');
|
const Tag = mongoose.model('Tag');
|
||||||
const User = mongoose.model('User');
|
const User = mongoose.model('User');
|
||||||
const StaffNotification = mongoose.model('StaffNotification');
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* True if member has the support role (ROLE_ID_TO_PING) or any ADDITIONAL_STAFF_ROLES.
|
* True if member has the support role (ROLE_ID_TO_PING) or any ADDITIONAL_STAFF_ROLES.
|
||||||
@@ -74,17 +72,11 @@ async function runEscalation(interaction, ticket, nextTier, reason) {
|
|||||||
// Clear claim on escalation
|
// Clear claim on escalation
|
||||||
await Ticket.updateOne(
|
await Ticket.updateOne(
|
||||||
{ gmailThreadId: ticket.gmailThreadId },
|
{ gmailThreadId: ticket.gmailThreadId },
|
||||||
{ $set: { escalated: true, escalationTier: nextTier, claimedBy: null, claimerId: null, unclaimedRemindersSent: [] } }
|
{ $set: { escalated: true, escalationTier: nextTier, claimedBy: null, claimerId: null } }
|
||||||
);
|
);
|
||||||
ticket.escalated = true;
|
ticket.escalated = true;
|
||||||
ticket.escalationTier = nextTier;
|
ticket.escalationTier = nextTier;
|
||||||
ticket.claimedBy = null;
|
ticket.claimedBy = null;
|
||||||
increment('escalations', ticket.game || 'unknown', 'today');
|
|
||||||
increment('escalations', ticket.game || 'unknown', 'week');
|
|
||||||
increment('user_escalations', ticket.senderEmail, 'week');
|
|
||||||
increment('staff_escalations', interaction.user.id, 'today');
|
|
||||||
increment('staff_escalations', interaction.user.id, 'week');
|
|
||||||
if (ticket.game) increment(`staff_game_escalations:${interaction.user.id}`, ticket.game, 'week');
|
|
||||||
|
|
||||||
const creatorNickname = await resolveCreatorNickname(interaction.guild, ticket);
|
const creatorNickname = await resolveCreatorNickname(interaction.guild, ticket);
|
||||||
const newName = makeTicketName('escalated', ticket, creatorNickname);
|
const newName = makeTicketName('escalated', ticket, creatorNickname);
|
||||||
@@ -265,12 +257,11 @@ async function handleCommand(interaction) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// /escalate (tier 2 or 3 via level; works for both email and Discord)
|
// /escalate (tier 2 or 3 via level; works for both email and Discord). Always unclaims on escalate.
|
||||||
if (interaction.commandName === 'escalate') {
|
if (interaction.commandName === 'escalate') {
|
||||||
const reason = null;
|
const reason = null;
|
||||||
const level = interaction.options.getString('level');
|
const level = interaction.options.getString('level');
|
||||||
const nextTier = level === '3' ? 2 : 1;
|
const nextTier = level === '3' ? 2 : 1;
|
||||||
const action = interaction.options.getString('action');
|
|
||||||
|
|
||||||
const ticket = await Ticket.findOne({ discordThreadId: interaction.channel.id }).lean();
|
const ticket = await Ticket.findOne({ discordThreadId: interaction.channel.id }).lean();
|
||||||
if (!ticket) {
|
if (!ticket) {
|
||||||
@@ -301,12 +292,6 @@ async function handleCommand(interaction) {
|
|||||||
try {
|
try {
|
||||||
await interaction.deferReply();
|
await interaction.deferReply();
|
||||||
await runEscalation(interaction, ticket, nextTier, reason);
|
await runEscalation(interaction, ticket, nextTier, reason);
|
||||||
if (action === 'unclaim') {
|
|
||||||
await Ticket.updateOne(
|
|
||||||
{ gmailThreadId: ticket.gmailThreadId },
|
|
||||||
{ $set: { claimedBy: null, claimerId: null } }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Escalate error:', err);
|
console.error('Escalate error:', err);
|
||||||
await interaction.editReply({ content: 'Failed to escalate this ticket.' }).catch(() =>
|
await interaction.editReply({ content: 'Failed to escalate this ticket.' }).catch(() =>
|
||||||
@@ -315,83 +300,6 @@ async function handleCommand(interaction) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// /notification set | /notification add
|
|
||||||
if (interaction.commandName === 'notification') {
|
|
||||||
const sub = interaction.options.getSubcommand();
|
|
||||||
if (sub === 'set') {
|
|
||||||
const hours = interaction.options.getInteger('hours');
|
|
||||||
try {
|
|
||||||
await StaffNotification.findOneAndUpdate(
|
|
||||||
{ userId: interaction.user.id },
|
|
||||||
{ $set: { cooldownHours: hours, updatedAt: new Date() } },
|
|
||||||
{ upsert: true }
|
|
||||||
);
|
|
||||||
return interaction.reply({ content: `Notification cooldown set to ${hours} hour(s).`, ephemeral: true });
|
|
||||||
} catch (err) {
|
|
||||||
console.error('notification set error:', err);
|
|
||||||
return interaction.reply({ content: 'Failed to update notification setting.', ephemeral: true }).catch(() => {});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (sub === 'add') {
|
|
||||||
if (!CONFIG.STAFF_NOTIFICATION_CATEGORY_ID) {
|
|
||||||
return interaction.reply({ content: 'STAFF_NOTIFICATION_CATEGORY_ID is not configured.', ephemeral: true });
|
|
||||||
}
|
|
||||||
const member = interaction.options.getMember('member');
|
|
||||||
if (!member) {
|
|
||||||
return interaction.reply({ content: 'Could not resolve that member.', ephemeral: true });
|
|
||||||
}
|
|
||||||
const displayName = member.displayName;
|
|
||||||
const emoji = CONFIG.STAFF_EMOJIS.get(member.id) || '';
|
|
||||||
const chanName = toDiscordSafeName(`${displayName}${emoji}`);
|
|
||||||
try {
|
|
||||||
const newChannel = await interaction.guild.channels.create({
|
|
||||||
name: chanName,
|
|
||||||
type: ChannelType.GuildText,
|
|
||||||
parent: CONFIG.STAFF_NOTIFICATION_CATEGORY_ID,
|
|
||||||
permissionOverwrites: [
|
|
||||||
{ id: interaction.guild.id, deny: [PermissionFlagsBits.ViewChannel] },
|
|
||||||
{ id: member.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory] },
|
|
||||||
...(CONFIG.ROLE_ID_TO_PING ? [{ id: CONFIG.ROLE_ID_TO_PING, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory] }] : [])
|
|
||||||
]
|
|
||||||
});
|
|
||||||
await StaffNotification.findOneAndUpdate(
|
|
||||||
{ userId: member.id },
|
|
||||||
{ $set: { channelId: newChannel.id, guildId: interaction.guild.id, updatedAt: new Date() } },
|
|
||||||
{ upsert: true }
|
|
||||||
);
|
|
||||||
return interaction.reply({ content: `Notification channel created: ${newChannel}`, ephemeral: true });
|
|
||||||
} catch (err) {
|
|
||||||
console.error('notification add error:', err);
|
|
||||||
return interaction.reply({ content: 'Failed to create notification channel.', ephemeral: true }).catch(() => {});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// /staffnotification (admin only)
|
|
||||||
if (interaction.commandName === 'staffnotification') {
|
|
||||||
if (interaction.user.id !== CONFIG.ADMIN_ID) {
|
|
||||||
logSecurity('Unauthorized command attempt', interaction.user, interaction.commandName).catch(() => {});
|
|
||||||
return interaction.reply({ content: 'This command is restricted to the bot admin.', ephemeral: true });
|
|
||||||
}
|
|
||||||
const member = interaction.options.getMember('member');
|
|
||||||
const hours = interaction.options.getInteger('hours');
|
|
||||||
if (!member) {
|
|
||||||
return interaction.reply({ content: 'Could not resolve that member.', ephemeral: true });
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await StaffNotification.findOneAndUpdate(
|
|
||||||
{ userId: member.id },
|
|
||||||
{ $set: { cooldownHours: hours, updatedAt: new Date() } },
|
|
||||||
{ upsert: true }
|
|
||||||
);
|
|
||||||
return interaction.reply({ content: `Notification cooldown for ${member.displayName} set to ${hours} hour(s).`, ephemeral: true });
|
|
||||||
} catch (err) {
|
|
||||||
console.error('staffnotification error:', err);
|
|
||||||
return interaction.reply({ content: 'Failed to update notification setting.', ephemeral: true }).catch(() => {});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (interaction.commandName === 'notifydm') {
|
if (interaction.commandName === 'notifydm') {
|
||||||
try {
|
try {
|
||||||
const setting = interaction.options.getString('setting') === 'on';
|
const setting = interaction.options.getString('setting') === 'on';
|
||||||
@@ -723,32 +631,6 @@ async function handleCommand(interaction) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// /tag – ticket category dropdown only
|
|
||||||
if (interaction.commandName === 'tag') {
|
|
||||||
trackInteraction('commands', 'tag', interaction.user.tag);
|
|
||||||
const categoryValue = interaction.options.getString('category');
|
|
||||||
const ticket = await Ticket.findOne({ discordThreadId: interaction.channel.id }).lean();
|
|
||||||
if (!ticket) {
|
|
||||||
return interaction.reply({ content: 'This channel is not linked to a ticket.', ephemeral: true });
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await Ticket.updateOne(
|
|
||||||
{ gmailThreadId: ticket.gmailThreadId },
|
|
||||||
{ $set: { ticketTag: categoryValue } }
|
|
||||||
);
|
|
||||||
const tagEntry = (TICKET_TAGS || []).find(t => t.value === categoryValue);
|
|
||||||
const emoji = tagEntry ? tagEntry.emoji : '';
|
|
||||||
const channelMessage = `Your ticket has been categorized as ${emoji} **${tagEntry ? tagEntry.name : categoryValue}** ${emoji}.`;
|
|
||||||
await interaction.reply(channelMessage);
|
|
||||||
increment('tag_usage', categoryValue, 'today');
|
|
||||||
increment('tag_usage', categoryValue, 'week');
|
|
||||||
if (ticket.game) increment(`tag_game:${categoryValue}`, ticket.game, 'week');
|
|
||||||
} catch (err) {
|
|
||||||
trackError('tag-command', err, interaction);
|
|
||||||
await interaction.reply({ content: 'Failed to set ticket category.', ephemeral: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// /response – saved response tags (send, create, edit, delete, list)
|
// /response – saved response tags (send, create, edit, delete, list)
|
||||||
if (interaction.commandName === 'response') {
|
if (interaction.commandName === 'response') {
|
||||||
trackInteraction('commands', 'response', interaction.user.tag);
|
trackInteraction('commands', 'response', interaction.user.tag);
|
||||||
@@ -936,14 +818,14 @@ async function handleCommand(interaction) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'Ticket Management',
|
name: 'Ticket Management',
|
||||||
value: '`/transfer @staff` - Transfer ticket to another staff member\n`/move #category` - Move ticket to another category\n`/force-close` - Force close ticket without confirmation\n`/topic <text>` - Set ticket topic/description\n`/priority <level>` - Set ticket priority\n`/accountinfo email` - Look up website account by email\n`/accountinfo discord @user` - Look up website account by Discord user'
|
value: '`/transfer @staff` - Transfer ticket to another staff member\n`/move #category` - Move ticket to another category\n`/force-close` - Force close ticket without confirmation\n`/topic <text>` - Set ticket topic/description\n`/accountinfo email` - Look up website account by email\n`/accountinfo discord @user` - Look up website account by Discord user'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'Tags & Responses',
|
name: 'Saved Responses',
|
||||||
value: '`/tag` - Set ticket category (dropdown)\n`/response send <name>` - Send saved response\n`/response create|edit|delete|list` - Manage saved responses'
|
value: '`/response send <name>` - Send saved response\n`/response create|edit|delete|list` - Manage saved responses'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'Variables (for tags)',
|
name: 'Variables (for responses)',
|
||||||
value: '`{ticket.user}`, `{ticket.email}`, `{ticket.number}`, `{ticket.subject}`, `{staff.name}`, `{server.name}`, `{date}`, `{time}`'
|
value: '`{ticket.user}`, `{ticket.email}`, `{ticket.number}`, `{ticket.subject}`, `{staff.name}`, `{server.name}`, `{date}`, `{time}`'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -960,63 +842,6 @@ async function handleCommand(interaction) {
|
|||||||
await interaction.reply({ embeds: [embed], ephemeral: true });
|
await interaction.reply({ embeds: [embed], ephemeral: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
// /priority
|
|
||||||
if (interaction.commandName === 'priority') {
|
|
||||||
const level = interaction.options.getString('level');
|
|
||||||
|
|
||||||
const ticket = await Ticket.findOne({ discordThreadId: interaction.channel.id }).lean();
|
|
||||||
if (!ticket) {
|
|
||||||
return interaction.reply({ content: 'This channel is not linked to a ticket.', ephemeral: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
const priorityOrder = ['low', 'normal', 'medium', 'high'];
|
|
||||||
const oldIdx = priorityOrder.indexOf((ticket.priority || 'normal').toLowerCase());
|
|
||||||
const newIdx = priorityOrder.indexOf(level.toLowerCase());
|
|
||||||
const emoji = getPriorityEmoji(level);
|
|
||||||
const levelLabel = level.charAt(0).toUpperCase() + level.slice(1).toLowerCase();
|
|
||||||
|
|
||||||
let channelMessage;
|
|
||||||
if (level === 'normal') {
|
|
||||||
channelMessage = 'Your ticket priority has returned to Normal.';
|
|
||||||
} else if (newIdx > oldIdx) {
|
|
||||||
channelMessage = `Your ticket has been upgraded to ${emoji} **${levelLabel}** ${emoji}.`;
|
|
||||||
} else if (newIdx < oldIdx) {
|
|
||||||
channelMessage = `Your ticket has been downgraded to ${emoji} **${levelLabel}** ${emoji}.`;
|
|
||||||
} else {
|
|
||||||
channelMessage = `Priority set to ${emoji} **${levelLabel}** ${emoji}.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await Ticket.updateOne(
|
|
||||||
{ gmailThreadId: ticket.gmailThreadId },
|
|
||||||
{ $set: { priority: level } }
|
|
||||||
);
|
|
||||||
|
|
||||||
const priorityTitle =
|
|
||||||
newIdx === oldIdx
|
|
||||||
? 'Priority Set'
|
|
||||||
: `Priority ${newIdx > oldIdx ? 'Upgraded' : 'Downgraded'} → ${levelLabel}`;
|
|
||||||
const priorityEmbed = new EmbedBuilder()
|
|
||||||
.setTitle(priorityTitle)
|
|
||||||
.setDescription(channelMessage)
|
|
||||||
.setColor(getPriorityColor(level))
|
|
||||||
.setFooter({ text: interaction.member?.displayName || interaction.user.username });
|
|
||||||
await interaction.reply({ embeds: [priorityEmbed] });
|
|
||||||
|
|
||||||
if (level === 'high' && ticket.gmailThreadId && !ticket.gmailThreadId.startsWith('discord-')) {
|
|
||||||
await sendTicketNotificationEmail(
|
|
||||||
ticket,
|
|
||||||
`Priority updated: ${levelLabel}`,
|
|
||||||
channelMessage,
|
|
||||||
interaction.member?.displayName || interaction.user.username
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Priority update error:', err);
|
|
||||||
await interaction.reply({ content: 'Failed to update priority.', ephemeral: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// /panel
|
// /panel
|
||||||
if (interaction.commandName === 'panel') {
|
if (interaction.commandName === 'panel') {
|
||||||
const channel = interaction.options.getChannel('channel');
|
const channel = interaction.options.getChannel('channel');
|
||||||
|
|||||||
@@ -7,8 +7,6 @@ const { extractRawEmail } = require('../utils');
|
|||||||
const { getGmailClient, sendGmailReply } = require('../services/gmail');
|
const { getGmailClient, sendGmailReply } = require('../services/gmail');
|
||||||
const { updateTicketActivity } = require('../services/tickets');
|
const { updateTicketActivity } = require('../services/tickets');
|
||||||
const { getNotifyDm } = require('../services/staffSettings');
|
const { getNotifyDm } = require('../services/staffSettings');
|
||||||
const { pingStaffChannel } = require('../services/staffChannel');
|
|
||||||
const { notifyStaffOfReply } = require('../services/staffNotifications');
|
|
||||||
|
|
||||||
const Ticket = mongoose.model('Ticket');
|
const Ticket = mongoose.model('Ticket');
|
||||||
|
|
||||||
@@ -21,12 +19,16 @@ async function handleDiscordReply(m) {
|
|||||||
const ticket = await Ticket.findOne({ discordThreadId: m.channel.id }).lean();
|
const ticket = await Ticket.findOne({ discordThreadId: m.channel.id }).lean();
|
||||||
if (!ticket) return;
|
if (!ticket) return;
|
||||||
|
|
||||||
if (ticket.claimerId && m.author.id !== ticket.claimerId && ticket.staffChannelId) {
|
// Track whether last message is from staff or customer
|
||||||
try {
|
const memberForCheck = await m.guild.members.fetch(m.author.id).catch(() => null);
|
||||||
const staffChan = await m.guild.channels.fetch(ticket.staffChannelId).catch(() => null);
|
const isStaffMember = memberForCheck && CONFIG.ROLE_ID_TO_PING && memberForCheck.roles.cache.has(CONFIG.ROLE_ID_TO_PING);
|
||||||
if (staffChan) {
|
Ticket.updateOne(
|
||||||
await pingStaffChannel(staffChan, ticket.claimerId, m);
|
{ discordThreadId: m.channel.id },
|
||||||
}
|
{ $set: { lastMessageAuthorIsStaff: !!isStaffMember, lastActivity: new Date() } }
|
||||||
|
).catch(() => {});
|
||||||
|
|
||||||
|
// DM the claimer if they have notifydm on and a non-staff user replied.
|
||||||
|
if (ticket.claimerId && !isStaffMember && m.author.id !== ticket.claimerId) {
|
||||||
const dmEnabled = await getNotifyDm(ticket.claimerId);
|
const dmEnabled = await getNotifyDm(ticket.claimerId);
|
||||||
if (dmEnabled) {
|
if (dmEnabled) {
|
||||||
const staffMember = await m.guild.members.fetch(ticket.claimerId).catch(() => null);
|
const staffMember = await m.guild.members.fetch(ticket.claimerId).catch(() => null);
|
||||||
@@ -39,26 +41,6 @@ async function handleDiscordReply(m) {
|
|||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
|
||||||
console.error('Staff ping error:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Track whether last message is from staff or customer
|
|
||||||
const memberForCheck = await m.guild.members.fetch(m.author.id).catch(() => null);
|
|
||||||
const isStaffMember = memberForCheck && CONFIG.ROLE_ID_TO_PING && memberForCheck.roles.cache.has(CONFIG.ROLE_ID_TO_PING);
|
|
||||||
Ticket.updateOne(
|
|
||||||
{ discordThreadId: m.channel.id },
|
|
||||||
{ $set: { lastMessageAuthorIsStaff: !!isStaffMember, lastActivity: new Date() } }
|
|
||||||
).catch(() => {});
|
|
||||||
|
|
||||||
// Notify claiming staff if a non-staff user replied (works for both Discord and email tickets)
|
|
||||||
if (ticket.claimerId && !isStaffMember) {
|
|
||||||
const guild = m.guild;
|
|
||||||
const freshTicket = await Ticket.findOne({ discordThreadId: m.channel.id }).lean();
|
|
||||||
if (freshTicket) {
|
|
||||||
await notifyStaffOfReply(guild, freshTicket, m).catch(e => console.error('notifyStaffOfReply:', e));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const discordUser = m.member?.displayName || m.author.username;
|
const discordUser = m.member?.displayName || m.author.username;
|
||||||
|
|||||||
@@ -864,14 +864,6 @@ mongoose.model('StaffSettings', new mongoose.Schema({
|
|||||||
updatedAt: { type: Date, default: Date.now }
|
updatedAt: { type: Date, default: Date.now }
|
||||||
}));
|
}));
|
||||||
|
|
||||||
mongoose.model('StaffNotification', new mongoose.Schema({
|
|
||||||
userId: { type: String, required: true, unique: true },
|
|
||||||
guildId: String,
|
|
||||||
channelId: String,
|
|
||||||
cooldownHours: { type: Number, default: 1 },
|
|
||||||
updatedAt: { type: Date, default: Date.now }
|
|
||||||
}));
|
|
||||||
|
|
||||||
mongoose.model('StaffSignature', new mongoose.Schema({
|
mongoose.model('StaffSignature', new mongoose.Schema({
|
||||||
userId: { type: String, required: true, unique: true },
|
userId: { type: String, required: true, unique: true },
|
||||||
guildId: { type: String, required: true },
|
guildId: { type: String, required: true },
|
||||||
|
|||||||
@@ -5,14 +5,7 @@ const { CONFIG } = require('../config');
|
|||||||
const { safeEqual } = require('../utils');
|
const { safeEqual } = require('../utils');
|
||||||
const { applyConfigUpdates, readAllConfig } = require('../services/configPersistence');
|
const { applyConfigUpdates, readAllConfig } = require('../services/configPersistence');
|
||||||
const { logSystem } = require('../services/debugLog');
|
const { logSystem } = require('../services/debugLog');
|
||||||
const { REGISTRY: NOTIFICATION_REGISTRY } = require('../services/notificationRegistry');
|
|
||||||
const { ALLOWED_CONFIG_KEYS } = require('../services/configSchema');
|
const { ALLOWED_CONFIG_KEYS } = require('../services/configSchema');
|
||||||
const {
|
|
||||||
getAllState: getNotificationState,
|
|
||||||
setKeyEnabled,
|
|
||||||
setCategoryEnabled,
|
|
||||||
setMasterEnabled
|
|
||||||
} = require('../services/notificationEnabled');
|
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -169,67 +162,6 @@ router.get('/restart/status', (req, res) => {
|
|||||||
res.json({ scheduledRestart: !!scheduledRestart });
|
res.json({ scheduledRestart: !!scheduledRestart });
|
||||||
});
|
});
|
||||||
|
|
||||||
// GET /notifications/alerts — canonical bot-side notification alert catalog
|
|
||||||
router.get('/notifications/alerts', (req, res) => {
|
|
||||||
res.json(NOTIFICATION_REGISTRY);
|
|
||||||
});
|
|
||||||
|
|
||||||
// GET /notifications/state — Phase 9: master flag + per-key enable map
|
|
||||||
router.get('/notifications/state', (req, res) => {
|
|
||||||
res.json(getNotificationState());
|
|
||||||
});
|
|
||||||
|
|
||||||
// POST /notifications/toggle — Phase 9: mutate one of {master, category, key}
|
|
||||||
//
|
|
||||||
// Body shapes (exactly one of these must be used):
|
|
||||||
// { master: true, enabled: <bool> }
|
|
||||||
// { category: <str>, enabled: <bool> }
|
|
||||||
// { key: <str>, enabled: <bool> }
|
|
||||||
//
|
|
||||||
// Mutates CONFIG in memory via notificationEnabled, then persists through
|
|
||||||
// applyConfigUpdates so the value passes schema validation and ends up in .env.
|
|
||||||
router.post('/notifications/toggle', express.json(), async (req, res) => {
|
|
||||||
const body = req.body;
|
|
||||||
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
||||||
return res.status(400).json({ error: 'Invalid body' });
|
|
||||||
}
|
|
||||||
if (typeof body.enabled !== 'boolean') {
|
|
||||||
return res.status(400).json({ error: '`enabled` must be boolean' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const hasMaster = Object.prototype.hasOwnProperty.call(body, 'master');
|
|
||||||
const hasCategory = Object.prototype.hasOwnProperty.call(body, 'category');
|
|
||||||
const hasKey = Object.prototype.hasOwnProperty.call(body, 'key');
|
|
||||||
const specifiedCount = Number(hasMaster) + Number(hasCategory) + Number(hasKey);
|
|
||||||
if (specifiedCount !== 1) {
|
|
||||||
return res.status(400).json({ error: 'Specify exactly one of: master, category, key' });
|
|
||||||
}
|
|
||||||
|
|
||||||
let updates;
|
|
||||||
if (hasMaster) {
|
|
||||||
setMasterEnabled(body.enabled);
|
|
||||||
updates = { NOTIFICATIONS_MASTER_ENABLED: body.enabled };
|
|
||||||
} else if (hasCategory) {
|
|
||||||
if (typeof body.category !== 'string' || !Object.prototype.hasOwnProperty.call(NOTIFICATION_REGISTRY, body.category)) {
|
|
||||||
return res.status(400).json({ error: 'Unknown category' });
|
|
||||||
}
|
|
||||||
const newJson = setCategoryEnabled(body.category, body.enabled);
|
|
||||||
updates = { NOTIFICATION_ENABLED_JSON: newJson };
|
|
||||||
} else {
|
|
||||||
if (typeof body.key !== 'string' || !body.key) {
|
|
||||||
return res.status(400).json({ error: '`key` must be a non-empty string' });
|
|
||||||
}
|
|
||||||
const newJson = setKeyEnabled(body.key, body.enabled);
|
|
||||||
updates = { NOTIFICATION_ENABLED_JSON: newJson };
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = applyConfigUpdates(updates);
|
|
||||||
if (result.errors.length > 0) {
|
|
||||||
return res.status(500).json({ error: 'Persistence failed', details: result.errors });
|
|
||||||
}
|
|
||||||
res.json({ state: getNotificationState() });
|
|
||||||
});
|
|
||||||
|
|
||||||
// POST /gmail/reload — hot-swap Gmail OAuth creds after weekly reauth without
|
// POST /gmail/reload — hot-swap Gmail OAuth creds after weekly reauth without
|
||||||
// restarting the process. Reads REFRESH_TOKEN from .env via configPersistence,
|
// restarting the process. Reads REFRESH_TOKEN from .env via configPersistence,
|
||||||
// probes Google with users.getProfile, and on success clears pollSuspended and
|
// probes Google with users.getProfile, and on success clears pollSuspended and
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
/**
|
|
||||||
* Chat monitoring — tracks unresponded messages in configured channels
|
|
||||||
* and alerts staff when thresholds are crossed.
|
|
||||||
*/
|
|
||||||
const { EmbedBuilder } = require('discord.js');
|
|
||||||
const { CONFIG, parseThresholdString } = require('../config');
|
|
||||||
const { shouldFireCooldownEscalating, clearEscalating } = require('./patternStore');
|
|
||||||
const { enqueueSend } = require('./channelQueue');
|
|
||||||
const { assertKeysRegistered } = require('./notificationRegistry');
|
|
||||||
const { isEnabled } = require('./notificationEnabled');
|
|
||||||
|
|
||||||
const CHAT_ALERT_KEYS = ['chat_messages', 'chat_time'];
|
|
||||||
assertKeysRegistered('chatAlertChecker', CHAT_ALERT_KEYS);
|
|
||||||
|
|
||||||
// channelId → { lastStaffMessageAt, unrespondedCount, lastAlertAt }
|
|
||||||
const chatState = new Map();
|
|
||||||
const chatMessageThresholdsMs = (CONFIG.NOTIFICATION_THRESHOLDS?.chat_messages || [])
|
|
||||||
.map(parseThresholdString)
|
|
||||||
.filter(n => Number.isFinite(n) && n > 0);
|
|
||||||
const chatTimeThresholdsMs = (CONFIG.NOTIFICATION_THRESHOLDS?.chat_time || [])
|
|
||||||
.map(parseThresholdString)
|
|
||||||
.filter(n => Number.isFinite(n) && n > 0);
|
|
||||||
|
|
||||||
function initChatMonitoring(client) {
|
|
||||||
for (const channelId of CONFIG.CHAT_ALERT_CHANNEL_IDS) {
|
|
||||||
chatState.set(channelId, {
|
|
||||||
lastStaffMessageAt: new Date(),
|
|
||||||
unrespondedCount: 0,
|
|
||||||
lastAlertAt: null
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function isStaff(member) {
|
|
||||||
if (!member?.roles?.cache) return false;
|
|
||||||
if (CONFIG.ROLE_ID_TO_PING && member.roles.cache.has(CONFIG.ROLE_ID_TO_PING)) return true;
|
|
||||||
const additional = CONFIG.ADDITIONAL_STAFF_ROLES || [];
|
|
||||||
return additional.some(roleId => member.roles.cache.has(roleId));
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleChatMessage(msg, client) {
|
|
||||||
if (msg.author.bot) return;
|
|
||||||
if (!chatState.has(msg.channel.id)) return;
|
|
||||||
|
|
||||||
const state = chatState.get(msg.channel.id);
|
|
||||||
if (isStaff(msg.member)) {
|
|
||||||
state.lastStaffMessageAt = new Date();
|
|
||||||
state.unrespondedCount = 0;
|
|
||||||
clearEscalating(`chat:messages:${msg.channel.id}`);
|
|
||||||
clearEscalating(`chat:time:${msg.channel.id}`);
|
|
||||||
} else {
|
|
||||||
state.unrespondedCount++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function runChatAlertChecks(client) {
|
|
||||||
const alertChannelId = CONFIG.ALL_STAFF_CHAT_ALERT_CHANNEL_ID;
|
|
||||||
if (!alertChannelId || !client) return;
|
|
||||||
|
|
||||||
for (const [channelId, state] of chatState) {
|
|
||||||
// Message count threshold
|
|
||||||
if (isEnabled('chat_messages') && state.unrespondedCount >= CONFIG.CHAT_ALERT_MESSAGE_COUNT) {
|
|
||||||
const cooldownKey = `chat:messages:${channelId}`;
|
|
||||||
if (shouldFireCooldownEscalating(cooldownKey, chatMessageThresholdsMs) !== null) {
|
|
||||||
const embed = new EmbedBuilder()
|
|
||||||
.setTitle('Chat needs attention')
|
|
||||||
.setDescription(`<#${channelId}> has ${state.unrespondedCount} unresponded messages.`)
|
|
||||||
.setColor(0xFF8800)
|
|
||||||
.setTimestamp();
|
|
||||||
try {
|
|
||||||
const alertChan = await client.channels.fetch(alertChannelId);
|
|
||||||
const content = CONFIG.SURGE_ROLE_ID ? `<@&${CONFIG.SURGE_ROLE_ID}>` : undefined;
|
|
||||||
if (alertChan) await enqueueSend(alertChan, { content, embeds: [embed] });
|
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Time threshold
|
|
||||||
const hoursSinceStaff = (Date.now() - state.lastStaffMessageAt.getTime()) / 3600000;
|
|
||||||
if (isEnabled('chat_time') && hoursSinceStaff >= CONFIG.CHAT_ALERT_HOURS_WITHOUT_RESPONSE && state.unrespondedCount > 0) {
|
|
||||||
const cooldownKey = `chat:time:${channelId}`;
|
|
||||||
if (shouldFireCooldownEscalating(cooldownKey, chatTimeThresholdsMs) !== null) {
|
|
||||||
const embed = new EmbedBuilder()
|
|
||||||
.setTitle('Chat without staff response')
|
|
||||||
.setDescription(`<#${channelId}> has had no staff response for ${Math.floor(hoursSinceStaff)} hour(s) with ${state.unrespondedCount} pending message(s).`)
|
|
||||||
.setColor(0xFF8800)
|
|
||||||
.setTimestamp();
|
|
||||||
try {
|
|
||||||
const alertChan = await client.channels.fetch(alertChannelId);
|
|
||||||
const content = CONFIG.SURGE_ROLE_ID ? `<@&${CONFIG.SURGE_ROLE_ID}>` : undefined;
|
|
||||||
if (alertChan) await enqueueSend(alertChan, { content, embeds: [embed] });
|
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { initChatMonitoring, handleChatMessage, runChatAlertChecks };
|
|
||||||
@@ -27,17 +27,12 @@ const ALLOWED_CONFIG_KEYS = new Set([
|
|||||||
'EMAIL_ESCALATED3_CHANNEL_ID', 'DISCORD_ESCALATED3_CHANNEL_ID',
|
'EMAIL_ESCALATED3_CHANNEL_ID', 'DISCORD_ESCALATED3_CHANNEL_ID',
|
||||||
// Roles and staff
|
// Roles and staff
|
||||||
'ROLE_ID_TO_PING', 'ROLE_TO_PING_ID', 'ADDITIONAL_STAFF_ROLES', 'BLACKLISTED_ROLES',
|
'ROLE_ID_TO_PING', 'ROLE_TO_PING_ID', 'ADDITIONAL_STAFF_ROLES', 'BLACKLISTED_ROLES',
|
||||||
'STAFF_IDS', 'ADMIN_ID', 'STAFF_EMOJIS', 'CLAIMER_EMOJI_FALLBACK',
|
'ADMIN_ID',
|
||||||
// Channel IDs
|
// Channel IDs
|
||||||
'TRANSCRIPT_CHANNEL_ID', 'LOGGING_CHANNEL_ID', 'DEBUGGING_CHANNEL_ID',
|
'TRANSCRIPT_CHANNEL_ID', 'LOGGING_CHANNEL_ID', 'DEBUGGING_CHANNEL_ID',
|
||||||
'BACKUP_EXPORT_CHANNEL_ID', 'ACCOUNT_INFO_CHANNEL_ID', 'DISCORD_CHANNEL_ID',
|
'BACKUP_EXPORT_CHANNEL_ID', 'ACCOUNT_INFO_CHANNEL_ID', 'DISCORD_CHANNEL_ID',
|
||||||
'GMAIL_LOG_CHANNEL_ID', 'AUTOMATION_LOG_CHANNEL_ID', 'RENAME_LOG_CHANNEL_ID',
|
'GMAIL_LOG_CHANNEL_ID', 'AUTOMATION_LOG_CHANNEL_ID', 'RENAME_LOG_CHANNEL_ID',
|
||||||
'SECURITY_LOG_CHANNEL_ID', 'SYSTEM_LOG_CHANNEL_ID',
|
'SECURITY_LOG_CHANNEL_ID', 'SYSTEM_LOG_CHANNEL_ID',
|
||||||
'ALL_STAFF_CHANNEL_ID', 'ALL_STAFF_CHAT_ALERT_CHANNEL_ID',
|
|
||||||
'STAFF_NOTIFICATION_CATEGORY_ID',
|
|
||||||
// Pattern channel IDs
|
|
||||||
'USER_PATTERNS_CHANNEL_ID', 'GAME_PATTERNS_CHANNEL_ID', 'TAG_PATTERNS_CHANNEL_ID',
|
|
||||||
'ESCALATION_PATTERNS_CHANNEL_ID', 'STAFF_PATTERNS_CHANNEL_ID', 'COMBINED_PATTERNS_CHANNEL_ID',
|
|
||||||
// Messages and labels
|
// Messages and labels
|
||||||
'ESCALATION_MESSAGE', 'TICKET_CLOSE_SUBJECT_PREFIX', 'TICKET_CLOSE_MESSAGE', 'TICKET_CLOSE_SIGNATURE',
|
'ESCALATION_MESSAGE', 'TICKET_CLOSE_SUBJECT_PREFIX', 'TICKET_CLOSE_MESSAGE', 'TICKET_CLOSE_SIGNATURE',
|
||||||
'DISCORD_CLOSE_MESSAGE', 'DISCORD_TRANSCRIPT_MESSAGE', 'DISCORD_AUTO_CLOSE_MESSAGE',
|
'DISCORD_CLOSE_MESSAGE', 'DISCORD_TRANSCRIPT_MESSAGE', 'DISCORD_AUTO_CLOSE_MESSAGE',
|
||||||
@@ -48,36 +43,17 @@ const ALLOWED_CONFIG_KEYS = new Set([
|
|||||||
'LOGO_URL', 'SUPPORT_NAME', 'EMAIL_SIGNATURE', 'GAME_LIST',
|
'LOGO_URL', 'SUPPORT_NAME', 'EMAIL_SIGNATURE', 'GAME_LIST',
|
||||||
// Toggles
|
// Toggles
|
||||||
'AUTO_CLOSE_ENABLED', 'AUTO_CLOSE_AFTER_HOURS', 'AUTO_UNCLAIM_ENABLED', 'AUTO_UNCLAIM_AFTER_HOURS',
|
'AUTO_CLOSE_ENABLED', 'AUTO_CLOSE_AFTER_HOURS', 'AUTO_UNCLAIM_ENABLED', 'AUTO_UNCLAIM_AFTER_HOURS',
|
||||||
'CLAIM_TIMEOUT_ENABLED', 'CLAIM_TIMEOUT_HOURS', 'ALLOW_CLAIM_OVERWRITE',
|
'ALLOW_CLAIM_OVERWRITE',
|
||||||
'REMINDER_ENABLED', 'REMINDER_AFTER_HOURS', 'PRIORITY_ENABLED', 'DEFAULT_PRIORITY',
|
'REMINDER_ENABLED', 'REMINDER_AFTER_HOURS', 'PRIORITY_ENABLED', 'DEFAULT_PRIORITY',
|
||||||
'STAFF_THREAD_ENABLED', 'STAFF_THREAD_NAME', 'STAFF_THREAD_AUTO_ADD_ROLE', 'STAFF_THREAD_ROLE_ID',
|
'STAFF_THREAD_ENABLED', 'STAFF_THREAD_NAME', 'STAFF_THREAD_AUTO_ADD_ROLE', 'STAFF_THREAD_ROLE_ID',
|
||||||
'PIN_INITIAL_MESSAGE_ENABLED', 'PIN_ESCALATION_MESSAGE_ENABLED', 'PIN_SUPPRESS_SYSTEM_MESSAGE',
|
'PIN_INITIAL_MESSAGE_ENABLED', 'PIN_ESCALATION_MESSAGE_ENABLED', 'PIN_SUPPRESS_SYSTEM_MESSAGE',
|
||||||
'STAFF_DND_COUNTS_AS_AVAILABLE',
|
|
||||||
// Limits and thresholds
|
// Limits and thresholds
|
||||||
'GLOBAL_TICKET_LIMIT', 'TICKET_LIMIT_PER_CATEGORY',
|
'GLOBAL_TICKET_LIMIT', 'TICKET_LIMIT_PER_CATEGORY',
|
||||||
'RATE_LIMIT_TICKETS_PER_USER', 'RATE_LIMIT_WINDOW_MINUTES',
|
'RATE_LIMIT_TICKETS_PER_USER', 'RATE_LIMIT_WINDOW_MINUTES',
|
||||||
'FORCE_CLOSE_TIMER_SECONDS', 'GMAIL_POLL_INTERVAL_SECONDS',
|
'FORCE_CLOSE_TIMER_SECONDS', 'GMAIL_POLL_INTERVAL_SECONDS',
|
||||||
// Embed colors
|
// Embed colors
|
||||||
'EMBED_COLOR_OPEN', 'EMBED_COLOR_CLOSED', 'EMBED_COLOR_CLAIMED', 'EMBED_COLOR_ESCALATED', 'EMBED_COLOR_INFO',
|
'EMBED_COLOR_OPEN', 'EMBED_COLOR_CLOSED', 'EMBED_COLOR_CLAIMED', 'EMBED_COLOR_ESCALATED', 'EMBED_COLOR_INFO',
|
||||||
'PRIORITY_HIGH_EMOJI', 'PRIORITY_MEDIUM_EMOJI', 'PRIORITY_LOW_EMOJI',
|
'PRIORITY_HIGH_EMOJI', 'PRIORITY_MEDIUM_EMOJI', 'PRIORITY_LOW_EMOJI'
|
||||||
// Pattern thresholds
|
|
||||||
'PATTERN_USER_TICKET_THRESHOLD', 'PATTERN_GAME_TICKET_THRESHOLD',
|
|
||||||
'PATTERN_STAFF_STALE_PING_THRESHOLD', 'PATTERN_ESCALATION_THRESHOLD',
|
|
||||||
'PATTERN_RAPID_CLOSE_SECONDS', 'PATTERN_UNCLAIMED_HOURS', 'PATTERN_CHECK_INTERVAL_MINUTES',
|
|
||||||
// Surge settings
|
|
||||||
'SURGE_ROLE_ID', 'SURGE_TICKET_COUNT', 'SURGE_TICKET_WINDOW_MINUTES',
|
|
||||||
'SURGE_GAME_TICKET_COUNT', 'SURGE_GAME_TICKET_WINDOW_MINUTES',
|
|
||||||
'SURGE_STALE_COUNT', 'SURGE_STALE_HOURS',
|
|
||||||
'SURGE_NEEDS_RESPONSE_COUNT', 'SURGE_NEEDS_RESPONSE_HOURS',
|
|
||||||
'SURGE_UNCLAIMED_COUNT', 'SURGE_UNCLAIMED_MINUTES', 'SURGE_TIER3_UNCLAIMED_MINUTES',
|
|
||||||
'SURGE_COOLDOWN_MINUTES', 'SURGE_NO_STAFF_COOLDOWN_MINUTES', 'SURGE_NO_STAFF_OPEN_TICKET_THRESHOLD',
|
|
||||||
// Chat alerts
|
|
||||||
'CHAT_ALERT_CHANNEL_IDS', 'CHAT_ALERT_MESSAGE_COUNT',
|
|
||||||
'CHAT_ALERT_HOURS_WITHOUT_RESPONSE', 'CHAT_ALERT_COOLDOWN_MINUTES',
|
|
||||||
// Notification thresholds
|
|
||||||
'NOTIFICATION_THRESHOLDS_JSON', 'UNCLAIMED_REMINDER_THRESHOLDS',
|
|
||||||
// Notification enable state (Phase 9)
|
|
||||||
'NOTIFICATION_ENABLED_JSON', 'NOTIFICATIONS_MASTER_ENABLED'
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// ---------- Regex primitives ----------
|
// ---------- Regex primitives ----------
|
||||||
@@ -207,13 +183,9 @@ const VALIDATORS = {
|
|||||||
|
|
||||||
function inferType(key) {
|
function inferType(key) {
|
||||||
// 1. Explicit overrides
|
// 1. Explicit overrides
|
||||||
if (key === 'NOTIFICATION_THRESHOLDS_JSON') return 'json';
|
|
||||||
if (key === 'NOTIFICATION_ENABLED_JSON') return 'json';
|
|
||||||
if (key === 'NOTIFICATIONS_MASTER_ENABLED') return 'boolean';
|
|
||||||
if (key === 'LOGO_URL') return 'url';
|
if (key === 'LOGO_URL') return 'url';
|
||||||
if (/_EMAIL$/.test(key)) return 'email';
|
if (/_EMAIL$/.test(key)) return 'email';
|
||||||
if (key.includes('COLOR')) return 'hex_color';
|
if (key.includes('COLOR')) return 'hex_color';
|
||||||
if (/_EMOJIS$/.test(key)) return 'string_or_json';
|
|
||||||
// ROLE_ID_TO_PING has _ID mid-key — standard _ID$ pattern misses it.
|
// ROLE_ID_TO_PING has _ID mid-key — standard _ID$ pattern misses it.
|
||||||
if (key === 'ROLE_ID_TO_PING') return 'discord_id';
|
if (key === 'ROLE_ID_TO_PING') return 'discord_id';
|
||||||
|
|
||||||
|
|||||||
@@ -1,102 +0,0 @@
|
|||||||
/**
|
|
||||||
* Canonical enable/disable state accessor for per-alert notifications.
|
|
||||||
*
|
|
||||||
* State lives in two CONFIG keys:
|
|
||||||
* - NOTIFICATIONS_MASTER_ENABLED (boolean) — global kill switch
|
|
||||||
* - NOTIFICATION_ENABLED_JSON (JSON string → flat { [key]: boolean })
|
|
||||||
*
|
|
||||||
* Defaults: master off, every key off. Unknown keys in the JSON are ignored
|
|
||||||
* on read (registry is the source of truth); keys missing from the JSON are
|
|
||||||
* treated as false. Master off short-circuits every read — isEnabled never
|
|
||||||
* returns true when master is off, so checkers bail without logs or metrics.
|
|
||||||
*
|
|
||||||
* Setters mutate CONFIG in memory and return the new value so the caller can
|
|
||||||
* persist it via configPersistence.applyConfigUpdates. .env writes happen
|
|
||||||
* there so schema validation and partial-success semantics stay consistent.
|
|
||||||
*/
|
|
||||||
'use strict';
|
|
||||||
|
|
||||||
const { CONFIG } = require('../config');
|
|
||||||
const { REGISTRY } = require('./notificationRegistry');
|
|
||||||
|
|
||||||
function parseState() {
|
|
||||||
const raw = CONFIG.NOTIFICATION_ENABLED_JSON;
|
|
||||||
if (raw === undefined || raw === null || raw === '') return {};
|
|
||||||
if (typeof raw === 'object' && !Array.isArray(raw)) return raw;
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(String(raw));
|
|
||||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
|
|
||||||
} catch (_) {}
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
function isMasterOn() {
|
|
||||||
const v = CONFIG.NOTIFICATIONS_MASTER_ENABLED;
|
|
||||||
return v === true || v === 'true';
|
|
||||||
}
|
|
||||||
|
|
||||||
function isEnabled(alertKey) {
|
|
||||||
if (!isMasterOn()) return false;
|
|
||||||
const state = parseState();
|
|
||||||
return state[alertKey] === true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isCategoryEnabled(category) {
|
|
||||||
if (!isMasterOn()) return false;
|
|
||||||
const entries = REGISTRY[category];
|
|
||||||
if (!Array.isArray(entries) || entries.length === 0) return false;
|
|
||||||
const state = parseState();
|
|
||||||
return entries.every(e => state[e.key] === true);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getAllState() {
|
|
||||||
const state = parseState();
|
|
||||||
const perKey = {};
|
|
||||||
for (const entries of Object.values(REGISTRY)) {
|
|
||||||
if (!Array.isArray(entries)) continue;
|
|
||||||
for (const e of entries) {
|
|
||||||
perKey[e.key] = state[e.key] === true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { master: isMasterOn(), perKey };
|
|
||||||
}
|
|
||||||
|
|
||||||
function serialize(state) {
|
|
||||||
const ordered = {};
|
|
||||||
Object.keys(state).sort().forEach(k => { ordered[k] = state[k] === true; });
|
|
||||||
return JSON.stringify(ordered);
|
|
||||||
}
|
|
||||||
|
|
||||||
function setKeyEnabled(key, enabled) {
|
|
||||||
const state = parseState();
|
|
||||||
state[String(key)] = enabled === true;
|
|
||||||
const json = serialize(state);
|
|
||||||
CONFIG.NOTIFICATION_ENABLED_JSON = json;
|
|
||||||
return json;
|
|
||||||
}
|
|
||||||
|
|
||||||
function setCategoryEnabled(category, enabled) {
|
|
||||||
const state = parseState();
|
|
||||||
const entries = REGISTRY[category];
|
|
||||||
if (Array.isArray(entries)) {
|
|
||||||
for (const e of entries) state[e.key] = enabled === true;
|
|
||||||
}
|
|
||||||
const json = serialize(state);
|
|
||||||
CONFIG.NOTIFICATION_ENABLED_JSON = json;
|
|
||||||
return json;
|
|
||||||
}
|
|
||||||
|
|
||||||
function setMasterEnabled(enabled) {
|
|
||||||
const value = enabled === true;
|
|
||||||
CONFIG.NOTIFICATIONS_MASTER_ENABLED = value;
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
isEnabled,
|
|
||||||
isCategoryEnabled,
|
|
||||||
getAllState,
|
|
||||||
setKeyEnabled,
|
|
||||||
setCategoryEnabled,
|
|
||||||
setMasterEnabled
|
|
||||||
};
|
|
||||||
@@ -1,214 +0,0 @@
|
|||||||
/**
|
|
||||||
* Canonical notification alert registry.
|
|
||||||
*
|
|
||||||
* Single source of truth for the 32 registered alert keys across surgeChecker,
|
|
||||||
* patternChecker, staffNotifications, and chatAlertChecker. Consumed by:
|
|
||||||
* - the checker services (startup drift-check, Phase 9 enable gating)
|
|
||||||
* - routes/internalApi.js GET /notifications/alerts
|
|
||||||
* - settings-site UI (via proxied /api/notifications/alerts, with fallback)
|
|
||||||
*
|
|
||||||
* Not covered here (intentionally fallback-only in the UI):
|
|
||||||
* - rapid_t2_t3 — uses count-milestone firing, not shouldFire()
|
|
||||||
*
|
|
||||||
* `windowType` is the reset window used by shouldFire() for pattern keys
|
|
||||||
* (today/week/month). For surge, unclaimed, and chat, firing is
|
|
||||||
* cooldown-escalating rather than window-based, so windowType is null.
|
|
||||||
*/
|
|
||||||
|
|
||||||
const REGISTRY = Object.freeze({
|
|
||||||
surge: Object.freeze([
|
|
||||||
Object.freeze({
|
|
||||||
key: 'surge_tickets',
|
|
||||||
description: 'Fires when total active ticket volume exceeds configured surge thresholds, signaling broad queue pressure that needs staffing attention.',
|
|
||||||
windowType: null
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'surge_game',
|
|
||||||
description: 'Fires when one game accumulates tickets unusually fast within the configured window, indicating a localized incident that should be triaged.',
|
|
||||||
windowType: null
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'surge_stale',
|
|
||||||
description: 'Fires when too many tickets stay unresolved past the stale-time threshold, prompting staff to clear aging backlog.',
|
|
||||||
windowType: null
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'surge_needs_response',
|
|
||||||
description: 'Fires when tickets needing a staff reply exceed count and age limits, indicating response latency is building.',
|
|
||||||
windowType: null
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'surge_unclaimed',
|
|
||||||
description: 'Fires when the unclaimed queue crosses configured count/age thresholds, signaling ownership gaps that need pickup.',
|
|
||||||
windowType: null
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'surge_tier3_unclaimed',
|
|
||||||
description: "Fires when Tier 3 tickets have been sitting unclaimed past each threshold. Escalating intervals prevent spam while ensuring critical tickets don't go unnoticed.",
|
|
||||||
windowType: null
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'surge_no_staff',
|
|
||||||
description: 'Fires when open-ticket load is high while no staff are detected as available, prompting immediate coverage.',
|
|
||||||
windowType: null
|
|
||||||
})
|
|
||||||
]),
|
|
||||||
|
|
||||||
patterns: Object.freeze([
|
|
||||||
Object.freeze({
|
|
||||||
key: 'user_tickets',
|
|
||||||
description: 'Detects users opening unusually high ticket counts in the active window, suggesting repeat-issue or abuse patterns.',
|
|
||||||
windowType: 'today'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'user_reopen',
|
|
||||||
description: 'Detects users who repeatedly reopen or recreate issues after closure, signaling unresolved root-cause patterns.',
|
|
||||||
windowType: 'week'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'user_crossgame',
|
|
||||||
description: 'Detects users reporting similar issues across multiple games in a short period, indicating broader account-level impact.',
|
|
||||||
windowType: 'week'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'game_surge',
|
|
||||||
description: 'Detects game-specific ticket spikes crossing thresholds in the pattern window, signaling service instability for that title.',
|
|
||||||
windowType: 'today'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'game_backlog',
|
|
||||||
description: 'Detects games accumulating unresolved backlog above threshold, implying triage capacity is lagging for that queue.',
|
|
||||||
windowType: 'today'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'game_resolution',
|
|
||||||
description: 'Detects unusual drops in resolution rate for a game, indicating tickets are staying open longer than expected.',
|
|
||||||
windowType: 'week'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'game_spike',
|
|
||||||
description: 'Detects abrupt short-window jumps in ticket volume for a game, flagging incidents that may need escalation.',
|
|
||||||
windowType: 'today'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'tag_top',
|
|
||||||
description: 'Detects tag frequency leaders above threshold so recurring issue types can be prioritized for fixes or macros.',
|
|
||||||
windowType: 'today'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'tag_escalation',
|
|
||||||
description: 'Detects tags with unusually high escalation rates, indicating categories that routinely require higher-tier handling.',
|
|
||||||
windowType: 'week'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'untagged_closes',
|
|
||||||
description: 'Detects elevated counts of closed tickets without tags, prompting cleanup to preserve reporting quality.',
|
|
||||||
windowType: 'today'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'tag_game_corr',
|
|
||||||
description: 'Detects strong tag-to-game concentration patterns, highlighting issue types tightly linked to specific games.',
|
|
||||||
windowType: 'week'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'user_esc',
|
|
||||||
description: 'Detects users whose tickets escalate unusually often, implying complex cases that may need proactive follow-up.',
|
|
||||||
windowType: 'week'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'game_esc_rate',
|
|
||||||
description: 'Detects games with escalating ticket-rate thresholds exceeded, signaling deeper technical issues for that title.',
|
|
||||||
windowType: 'week'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'staff_no_close',
|
|
||||||
description: 'Detects staff with prolonged periods of claims but few closes, suggesting overloaded ownership or stuck work.',
|
|
||||||
windowType: 'today'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'staff_overloaded',
|
|
||||||
description: 'Detects staff carrying ticket loads beyond threshold, indicating balancing or reassignment may be needed.',
|
|
||||||
windowType: 'today'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'staff_stale',
|
|
||||||
description: 'Detects staff-owned tickets aging beyond stale limits, prompting review and unblock actions.',
|
|
||||||
windowType: 'today'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'staff_transfer_rate',
|
|
||||||
description: 'Detects unusually high transfer/reassignment rates by staff, signaling ownership churn that may hurt throughput.',
|
|
||||||
windowType: 'today'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'staff_esc',
|
|
||||||
description: 'Detects staff escalation counts above threshold, highlighting where extra support or training may be needed.',
|
|
||||||
windowType: 'week'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'staff_game_esc',
|
|
||||||
description: 'Detects high escalation concentration for specific staff/game combinations, indicating targeted expertise gaps.',
|
|
||||||
windowType: 'week'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'game_tag_spike',
|
|
||||||
description: 'Detects sudden spikes of specific tags within a game, flagging focused incident signatures.',
|
|
||||||
windowType: 'today'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'overnight_gap',
|
|
||||||
description: 'Detects recurring unattended overnight windows with active demand, suggesting staffing coverage gaps.',
|
|
||||||
windowType: 'week'
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'staff_always_esc',
|
|
||||||
description: 'Detects staff whose handled tickets escalate at consistently high rates, implying sustained tier-fit issues.',
|
|
||||||
windowType: 'month'
|
|
||||||
})
|
|
||||||
]),
|
|
||||||
|
|
||||||
unclaimed: Object.freeze([
|
|
||||||
Object.freeze({
|
|
||||||
key: 'unclaimed_reminder',
|
|
||||||
description: 'Reminds all staff notification channels about unclaimed tickets. Thresholds are per-ticket age — each threshold fires once per ticket and resets on escalation.',
|
|
||||||
windowType: null
|
|
||||||
})
|
|
||||||
]),
|
|
||||||
|
|
||||||
chat: Object.freeze([
|
|
||||||
Object.freeze({
|
|
||||||
key: 'chat_messages',
|
|
||||||
description: 'Fires when pending user message volume in monitored chat channels crosses configured count thresholds without staff replies.',
|
|
||||||
windowType: null
|
|
||||||
}),
|
|
||||||
Object.freeze({
|
|
||||||
key: 'chat_time',
|
|
||||||
description: 'Fires when a monitored chat channel has had no staff response for the given duration with pending user messages. Resets when staff responds.',
|
|
||||||
windowType: null
|
|
||||||
})
|
|
||||||
])
|
|
||||||
});
|
|
||||||
|
|
||||||
const ALL_KEYS = Object.freeze([
|
|
||||||
...REGISTRY.surge.map(e => e.key),
|
|
||||||
...REGISTRY.patterns.map(e => e.key),
|
|
||||||
...REGISTRY.unclaimed.map(e => e.key),
|
|
||||||
...REGISTRY.chat.map(e => e.key)
|
|
||||||
]);
|
|
||||||
|
|
||||||
const ALL_KEYS_SET = new Set(ALL_KEYS);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Throws if any of `keys` is not in the registry. Call at module load from
|
|
||||||
* each checker that references registry keys so drift fails fast.
|
|
||||||
*/
|
|
||||||
function assertKeysRegistered(moduleName, keys) {
|
|
||||||
const missing = keys.filter(k => !ALL_KEYS_SET.has(k));
|
|
||||||
if (missing.length > 0) {
|
|
||||||
throw new Error(
|
|
||||||
`[notificationRegistry] ${moduleName} references keys not in REGISTRY: ${missing.join(', ')}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { REGISTRY, ALL_KEYS, assertKeysRegistered };
|
|
||||||
@@ -1,587 +0,0 @@
|
|||||||
/**
|
|
||||||
* Pattern detection — scheduled checks that analyze ticket trends and post
|
|
||||||
* alerts to dedicated Discord channels.
|
|
||||||
*/
|
|
||||||
const { EmbedBuilder } = require('discord.js');
|
|
||||||
const { CONFIG, parseThresholdString } = require('../config');
|
|
||||||
const { mongoose } = require('../db-connection');
|
|
||||||
const { getAll, get, shouldFireThreshold, onWeeklyReset } = require('./patternStore');
|
|
||||||
const { enqueueSend } = require('./channelQueue');
|
|
||||||
const { assertKeysRegistered } = require('./notificationRegistry');
|
|
||||||
const { isEnabled } = require('./notificationEnabled');
|
|
||||||
|
|
||||||
// Alert keys this module fires via shouldFire()/standard threshold path.
|
|
||||||
// rapid_t2_t3 is intentionally excluded — it uses count-milestone firing below
|
|
||||||
// via firedCountMilestones, not the shouldFire() pipeline, so it is not part
|
|
||||||
// of the notification registry.
|
|
||||||
const PATTERN_ALERT_KEYS = [
|
|
||||||
'user_tickets', 'user_reopen', 'user_crossgame',
|
|
||||||
'game_surge', 'game_backlog', 'game_resolution', 'game_spike',
|
|
||||||
'tag_top', 'tag_escalation', 'untagged_closes', 'tag_game_corr',
|
|
||||||
'user_esc', 'game_esc_rate',
|
|
||||||
'staff_no_close', 'staff_overloaded', 'staff_stale', 'staff_transfer_rate',
|
|
||||||
'staff_esc', 'staff_game_esc',
|
|
||||||
'game_tag_spike', 'overnight_gap', 'staff_always_esc'
|
|
||||||
];
|
|
||||||
assertKeysRegistered('patternChecker', PATTERN_ALERT_KEYS);
|
|
||||||
|
|
||||||
const Ticket = mongoose.model('Ticket');
|
|
||||||
|
|
||||||
// rapid_t2_t3 count milestone state (cleared weekly)
|
|
||||||
const firedCountMilestones = new Map();
|
|
||||||
onWeeklyReset(() => firedCountMilestones.clear());
|
|
||||||
|
|
||||||
// --- Helpers ---
|
|
||||||
|
|
||||||
function buildEmbed(title, description, color = 0xFFAA00) {
|
|
||||||
return new EmbedBuilder()
|
|
||||||
.setTitle(title)
|
|
||||||
.setDescription(String(description).slice(0, 4000))
|
|
||||||
.setColor(color)
|
|
||||||
.setTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
async function postPattern(client, channelConfigKey, embed) {
|
|
||||||
const channelId = CONFIG[channelConfigKey];
|
|
||||||
if (!channelId || !client) return;
|
|
||||||
try {
|
|
||||||
const channel = await client.channels.fetch(channelId);
|
|
||||||
if (channel) await enqueueSend(channel, { embeds: [embed] });
|
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
function getWindowStartMs(windowType) {
|
|
||||||
if (windowType === 'today') {
|
|
||||||
const start = new Date();
|
|
||||||
start.setHours(0, 0, 0, 0);
|
|
||||||
return start.getTime();
|
|
||||||
}
|
|
||||||
if (windowType === 'week') return getThisWeekStart().getTime();
|
|
||||||
if (windowType === 'month') {
|
|
||||||
const start = new Date();
|
|
||||||
start.setDate(1);
|
|
||||||
start.setHours(0, 0, 0, 0);
|
|
||||||
return start.getTime();
|
|
||||||
}
|
|
||||||
return Date.now();
|
|
||||||
}
|
|
||||||
|
|
||||||
function shouldFire(alertKey, key, windowType) {
|
|
||||||
const rawThresholds = (CONFIG.NOTIFICATION_THRESHOLDS && CONFIG.NOTIFICATION_THRESHOLDS[alertKey]) || [];
|
|
||||||
const thresholds = rawThresholds
|
|
||||||
.map(parseThresholdString)
|
|
||||||
.filter(n => Number.isFinite(n) && n >= 0);
|
|
||||||
if (thresholds.length === 0) return false;
|
|
||||||
|
|
||||||
const ageMs = Date.now() - getWindowStartMs(windowType);
|
|
||||||
return shouldFireThreshold(key, ageMs, thresholds, windowType) !== null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getThisWeekStart() {
|
|
||||||
const now = new Date();
|
|
||||||
const day = now.getDay();
|
|
||||||
const diff = day === 0 ? 6 : day - 1;
|
|
||||||
const monday = new Date(now);
|
|
||||||
monday.setDate(now.getDate() - diff);
|
|
||||||
monday.setHours(0, 0, 0, 0);
|
|
||||||
return monday;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Check functions ---
|
|
||||||
|
|
||||||
async function checkUserPatterns(client) {
|
|
||||||
// Surge: users with tickets >= threshold today
|
|
||||||
const todayCounts = getAll('user_tickets', 'today');
|
|
||||||
for (const [userId, count] of todayCounts) {
|
|
||||||
if (count >= CONFIG.PATTERN_USER_TICKET_THRESHOLD) {
|
|
||||||
const key = `user_tickets:${userId}:today`;
|
|
||||||
if (isEnabled('user_tickets') && shouldFire('user_tickets', key, 'today')) {
|
|
||||||
postPattern(client, 'USER_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Repeat ticket user',
|
|
||||||
`User \`${userId}\` created ${count} tickets today (threshold: ${CONFIG.PATTERN_USER_TICKET_THRESHOLD}).`,
|
|
||||||
0xFFAA00
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reopens this week
|
|
||||||
const since = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
|
||||||
try {
|
|
||||||
const reopens = await Ticket.aggregate([
|
|
||||||
{ $match: { reopenedAt: { $gte: since } } },
|
|
||||||
{ $group: { _id: '$senderEmail', count: { $sum: 1 } } },
|
|
||||||
{ $match: { count: { $gte: 2 } } }
|
|
||||||
]);
|
|
||||||
for (const r of reopens) {
|
|
||||||
const key = `user_reopen:${r._id}:week`;
|
|
||||||
if (isEnabled('user_reopen') && shouldFire('user_reopen', key, 'week')) {
|
|
||||||
postPattern(client, 'USER_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'High reopen rate',
|
|
||||||
`${r._id} reopened tickets ${r.count}x this week`,
|
|
||||||
0xFFAA00
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
// Cross-game: users with tickets across 3+ games this week
|
|
||||||
try {
|
|
||||||
const crossGame = await Ticket.aggregate([
|
|
||||||
{ $match: { createdAt: { $gte: since }, status: { $ne: 'closed' } } },
|
|
||||||
{ $group: { _id: '$senderEmail', games: { $addToSet: '$game' } } },
|
|
||||||
{ $match: { 'games.2': { $exists: true } } }
|
|
||||||
]);
|
|
||||||
for (const c of crossGame) {
|
|
||||||
const key = `user_crossgame:${c._id}:week`;
|
|
||||||
if (isEnabled('user_crossgame') && shouldFire('user_crossgame', key, 'week')) {
|
|
||||||
postPattern(client, 'USER_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Cross-game user',
|
|
||||||
`${c._id} has tickets across ${c.games.length} games: ${c.games.filter(Boolean).join(', ')}`,
|
|
||||||
0x00AAFF
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkGamePatterns(client) {
|
|
||||||
// Surge: games with tickets >= threshold today
|
|
||||||
const todayCounts = getAll('game_tickets', 'today');
|
|
||||||
for (const [game, count] of todayCounts) {
|
|
||||||
if (count >= CONFIG.PATTERN_GAME_TICKET_THRESHOLD) {
|
|
||||||
const key = `game_surge:${game}:today`;
|
|
||||||
if (isEnabled('game_surge') && shouldFire('game_surge', key, 'today')) {
|
|
||||||
postPattern(client, 'GAME_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Game ticket surge',
|
|
||||||
`**${game}** has ${count} tickets today (threshold: ${CONFIG.PATTERN_GAME_TICKET_THRESHOLD}).`,
|
|
||||||
0xFF6600
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backlog: unclaimed tickets older than threshold
|
|
||||||
try {
|
|
||||||
const cutoff = new Date(Date.now() - CONFIG.PATTERN_UNCLAIMED_HOURS * 3600000);
|
|
||||||
const backlog = await Ticket.aggregate([
|
|
||||||
{ $match: { status: 'open', claimedBy: null, createdAt: { $lte: cutoff } } },
|
|
||||||
{ $group: { _id: '$game', count: { $sum: 1 } } },
|
|
||||||
{ $match: { count: { $gte: 3 } } }
|
|
||||||
]);
|
|
||||||
for (const b of backlog) {
|
|
||||||
const gameName = b._id || 'Unknown';
|
|
||||||
const key = `game_backlog:${gameName}:today`;
|
|
||||||
if (isEnabled('game_backlog') && shouldFire('game_backlog', key, 'today')) {
|
|
||||||
postPattern(client, 'GAME_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Game backlog alert',
|
|
||||||
`**${gameName}** has ${b.count} unclaimed tickets older than ${CONFIG.PATTERN_UNCLAIMED_HOURS}h.`,
|
|
||||||
0xFF0000
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
// Resolution time trending: this week vs last week
|
|
||||||
try {
|
|
||||||
const thisWeekStart = getThisWeekStart();
|
|
||||||
const lastWeekStart = new Date(thisWeekStart.getTime() - 7 * 24 * 60 * 60 * 1000);
|
|
||||||
const thisWeek = await Ticket.aggregate([
|
|
||||||
{ $match: { status: 'closed', closedAt: { $gte: thisWeekStart }, game: { $ne: null } } },
|
|
||||||
{ $group: { _id: '$game', avg: { $avg: { $subtract: ['$closedAt', '$createdAt'] } } } }
|
|
||||||
]);
|
|
||||||
const lastWeek = await Ticket.aggregate([
|
|
||||||
{ $match: { status: 'closed', closedAt: { $gte: lastWeekStart, $lt: thisWeekStart }, game: { $ne: null } } },
|
|
||||||
{ $group: { _id: '$game', avg: { $avg: { $subtract: ['$closedAt', '$createdAt'] } } } }
|
|
||||||
]);
|
|
||||||
const lastWeekMap = new Map(lastWeek.map(l => [l._id, l.avg]));
|
|
||||||
for (const tw of thisWeek) {
|
|
||||||
const lw = lastWeekMap.get(tw._id);
|
|
||||||
if (lw && tw.avg > lw * 1.2) {
|
|
||||||
const key = `game_resolution:${tw._id}:week`;
|
|
||||||
if (isEnabled('game_resolution') && shouldFire('game_resolution', key, 'week')) {
|
|
||||||
const twHrs = (tw.avg / 3600000).toFixed(1);
|
|
||||||
const lwHrs = (lw / 3600000).toFixed(1);
|
|
||||||
postPattern(client, 'GAME_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Resolution time increasing',
|
|
||||||
`**${tw._id}**: ${twHrs}h avg this week vs ${lwHrs}h last week (+${((tw.avg / lw - 1) * 100).toFixed(0)}%).`,
|
|
||||||
0xFFAA00
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
// Spike after silence: games with 0 tickets in last 3 days but 3+ today
|
|
||||||
try {
|
|
||||||
const threeDaysAgo = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000);
|
|
||||||
const todayStart = new Date(); todayStart.setHours(0, 0, 0, 0);
|
|
||||||
const recentByGame = await Ticket.aggregate([
|
|
||||||
{ $match: { createdAt: { $gte: threeDaysAgo, $lt: todayStart }, game: { $ne: null } } },
|
|
||||||
{ $group: { _id: '$game', count: { $sum: 1 } } }
|
|
||||||
]);
|
|
||||||
const recentGames = new Set(recentByGame.map(r => r._id));
|
|
||||||
for (const [game, count] of todayCounts) {
|
|
||||||
if (count >= 3 && !recentGames.has(game)) {
|
|
||||||
const key = `game_spike:${game}:today`;
|
|
||||||
if (isEnabled('game_spike') && shouldFire('game_spike', key, 'today')) {
|
|
||||||
postPattern(client, 'GAME_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Possible outage',
|
|
||||||
`**${game}**: ${count} tickets today after 0 in the last 3 days.`,
|
|
||||||
0xFF0000
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkTagPatterns(client) {
|
|
||||||
// Most common tag today
|
|
||||||
const todayTags = getAll('tag_usage', 'today');
|
|
||||||
let topTag = null, topCount = 0;
|
|
||||||
for (const [tag, count] of todayTags) {
|
|
||||||
if (count > topCount) { topTag = tag; topCount = count; }
|
|
||||||
}
|
|
||||||
if (topTag && topCount >= 5) {
|
|
||||||
const key = `tag_top:${topTag}:today`;
|
|
||||||
if (isEnabled('tag_top') && shouldFire('tag_top', key, 'today')) {
|
|
||||||
postPattern(client, 'TAG_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Top issue tag today',
|
|
||||||
`**${topTag}** used ${topCount} times today.`,
|
|
||||||
0x00AAFF
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tag→escalation correlation
|
|
||||||
try {
|
|
||||||
const since = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
|
||||||
const tagEscalations = await Ticket.aggregate([
|
|
||||||
{ $match: { createdAt: { $gte: since }, escalationTier: { $gte: 1 }, ticketTag: { $ne: null } } },
|
|
||||||
{ $group: { _id: '$ticketTag', count: { $sum: 1 } } },
|
|
||||||
{ $match: { count: { $gte: 3 } } }
|
|
||||||
]);
|
|
||||||
for (const te of tagEscalations) {
|
|
||||||
const key = `tag_escalation:${te._id}:week`;
|
|
||||||
if (isEnabled('tag_escalation') && shouldFire('tag_escalation', key, 'week')) {
|
|
||||||
postPattern(client, 'TAG_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Tag frequently leads to escalation',
|
|
||||||
`**${te._id}**: ${te.count} escalated tickets this week.`,
|
|
||||||
0xFFAA00
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
// Untagged closes
|
|
||||||
const untaggedCount = get('untagged_closes', 'total', 'today');
|
|
||||||
if (untaggedCount >= 5) {
|
|
||||||
const key = 'untagged_closes:today';
|
|
||||||
if (isEnabled('untagged_closes') && shouldFire('untagged_closes', key, 'today')) {
|
|
||||||
postPattern(client, 'TAG_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'High untagged close rate',
|
|
||||||
`${untaggedCount} tickets closed today without a tag.`,
|
|
||||||
0xFFAA00
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tag↔game correlation: for each tag this week, check if one game dominates
|
|
||||||
const weekTags = getAll('tag_usage', 'week');
|
|
||||||
for (const [tag] of weekTags) {
|
|
||||||
const tagGameCounts = getAll(`tag_game:${tag}`, 'week');
|
|
||||||
let total = 0, maxGame = null, maxCount = 0;
|
|
||||||
for (const [game, count] of tagGameCounts) {
|
|
||||||
total += count;
|
|
||||||
if (count > maxCount) { maxGame = game; maxCount = count; }
|
|
||||||
}
|
|
||||||
if (total >= 5 && maxGame && maxCount / total > 0.8) {
|
|
||||||
const key = `tag_game_corr:${tag}:${maxGame}:week`;
|
|
||||||
if (isEnabled('tag_game_corr') && shouldFire('tag_game_corr', key, 'week')) {
|
|
||||||
postPattern(client, 'COMBINED_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Auto-tagging opportunity',
|
|
||||||
`**${tag}** is ${Math.round(maxCount / total * 100)}% from **${maxGame}** (${maxCount}/${total} this week).`,
|
|
||||||
0x00AAFF
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkEscalationPatterns(client) {
|
|
||||||
// User escalation rate
|
|
||||||
const userEscalations = getAll('user_escalations', 'week');
|
|
||||||
for (const [user, count] of userEscalations) {
|
|
||||||
if (count >= CONFIG.PATTERN_ESCALATION_THRESHOLD) {
|
|
||||||
const key = `user_esc:${user}:week`;
|
|
||||||
if (isEnabled('user_esc') && shouldFire('user_esc', key, 'week')) {
|
|
||||||
postPattern(client, 'ESCALATION_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Frequent escalation user',
|
|
||||||
`\`${user}\` has ${count} escalated tickets this week (threshold: ${CONFIG.PATTERN_ESCALATION_THRESHOLD}).`,
|
|
||||||
0xFFAA00
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Game escalation rate vs baseline
|
|
||||||
try {
|
|
||||||
const thisWeekStart = getThisWeekStart();
|
|
||||||
const thisWeek = await Ticket.aggregate([
|
|
||||||
{ $match: { escalationTier: { $gte: 1 }, createdAt: { $gte: thisWeekStart } } },
|
|
||||||
{ $group: { _id: '$game', count: { $sum: 1 } } }
|
|
||||||
]);
|
|
||||||
const totalThisWeek = await Ticket.countDocuments({ createdAt: { $gte: thisWeekStart } });
|
|
||||||
for (const tw of thisWeek) {
|
|
||||||
if (!tw._id) continue;
|
|
||||||
const gameTotal = await Ticket.countDocuments({ createdAt: { $gte: thisWeekStart }, game: tw._id });
|
|
||||||
if (gameTotal > 0 && tw.count / gameTotal > 0.5) {
|
|
||||||
const key = `game_esc_rate:${tw._id}:week`;
|
|
||||||
if (isEnabled('game_esc_rate') && shouldFire('game_esc_rate', key, 'week')) {
|
|
||||||
postPattern(client, 'ESCALATION_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'High escalation rate for game',
|
|
||||||
`**${tw._id}**: ${tw.count}/${gameTotal} tickets escalated (${Math.round(tw.count / gameTotal * 100)}%) this week.`,
|
|
||||||
0xFF6600
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
// Rapid tier 2→3
|
|
||||||
if (!isEnabled('rapid_t2_t3')) return;
|
|
||||||
try {
|
|
||||||
const since = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
|
||||||
const rapid = await Ticket.find({
|
|
||||||
escalationTier: 2,
|
|
||||||
escalatedAt: { $gte: since }
|
|
||||||
}).lean();
|
|
||||||
// Count tickets where escalation happened very quickly (approximate: check if tier was changed recently)
|
|
||||||
const rapidCount = rapid.length;
|
|
||||||
if (rapidCount >= 3) {
|
|
||||||
const key = 'rapid_t2_t3:week';
|
|
||||||
const rawThresholds = (CONFIG.NOTIFICATION_THRESHOLDS && CONFIG.NOTIFICATION_THRESHOLDS.rapid_t2_t3) || [];
|
|
||||||
const thresholds = rawThresholds
|
|
||||||
.map(parseThresholdString)
|
|
||||||
.filter(n => Number.isFinite(n) && n >= 0)
|
|
||||||
.sort((a, b) => a - b);
|
|
||||||
const firedSet = firedCountMilestones.get(key) || new Set();
|
|
||||||
let shouldNotify = false;
|
|
||||||
for (const threshold of thresholds) {
|
|
||||||
if (rapidCount >= threshold && !firedSet.has(threshold)) {
|
|
||||||
firedSet.add(threshold);
|
|
||||||
shouldNotify = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (shouldNotify) {
|
|
||||||
firedCountMilestones.set(key, firedSet);
|
|
||||||
postPattern(client, 'ESCALATION_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Rapid tier 3 escalations',
|
|
||||||
`${rapidCount} tickets reached tier 3 this week.`,
|
|
||||||
0xFF0000
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkStaffPatterns(client) {
|
|
||||||
// Claims without closes
|
|
||||||
const todayClaims = getAll('staff_claims', 'today');
|
|
||||||
for (const [staffId, claims] of todayClaims) {
|
|
||||||
if (claims >= 3 && get('staff_closes', staffId, 'today') === 0) {
|
|
||||||
const key = `staff_no_close:${staffId}:today`;
|
|
||||||
if (isEnabled('staff_no_close') && shouldFire('staff_no_close', key, 'today')) {
|
|
||||||
postPattern(client, 'STAFF_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Claims without closes',
|
|
||||||
`Staff \`${staffId}\` claimed ${claims} tickets today but closed 0.`,
|
|
||||||
0xFFAA00
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Overloaded: open tickets per claimer
|
|
||||||
try {
|
|
||||||
const overloaded = await Ticket.aggregate([
|
|
||||||
{ $match: { status: 'open', claimerId: { $ne: null } } },
|
|
||||||
{ $group: { _id: '$claimerId', count: { $sum: 1 } } },
|
|
||||||
{ $match: { count: { $gte: 5 } } }
|
|
||||||
]);
|
|
||||||
for (const o of overloaded) {
|
|
||||||
const key = `staff_overloaded:${o._id}:today`;
|
|
||||||
if (isEnabled('staff_overloaded') && shouldFire('staff_overloaded', key, 'today')) {
|
|
||||||
postPattern(client, 'STAFF_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Staff overloaded',
|
|
||||||
`Staff \`${o._id}\` has ${o.count} open claimed tickets.`,
|
|
||||||
0xFF6600
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
// Stale ping threshold
|
|
||||||
const stalePings = getAll('staff_stale_pings', 'today');
|
|
||||||
for (const [staffId, count] of stalePings) {
|
|
||||||
if (count >= CONFIG.PATTERN_STAFF_STALE_PING_THRESHOLD) {
|
|
||||||
const key = `staff_stale:${staffId}:today`;
|
|
||||||
if (isEnabled('staff_stale') && shouldFire('staff_stale', key, 'today')) {
|
|
||||||
postPattern(client, 'STAFF_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Staff stale ping threshold',
|
|
||||||
`Staff \`${staffId}\` received ${count} stale pings today.`,
|
|
||||||
0xFFAA00
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transfer rate
|
|
||||||
const todayTransfers = getAll('staff_transfers', 'today');
|
|
||||||
for (const [staffId, transfers] of todayTransfers) {
|
|
||||||
const claims = get('staff_claims', staffId, 'today');
|
|
||||||
if (claims > 0 && transfers >= claims) {
|
|
||||||
const key = `staff_transfer_rate:${staffId}:today`;
|
|
||||||
if (isEnabled('staff_transfer_rate') && shouldFire('staff_transfer_rate', key, 'today')) {
|
|
||||||
postPattern(client, 'STAFF_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'High transfer rate',
|
|
||||||
`Staff \`${staffId}\` transferred ${transfers}/${claims} claimed tickets today.`,
|
|
||||||
0xFFAA00
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Escalations per staff
|
|
||||||
const weekEscalations = getAll('staff_escalations', 'week');
|
|
||||||
for (const [staffId, count] of weekEscalations) {
|
|
||||||
if (count >= CONFIG.PATTERN_ESCALATION_THRESHOLD) {
|
|
||||||
const key = `staff_esc:${staffId}:week`;
|
|
||||||
if (isEnabled('staff_esc') && shouldFire('staff_esc', key, 'week')) {
|
|
||||||
postPattern(client, 'STAFF_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Staff frequent escalator',
|
|
||||||
`Staff \`${staffId}\` escalated ${count} tickets this week.`,
|
|
||||||
0xFFAA00
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkCombinedPatterns(client) {
|
|
||||||
// Staff+game escalation correlation
|
|
||||||
const weekEscStaff = getAll('staff_escalations', 'week');
|
|
||||||
for (const [staffId] of weekEscStaff) {
|
|
||||||
const gameEsc = getAll(`staff_game_escalations:${staffId}`, 'week');
|
|
||||||
for (const [game, count] of gameEsc) {
|
|
||||||
if (count >= 3) {
|
|
||||||
const key = `staff_game_esc:${staffId}:${game}:week`;
|
|
||||||
if (isEnabled('staff_game_esc') && shouldFire('staff_game_esc', key, 'week')) {
|
|
||||||
postPattern(client, 'COMBINED_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Staff may need training for this game',
|
|
||||||
`Staff \`${staffId}\` escalated ${count} **${game}** tickets this week.`,
|
|
||||||
0xFFAA00
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Game+tag spike: specific game+tag combo >= 5 today
|
|
||||||
const todayGames = getAll('game_tickets', 'today');
|
|
||||||
const todayTags = getAll('tag_usage', 'today');
|
|
||||||
for (const [game] of todayGames) {
|
|
||||||
for (const [tag] of todayTags) {
|
|
||||||
const tagGameCount = get(`tag_game:${tag}`, game, 'week');
|
|
||||||
if (tagGameCount >= 5) {
|
|
||||||
const key = `game_tag_spike:${game}:${tag}:today`;
|
|
||||||
if (isEnabled('game_tag_spike') && shouldFire('game_tag_spike', key, 'today')) {
|
|
||||||
postPattern(client, 'COMBINED_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Specific feature of specific game spiking',
|
|
||||||
`**${game}** + **${tag}**: ${tagGameCount} tickets this week.`,
|
|
||||||
0xFF6600
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Overnight escalation gap: compare 00:00-06:00 vs daytime escalation rates
|
|
||||||
try {
|
|
||||||
const since = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
|
||||||
const overnight = await Ticket.countDocuments({
|
|
||||||
createdAt: { $gte: since },
|
|
||||||
escalationTier: { $gte: 1 },
|
|
||||||
$expr: { $and: [{ $gte: [{ $hour: '$createdAt' }, 0] }, { $lt: [{ $hour: '$createdAt' }, 6] }] }
|
|
||||||
});
|
|
||||||
const daytime = await Ticket.countDocuments({
|
|
||||||
createdAt: { $gte: since },
|
|
||||||
escalationTier: { $gte: 1 },
|
|
||||||
$expr: { $and: [{ $gte: [{ $hour: '$createdAt' }, 6] }, { $lt: [{ $hour: '$createdAt' }, 24] }] }
|
|
||||||
});
|
|
||||||
const overnightTotal = await Ticket.countDocuments({
|
|
||||||
createdAt: { $gte: since },
|
|
||||||
$expr: { $and: [{ $gte: [{ $hour: '$createdAt' }, 0] }, { $lt: [{ $hour: '$createdAt' }, 6] }] }
|
|
||||||
});
|
|
||||||
const daytimeTotal = await Ticket.countDocuments({
|
|
||||||
createdAt: { $gte: since },
|
|
||||||
$expr: { $and: [{ $gte: [{ $hour: '$createdAt' }, 6] }, { $lt: [{ $hour: '$createdAt' }, 24] }] }
|
|
||||||
});
|
|
||||||
if (overnightTotal > 0 && daytimeTotal > 0) {
|
|
||||||
const overnightRate = overnight / overnightTotal;
|
|
||||||
const daytimeRate = daytime / daytimeTotal;
|
|
||||||
if (overnightRate > daytimeRate * 2 && overnight >= 3) {
|
|
||||||
const key = 'overnight_gap:week';
|
|
||||||
if (isEnabled('overnight_gap') && shouldFire('overnight_gap', key, 'week')) {
|
|
||||||
postPattern(client, 'COMBINED_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Overnight coverage gap',
|
|
||||||
`Overnight escalation rate: ${Math.round(overnightRate * 100)}% vs daytime ${Math.round(daytimeRate * 100)}%.`,
|
|
||||||
0xFF0000
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
// Staff never resolves game X without escalating
|
|
||||||
try {
|
|
||||||
const monthStart = new Date();
|
|
||||||
monthStart.setDate(1);
|
|
||||||
monthStart.setHours(0, 0, 0, 0);
|
|
||||||
const staffGameStats = await Ticket.aggregate([
|
|
||||||
{ $match: { claimerId: { $ne: null }, game: { $ne: null }, createdAt: { $gte: monthStart } } },
|
|
||||||
{ $group: {
|
|
||||||
_id: { staff: '$claimerId', game: '$game' },
|
|
||||||
total: { $sum: 1 },
|
|
||||||
escalated: { $sum: { $cond: [{ $gte: ['$escalationTier', 1] }, 1, 0] } }
|
|
||||||
}},
|
|
||||||
{ $match: { total: { $gte: 3 } } }
|
|
||||||
]);
|
|
||||||
for (const s of staffGameStats) {
|
|
||||||
if (s.escalated / s.total >= 0.9) {
|
|
||||||
const key = `staff_always_esc:${s._id.staff}:${s._id.game}:month`;
|
|
||||||
if (isEnabled('staff_always_esc') && shouldFire('staff_always_esc', key, 'month')) {
|
|
||||||
postPattern(client, 'COMBINED_PATTERNS_CHANNEL_ID', buildEmbed(
|
|
||||||
'Staff always escalates this game',
|
|
||||||
`Staff \`${s._id.staff}\` escalated ${s.escalated}/${s.total} **${s._id.game}** tickets this month.`,
|
|
||||||
0xFF6600
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Main entry point ---
|
|
||||||
|
|
||||||
async function runPatternChecks(client) {
|
|
||||||
try { await checkUserPatterns(client); } catch (e) { console.error('checkUserPatterns:', e); }
|
|
||||||
try { await checkGamePatterns(client); } catch (e) { console.error('checkGamePatterns:', e); }
|
|
||||||
try { await checkTagPatterns(client); } catch (e) { console.error('checkTagPatterns:', e); }
|
|
||||||
try { await checkEscalationPatterns(client); } catch (e) { console.error('checkEscalationPatterns:', e); }
|
|
||||||
try { await checkStaffPatterns(client); } catch (e) { console.error('checkStaffPatterns:', e); }
|
|
||||||
try { await checkCombinedPatterns(client); } catch (e) { console.error('checkCombinedPatterns:', e); }
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { runPatternChecks };
|
|
||||||
@@ -1,286 +0,0 @@
|
|||||||
/**
|
|
||||||
* In-memory counter store with TTL windows for pattern detection.
|
|
||||||
* Windows: 'today' resets at midnight, 'week' resets Monday 00:00, 'month' resets 1st 00:00.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// store[window][namespace][key] = count
|
|
||||||
const store = {
|
|
||||||
today: new Map(),
|
|
||||||
week: new Map(),
|
|
||||||
month: new Map()
|
|
||||||
};
|
|
||||||
|
|
||||||
function getNamespaceMap(window, namespace) {
|
|
||||||
const windowMap = store[window];
|
|
||||||
if (!windowMap) return null;
|
|
||||||
if (!windowMap.has(namespace)) windowMap.set(namespace, new Map());
|
|
||||||
return windowMap.get(namespace);
|
|
||||||
}
|
|
||||||
|
|
||||||
function increment(namespace, key, window) {
|
|
||||||
const map = getNamespaceMap(window, namespace);
|
|
||||||
if (!map) return;
|
|
||||||
map.set(key, (map.get(key) || 0) + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
function get(namespace, key, window) {
|
|
||||||
const map = getNamespaceMap(window, namespace);
|
|
||||||
if (!map) return 0;
|
|
||||||
return map.get(key) || 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
function reset(namespace, window) {
|
|
||||||
const windowMap = store[window];
|
|
||||||
if (!windowMap) return;
|
|
||||||
windowMap.delete(namespace);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getAll(namespace, window) {
|
|
||||||
const map = getNamespaceMap(window, namespace);
|
|
||||||
if (!map) return new Map();
|
|
||||||
return new Map(map);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Scheduled resets ---
|
|
||||||
|
|
||||||
function msUntilNextMidnight() {
|
|
||||||
const now = new Date();
|
|
||||||
const next = new Date(now);
|
|
||||||
next.setHours(24, 0, 0, 0);
|
|
||||||
return next.getTime() - now.getTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
function msUntilNextMonday() {
|
|
||||||
const now = new Date();
|
|
||||||
const day = now.getDay(); // 0=Sun
|
|
||||||
const daysUntilMonday = day === 0 ? 1 : (8 - day);
|
|
||||||
const next = new Date(now);
|
|
||||||
next.setDate(now.getDate() + daysUntilMonday);
|
|
||||||
next.setHours(0, 0, 0, 0);
|
|
||||||
return next.getTime() - now.getTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
function msUntilNextMonth() {
|
|
||||||
const now = new Date();
|
|
||||||
const next = new Date(now.getFullYear(), now.getMonth() + 1, 1, 0, 0, 0, 0);
|
|
||||||
return next.getTime() - now.getTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Callbacks to run on daily reset (e.g. clear firedToday in patternChecker)
|
|
||||||
const dailyResetCallbacks = [];
|
|
||||||
const weeklyResetCallbacks = [];
|
|
||||||
|
|
||||||
function onDailyReset(fn) {
|
|
||||||
dailyResetCallbacks.push(fn);
|
|
||||||
}
|
|
||||||
|
|
||||||
function onWeeklyReset(fn) {
|
|
||||||
weeklyResetCallbacks.push(fn);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Threshold firing state ---
|
|
||||||
// key -> Set<thresholdMs> that have fired within the key's window.
|
|
||||||
const firedThresholds = new Map();
|
|
||||||
// key -> window type used for threshold clearing ("today" | "week" | "month")
|
|
||||||
const firedThresholdWindows = new Map();
|
|
||||||
// key -> last-seen timestamp; drives periodic sweep for keys that outlive their window reset.
|
|
||||||
const firedThresholdLastSeen = new Map();
|
|
||||||
|
|
||||||
function clearFiredThresholdsForWindow(windowType) {
|
|
||||||
for (const [key, mappedWindowType] of firedThresholdWindows.entries()) {
|
|
||||||
if (mappedWindowType === windowType) {
|
|
||||||
firedThresholds.delete(key);
|
|
||||||
firedThresholdWindows.delete(key);
|
|
||||||
firedThresholdLastSeen.delete(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function shouldFireThreshold(key, ageMs, thresholdsMs, windowType) {
|
|
||||||
if (!Array.isArray(thresholdsMs) || thresholdsMs.length === 0) return null;
|
|
||||||
if (!['today', 'week', 'month'].includes(windowType)) return null;
|
|
||||||
|
|
||||||
firedThresholdWindows.set(key, windowType);
|
|
||||||
firedThresholdLastSeen.set(key, Date.now());
|
|
||||||
|
|
||||||
const firedForKey = firedThresholds.get(key) || new Set();
|
|
||||||
const sortedThresholds = [...thresholdsMs].sort((a, b) => a - b);
|
|
||||||
|
|
||||||
let highestUnfiredCrossed = null;
|
|
||||||
for (const thresholdMs of sortedThresholds) {
|
|
||||||
if (ageMs >= thresholdMs && !firedForKey.has(thresholdMs)) {
|
|
||||||
highestUnfiredCrossed = thresholdMs;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (highestUnfiredCrossed === null) return null;
|
|
||||||
|
|
||||||
firedForKey.add(highestUnfiredCrossed);
|
|
||||||
firedThresholds.set(key, firedForKey);
|
|
||||||
return highestUnfiredCrossed;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Escalating cooldown state ---
|
|
||||||
// key -> { startedAtMs, lastFireAtMs, fireCount }
|
|
||||||
const escalatingCooldowns = new Map();
|
|
||||||
|
|
||||||
function shouldFireCooldownEscalating(key, thresholdsMs) {
|
|
||||||
if (!Array.isArray(thresholdsMs) || thresholdsMs.length === 0) return null;
|
|
||||||
|
|
||||||
const sortedThresholds = [...thresholdsMs].sort((a, b) => a - b);
|
|
||||||
const now = Date.now();
|
|
||||||
let state = escalatingCooldowns.get(key);
|
|
||||||
|
|
||||||
if (!state) {
|
|
||||||
state = { startedAtMs: now, lastFireAtMs: null, fireCount: 0, lastUsed: now };
|
|
||||||
escalatingCooldowns.set(key, state);
|
|
||||||
}
|
|
||||||
state.lastUsed = now;
|
|
||||||
|
|
||||||
const nextThreshold = sortedThresholds[state.fireCount];
|
|
||||||
if (typeof nextThreshold !== 'number') return null;
|
|
||||||
|
|
||||||
const referenceMs = state.fireCount === 0 ? state.startedAtMs : state.lastFireAtMs;
|
|
||||||
if ((now - referenceMs) < nextThreshold) return null;
|
|
||||||
|
|
||||||
state.fireCount += 1;
|
|
||||||
state.lastFireAtMs = now;
|
|
||||||
return nextThreshold;
|
|
||||||
}
|
|
||||||
|
|
||||||
function clearEscalating(key) {
|
|
||||||
escalatingCooldowns.delete(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
const SWEEP_TTL_MS = 48 * 60 * 60 * 1000;
|
|
||||||
const SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
|
||||||
|
|
||||||
function cleanupStaleEscalatingCooldowns(now = Date.now()) {
|
|
||||||
const cutoff = now - SWEEP_TTL_MS;
|
|
||||||
for (const [key, state] of escalatingCooldowns.entries()) {
|
|
||||||
const lastUsed = state.lastUsed || state.lastFireAtMs || state.startedAtMs || 0;
|
|
||||||
if (lastUsed < cutoff) escalatingCooldowns.delete(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sweep every per-Map timestamp-bearing entry older than SWEEP_TTL_MS.
|
|
||||||
// firedThresholds/firedThresholdWindows are cleared by windowType-resets;
|
|
||||||
// this sweep covers keys whose window never resets under load.
|
|
||||||
function sweepPatternStore(now = Date.now()) {
|
|
||||||
const cutoff = now - SWEEP_TTL_MS;
|
|
||||||
for (const [key, ts] of cooldowns.entries()) {
|
|
||||||
if (ts < cutoff) cooldowns.delete(key);
|
|
||||||
}
|
|
||||||
for (const [key, ts] of staffLastSeen.entries()) {
|
|
||||||
if (ts < cutoff) staffLastSeen.delete(key);
|
|
||||||
}
|
|
||||||
cleanupStaleEscalatingCooldowns(now);
|
|
||||||
for (const [key, ts] of firedThresholdLastSeen.entries()) {
|
|
||||||
if (ts < cutoff) {
|
|
||||||
firedThresholds.delete(key);
|
|
||||||
firedThresholdWindows.delete(key);
|
|
||||||
firedThresholdLastSeen.delete(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register the module's sweep on the given trackInterval function.
|
|
||||||
* Called once from the ready handler. Interval is unref'd so it never
|
|
||||||
* blocks shutdown; trackInterval ensures handleShutdown clears it.
|
|
||||||
*/
|
|
||||||
function startSweeps(trackInterval) {
|
|
||||||
const handle = setInterval(() => sweepPatternStore(), SWEEP_INTERVAL_MS);
|
|
||||||
if (typeof handle.unref === 'function') handle.unref();
|
|
||||||
if (typeof trackInterval === 'function') trackInterval(handle);
|
|
||||||
return handle;
|
|
||||||
}
|
|
||||||
|
|
||||||
function scheduleDailyReset() {
|
|
||||||
setTimeout(() => {
|
|
||||||
store.today = new Map();
|
|
||||||
clearFiredThresholdsForWindow('today');
|
|
||||||
for (const fn of dailyResetCallbacks) {
|
|
||||||
try { fn(); } catch (_) {}
|
|
||||||
}
|
|
||||||
scheduleDailyReset();
|
|
||||||
}, msUntilNextMidnight());
|
|
||||||
}
|
|
||||||
|
|
||||||
function scheduleWeeklyReset() {
|
|
||||||
setTimeout(() => {
|
|
||||||
store.week = new Map();
|
|
||||||
clearFiredThresholdsForWindow('week');
|
|
||||||
for (const fn of weeklyResetCallbacks) {
|
|
||||||
try { fn(); } catch (_) {}
|
|
||||||
}
|
|
||||||
scheduleWeeklyReset();
|
|
||||||
}, msUntilNextMonday());
|
|
||||||
}
|
|
||||||
|
|
||||||
function scheduleMonthlyReset() {
|
|
||||||
setTimeout(() => {
|
|
||||||
store.month = new Map();
|
|
||||||
clearFiredThresholdsForWindow('month');
|
|
||||||
scheduleMonthlyReset();
|
|
||||||
}, msUntilNextMonth());
|
|
||||||
}
|
|
||||||
|
|
||||||
function scheduleResets() {
|
|
||||||
scheduleDailyReset();
|
|
||||||
scheduleWeeklyReset();
|
|
||||||
scheduleMonthlyReset();
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Cooldown store ---
|
|
||||||
const cooldowns = new Map();
|
|
||||||
|
|
||||||
function setCooldown(key) {
|
|
||||||
cooldowns.set(key, Date.now());
|
|
||||||
}
|
|
||||||
|
|
||||||
function isOnCooldown(key, cooldownMinutes) {
|
|
||||||
const last = cooldowns.get(key);
|
|
||||||
if (!last) return false;
|
|
||||||
return (Date.now() - last) < cooldownMinutes * 60 * 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Staff last-seen tracker (fallback for missing presence intent) ---
|
|
||||||
const staffLastSeen = new Map();
|
|
||||||
|
|
||||||
function updateStaffLastSeen(staffId) {
|
|
||||||
staffLastSeen.set(staffId, Date.now());
|
|
||||||
}
|
|
||||||
|
|
||||||
function getStaffLastSeen(staffId) {
|
|
||||||
return staffLastSeen.get(staffId) || null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isStaffRecentlyActive(staffId, withinMinutes = 60) {
|
|
||||||
const last = staffLastSeen.get(staffId);
|
|
||||||
if (!last) return false;
|
|
||||||
return (Date.now() - last) < withinMinutes * 60 * 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
increment,
|
|
||||||
get,
|
|
||||||
reset,
|
|
||||||
getAll,
|
|
||||||
scheduleResets,
|
|
||||||
onDailyReset,
|
|
||||||
onWeeklyReset,
|
|
||||||
firedThresholds,
|
|
||||||
shouldFireThreshold,
|
|
||||||
shouldFireCooldownEscalating,
|
|
||||||
clearEscalating,
|
|
||||||
setCooldown,
|
|
||||||
isOnCooldown,
|
|
||||||
updateStaffLastSeen,
|
|
||||||
getStaffLastSeen,
|
|
||||||
isStaffRecentlyActive,
|
|
||||||
startSweeps,
|
|
||||||
sweepPatternStore,
|
|
||||||
// test-only exports
|
|
||||||
_internals: { cooldowns, staffLastSeen, escalatingCooldowns, firedThresholds, firedThresholdWindows, firedThresholdLastSeen, SWEEP_TTL_MS }
|
|
||||||
};
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
const { CONFIG } = require('../config');
|
|
||||||
const { enqueueSend } = require('./channelQueue');
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a staff tracking channel for a ticket.
|
|
||||||
* Returns the created channel or null if no staff category configured.
|
|
||||||
*/
|
|
||||||
async function createStaffChannel(guild, ticket, claimerId, channelName) {
|
|
||||||
const categoryId = CONFIG.STAFF_CATEGORIES.get(claimerId);
|
|
||||||
if (!categoryId) return null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { ChannelType } = require('discord.js');
|
|
||||||
const staffChan = await guild.channels.create({
|
|
||||||
name: channelName,
|
|
||||||
type: ChannelType.GuildText,
|
|
||||||
parent: categoryId
|
|
||||||
});
|
|
||||||
|
|
||||||
// Build pinned embed with ticket info + jump link to original ticket channel
|
|
||||||
const { EmbedBuilder } = require('discord.js');
|
|
||||||
const originalChannel = await guild.channels.fetch(ticket.discordThreadId).catch(() => null);
|
|
||||||
const jumpLink = originalChannel ? `https://discord.com/channels/${guild.id}/${ticket.discordThreadId}` : null;
|
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
|
||||||
.setTitle(`🎫 Ticket #${ticket.ticketNumber}`)
|
|
||||||
.setColor(0x5865f2)
|
|
||||||
.addFields(
|
|
||||||
{ name: 'Customer', value: ticket.senderEmail || 'Unknown', inline: true },
|
|
||||||
{ name: 'Game', value: ticket.game || 'Not detected', inline: true },
|
|
||||||
{ name: 'Subject', value: ticket.subject || 'No subject', inline: false },
|
|
||||||
{ name: 'Original Ticket', value: jumpLink ? `[Jump to ticket](${jumpLink})` : 'Unknown', inline: false }
|
|
||||||
)
|
|
||||||
.setFooter({ text: `Claimed by ${ticket.claimedBy || 'Unknown'}` })
|
|
||||||
.setTimestamp();
|
|
||||||
|
|
||||||
const pinMsg = await enqueueSend(staffChan, { embeds: [embed] });
|
|
||||||
await pinMsg.pin().catch(() => {});
|
|
||||||
|
|
||||||
return staffChan;
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to create staff channel:', e);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ping the staff channel with a customer reply, including jump link and message copy.
|
|
||||||
*/
|
|
||||||
async function pingStaffChannel(staffChannel, claimerId, originalMessage) {
|
|
||||||
if (!staffChannel) return;
|
|
||||||
try {
|
|
||||||
const jumpLink = `https://discord.com/channels/${originalMessage.guild.id}/${originalMessage.channel.id}/${originalMessage.id}`;
|
|
||||||
await enqueueSend(staffChannel,
|
|
||||||
`<@${claimerId}> Customer replied in ticket:\n> ${originalMessage.content.slice(0, 500)}\n[Jump to message](${jumpLink})`
|
|
||||||
);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to ping staff channel:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Move staff channel to a different category.
|
|
||||||
*/
|
|
||||||
async function moveStaffChannel(staffChannel, categoryId) {
|
|
||||||
if (!staffChannel || !categoryId) return;
|
|
||||||
try {
|
|
||||||
const { enqueueMove } = require('./channelQueue');
|
|
||||||
await enqueueMove(staffChannel, categoryId);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to move staff channel:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Delete the staff tracking channel.
|
|
||||||
*/
|
|
||||||
async function deleteStaffChannel(guild, staffChannelId) {
|
|
||||||
if (!staffChannelId) return;
|
|
||||||
try {
|
|
||||||
const chan = await guild.channels.fetch(staffChannelId).catch(() => null);
|
|
||||||
// TODO(queue-migrate): raw channel.delete bypasses channelQueue (enqueueDelete) — if a staff-channel send is in-flight, this can race it.
|
|
||||||
if (chan) await chan.delete();
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to delete staff channel:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { createStaffChannel, pingStaffChannel, moveStaffChannel, deleteStaffChannel };
|
|
||||||
@@ -1,149 +0,0 @@
|
|||||||
/**
|
|
||||||
* Staff notification service – reply alerts and unclaimed ticket reminders.
|
|
||||||
*
|
|
||||||
* notifyStaffOfReply: posts in the claimer's notification channel when a
|
|
||||||
* non-staff user replies, respecting a per-staff cooldown.
|
|
||||||
*
|
|
||||||
* notifyAllStaffUnclaimed: background job that checks unclaimed tickets
|
|
||||||
* against configurable hour thresholds and posts one alert per threshold
|
|
||||||
* per ticket (highest newly-crossed threshold only).
|
|
||||||
*/
|
|
||||||
const { mongoose } = require('../db-connection');
|
|
||||||
const { CONFIG, parseThresholdString } = require('../config');
|
|
||||||
const { increment } = require('./patternStore');
|
|
||||||
const { enqueueSend } = require('./channelQueue');
|
|
||||||
const { assertKeysRegistered } = require('./notificationRegistry');
|
|
||||||
const { isEnabled } = require('./notificationEnabled');
|
|
||||||
|
|
||||||
// Alert key this module drives. Registered to fail fast on drift.
|
|
||||||
const UNCLAIMED_ALERT_KEYS = ['unclaimed_reminder'];
|
|
||||||
assertKeysRegistered('staffNotifications', UNCLAIMED_ALERT_KEYS);
|
|
||||||
|
|
||||||
const Ticket = mongoose.model('Ticket');
|
|
||||||
const StaffNotification = mongoose.model('StaffNotification');
|
|
||||||
|
|
||||||
// In-memory cooldown map: `${userId}:${ticketId}` -> last notified timestamp
|
|
||||||
const replyCooldowns = new Map();
|
|
||||||
|
|
||||||
const REPLY_COOLDOWN_SWEEP_TTL_MS = 48 * 60 * 60 * 1000;
|
|
||||||
const REPLY_COOLDOWN_SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
|
||||||
|
|
||||||
function sweepReplyCooldowns(now = Date.now()) {
|
|
||||||
const cutoff = now - REPLY_COOLDOWN_SWEEP_TTL_MS;
|
|
||||||
for (const [key, ts] of replyCooldowns.entries()) {
|
|
||||||
if (ts < cutoff) replyCooldowns.delete(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function startSweeps(trackInterval) {
|
|
||||||
const handle = setInterval(() => sweepReplyCooldowns(), REPLY_COOLDOWN_SWEEP_INTERVAL_MS);
|
|
||||||
if (typeof handle.unref === 'function') handle.unref();
|
|
||||||
if (typeof trackInterval === 'function') trackInterval(handle);
|
|
||||||
return handle;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Notify the claiming staff member when a non-staff user replies.
|
|
||||||
* Respects the staff member's cooldownHours setting (default 1h).
|
|
||||||
* Posts in their notification channel if one exists.
|
|
||||||
*/
|
|
||||||
async function notifyStaffOfReply(guild, ticket, message) {
|
|
||||||
if (!ticket.claimerId) return;
|
|
||||||
|
|
||||||
const staffRecord = await StaffNotification.findOne({ userId: ticket.claimerId }).lean();
|
|
||||||
if (!staffRecord?.channelId) return;
|
|
||||||
|
|
||||||
const cooldownMs = (staffRecord.cooldownHours || 1) * 60 * 60 * 1000;
|
|
||||||
const cooldownKey = `${ticket.claimerId}:${ticket.gmailThreadId}`;
|
|
||||||
const lastNotified = replyCooldowns.get(cooldownKey) || 0;
|
|
||||||
if (Date.now() - lastNotified < cooldownMs) return;
|
|
||||||
|
|
||||||
const notifChannel = await guild.channels.fetch(staffRecord.channelId).catch(() => null);
|
|
||||||
if (!notifChannel) return;
|
|
||||||
|
|
||||||
const jumpLink = `https://discord.com/channels/${guild.id}/${message.channel.id}/${message.id}`;
|
|
||||||
const snippet = message.content?.slice(0, 300) || '(no text)';
|
|
||||||
await enqueueSend(
|
|
||||||
notifChannel,
|
|
||||||
`New reply in **${message.channel.name}** from ${message.author.tag}:\n> ${snippet}\n[Jump to message](${jumpLink})`
|
|
||||||
);
|
|
||||||
|
|
||||||
replyCooldowns.set(cooldownKey, Date.now());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Background job: check all open unclaimed tickets against hour thresholds.
|
|
||||||
* For each ticket, find the highest threshold that has been crossed but not
|
|
||||||
* yet recorded. Post one notification per ticket per run (the highest new
|
|
||||||
* threshold) into every staff notification channel.
|
|
||||||
*/
|
|
||||||
async function notifyAllStaffUnclaimed(client) {
|
|
||||||
if (!isEnabled('unclaimed_reminder')) return;
|
|
||||||
const rawThresholds = (CONFIG.NOTIFICATION_THRESHOLDS && CONFIG.NOTIFICATION_THRESHOLDS.unclaimed_reminder) || [];
|
|
||||||
const thresholds = rawThresholds
|
|
||||||
.map(parseThresholdString)
|
|
||||||
.filter(n => Number.isFinite(n) && n >= 0)
|
|
||||||
.map(ms => ms / (60 * 60 * 1000));
|
|
||||||
if (thresholds.length === 0) return;
|
|
||||||
|
|
||||||
const sorted = [...thresholds].sort((a, b) => a - b);
|
|
||||||
const now = Date.now();
|
|
||||||
|
|
||||||
// Bounded per-tick: oldest-first, capped at 500. A backlog larger than 500
|
|
||||||
// gets drained in subsequent 30-minute ticks rather than one long run.
|
|
||||||
const unclaimedTickets = await Ticket.find({
|
|
||||||
status: 'open',
|
|
||||||
claimedBy: null,
|
|
||||||
createdAt: { $ne: null }
|
|
||||||
}).sort({ createdAt: 1 }).limit(500).lean();
|
|
||||||
|
|
||||||
if (unclaimedTickets.length === 0) return;
|
|
||||||
|
|
||||||
const staffRecords = await StaffNotification.find({ channelId: { $ne: null } }).lean();
|
|
||||||
if (staffRecords.length === 0) return;
|
|
||||||
|
|
||||||
const guild = CONFIG.DISCORD_GUILD_ID
|
|
||||||
? client.guilds.cache.get(CONFIG.DISCORD_GUILD_ID)
|
|
||||||
: client.guilds.cache.first();
|
|
||||||
if (!guild) return;
|
|
||||||
|
|
||||||
for (const ticket of unclaimedTickets) {
|
|
||||||
const ageMs = now - new Date(ticket.createdAt).getTime();
|
|
||||||
const ageHours = ageMs / (60 * 60 * 1000);
|
|
||||||
const alreadySent = ticket.unclaimedRemindersSent || [];
|
|
||||||
|
|
||||||
// Find thresholds crossed but not yet sent
|
|
||||||
const crossedNew = sorted.filter(t => ageHours >= t && !alreadySent.includes(t));
|
|
||||||
if (crossedNew.length === 0) continue;
|
|
||||||
|
|
||||||
// Only send the highest newly-crossed threshold
|
|
||||||
const highest = crossedNew[crossedNew.length - 1];
|
|
||||||
|
|
||||||
const channelName = ticket.discordThreadId
|
|
||||||
? `<#${ticket.discordThreadId}>`
|
|
||||||
: `ticket #${ticket.ticketNumber}`;
|
|
||||||
const alertMsg = `[${highest}h+ unclaimed] ${channelName}`;
|
|
||||||
|
|
||||||
for (const rec of staffRecords) {
|
|
||||||
const chan = await guild.channels.fetch(rec.channelId).catch(() => null);
|
|
||||||
if (chan) {
|
|
||||||
await enqueueSend(chan, alertMsg).catch(e => console.error('Unclaimed notify send:', e));
|
|
||||||
increment('staff_stale_pings', rec.userId, 'today');
|
|
||||||
increment('staff_stale_pings', rec.userId, 'week');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await Ticket.updateOne(
|
|
||||||
{ gmailThreadId: ticket.gmailThreadId },
|
|
||||||
{ $addToSet: { unclaimedRemindersSent: highest } }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
notifyStaffOfReply,
|
|
||||||
notifyAllStaffUnclaimed,
|
|
||||||
startSweeps,
|
|
||||||
sweepReplyCooldowns,
|
|
||||||
_internals: { replyCooldowns, REPLY_COOLDOWN_SWEEP_TTL_MS }
|
|
||||||
};
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
/**
|
|
||||||
* Staff presence detection — checks Discord presence status for staff members.
|
|
||||||
* Requires GuildPresences intent enabled in Discord Developer Portal.
|
|
||||||
*/
|
|
||||||
const { CONFIG } = require('../config');
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get categorized availability of all configured staff members.
|
|
||||||
* @param {import('discord.js').Guild} guild
|
|
||||||
* @returns {{ online: string[], dnd: string[], offline: string[], unknown: string[] }}
|
|
||||||
*/
|
|
||||||
function getStaffAvailability(guild) {
|
|
||||||
const results = {
|
|
||||||
online: [],
|
|
||||||
dnd: [],
|
|
||||||
offline: [],
|
|
||||||
unknown: []
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const staffId of CONFIG.STAFF_IDS) {
|
|
||||||
const member = guild.members.cache.get(staffId);
|
|
||||||
if (!member) { results.offline.push(staffId); continue; }
|
|
||||||
|
|
||||||
const status = member.presence?.status;
|
|
||||||
if (!status) { results.unknown.push(staffId); continue; }
|
|
||||||
|
|
||||||
if (status === 'online' || status === 'idle') results.online.push(staffId);
|
|
||||||
else if (status === 'dnd') results.dnd.push(staffId);
|
|
||||||
else results.offline.push(staffId);
|
|
||||||
}
|
|
||||||
|
|
||||||
return results;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if any staff member is currently available.
|
|
||||||
* @param {import('discord.js').Guild} guild
|
|
||||||
* @returns {{ available: boolean|null, source: string }}
|
|
||||||
*/
|
|
||||||
function isAnyStaffAvailable(guild) {
|
|
||||||
const { online, dnd, unknown } = getStaffAvailability(guild);
|
|
||||||
if (online.length > 0) return { available: true, source: 'presence' };
|
|
||||||
if (CONFIG.STAFF_DND_COUNTS_AS_AVAILABLE && dnd.length > 0) return { available: true, source: 'presence_dnd' };
|
|
||||||
if (unknown.length === CONFIG.STAFF_IDS.length) return { available: null, source: 'unknown' };
|
|
||||||
return { available: false, source: 'presence' };
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { getStaffAvailability, isAnyStaffAvailable };
|
|
||||||
@@ -1,260 +0,0 @@
|
|||||||
/**
|
|
||||||
* Surge detection — checks for critical ticket volume/staffing conditions
|
|
||||||
* and pings ALL_STAFF_CHANNEL_ID with role mention.
|
|
||||||
*/
|
|
||||||
const { EmbedBuilder } = require('discord.js');
|
|
||||||
const { CONFIG, parseThresholdString } = require('../config');
|
|
||||||
const { mongoose } = require('../db-connection');
|
|
||||||
const { shouldFireCooldownEscalating, clearEscalating, isStaffRecentlyActive } = require('./patternStore');
|
|
||||||
const { getStaffAvailability, isAnyStaffAvailable } = require('./staffPresence');
|
|
||||||
const { enqueueSend } = require('./channelQueue');
|
|
||||||
const { assertKeysRegistered } = require('./notificationRegistry');
|
|
||||||
const { isEnabled } = require('./notificationEnabled');
|
|
||||||
|
|
||||||
// Alert keys this module drives. Asserted against the registry at load so any
|
|
||||||
// future drift (rename, typo, unregistered key) fails fast rather than
|
|
||||||
// silently breaking the settings-site config editor.
|
|
||||||
const SURGE_ALERT_KEYS = [
|
|
||||||
'surge_tickets',
|
|
||||||
'surge_game',
|
|
||||||
'surge_stale',
|
|
||||||
'surge_needs_response',
|
|
||||||
'surge_unclaimed',
|
|
||||||
'surge_tier3_unclaimed',
|
|
||||||
'surge_no_staff'
|
|
||||||
];
|
|
||||||
assertKeysRegistered('surgeChecker', SURGE_ALERT_KEYS);
|
|
||||||
|
|
||||||
const Ticket = mongoose.model('Ticket');
|
|
||||||
|
|
||||||
function getThresholdsMs(alertKey) {
|
|
||||||
const rawThresholds = (CONFIG.NOTIFICATION_THRESHOLDS && CONFIG.NOTIFICATION_THRESHOLDS[alertKey]) || [];
|
|
||||||
return rawThresholds
|
|
||||||
.map(parseThresholdString)
|
|
||||||
.filter(n => Number.isFinite(n) && n >= 0)
|
|
||||||
.sort((a, b) => a - b);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pingStaff(client, message, embedFields) {
|
|
||||||
const channelId = CONFIG.ALL_STAFF_CHANNEL_ID;
|
|
||||||
if (!channelId || !client) return;
|
|
||||||
try {
|
|
||||||
const channel = await client.channels.fetch(channelId);
|
|
||||||
if (!channel) return;
|
|
||||||
const embed = new EmbedBuilder()
|
|
||||||
.setTitle('Staff Alert')
|
|
||||||
.setDescription(message)
|
|
||||||
.setColor(0xFF4400)
|
|
||||||
.setTimestamp();
|
|
||||||
if (embedFields.length > 0) {
|
|
||||||
embed.addFields(embedFields.map(f => ({
|
|
||||||
name: f.name,
|
|
||||||
value: String(f.value).slice(0, 1024),
|
|
||||||
inline: f.inline ?? true
|
|
||||||
})));
|
|
||||||
}
|
|
||||||
const content = CONFIG.SURGE_ROLE_ID ? `<@&${CONFIG.SURGE_ROLE_ID}>` : undefined;
|
|
||||||
await enqueueSend(channel, { content, embeds: [embed] });
|
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkTicketSurge(client) {
|
|
||||||
if (!isEnabled('surge_tickets')) return;
|
|
||||||
const key = 'surge:tickets';
|
|
||||||
const since = new Date(Date.now() - CONFIG.SURGE_TICKET_WINDOW_MINUTES * 60000);
|
|
||||||
const count = await Ticket.countDocuments({ createdAt: { $gte: since } });
|
|
||||||
if (count >= CONFIG.SURGE_TICKET_COUNT) {
|
|
||||||
const thresholdMs = shouldFireCooldownEscalating(key, getThresholdsMs('surge_tickets'));
|
|
||||||
if (thresholdMs !== null) {
|
|
||||||
await pingStaff(client,
|
|
||||||
`${count} tickets created in the past ${CONFIG.SURGE_TICKET_WINDOW_MINUTES} minutes.`,
|
|
||||||
[{ name: 'Action needed', value: 'Check open tickets and claim.', inline: false }]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
clearEscalating(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkGameSurge(client) {
|
|
||||||
if (!isEnabled('surge_game')) return;
|
|
||||||
const key = 'surge:game';
|
|
||||||
const since = new Date(Date.now() - CONFIG.SURGE_GAME_TICKET_WINDOW_MINUTES * 60000);
|
|
||||||
const gameCounts = await Ticket.aggregate([
|
|
||||||
{ $match: { createdAt: { $gte: since }, game: { $ne: null } } },
|
|
||||||
{ $group: { _id: '$game', count: { $sum: 1 } } },
|
|
||||||
{ $match: { count: { $gte: CONFIG.SURGE_GAME_TICKET_COUNT } } },
|
|
||||||
{ $sort: { count: -1 } }
|
|
||||||
]);
|
|
||||||
if (gameCounts.length > 0) {
|
|
||||||
const thresholdMs = shouldFireCooldownEscalating(key, getThresholdsMs('surge_game'));
|
|
||||||
if (thresholdMs !== null) {
|
|
||||||
const fields = gameCounts.map(g => ({
|
|
||||||
name: g._id,
|
|
||||||
value: `${g.count} tickets in ${CONFIG.SURGE_GAME_TICKET_WINDOW_MINUTES} min`,
|
|
||||||
inline: true
|
|
||||||
}));
|
|
||||||
await pingStaff(client, 'Game ticket surge detected.', fields);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
clearEscalating(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkStaleSurge(client) {
|
|
||||||
if (!isEnabled('surge_stale')) return;
|
|
||||||
const key = 'surge:stale';
|
|
||||||
const cutoff = new Date(Date.now() - CONFIG.SURGE_STALE_HOURS * 3600000);
|
|
||||||
const count = await Ticket.countDocuments({
|
|
||||||
status: 'open',
|
|
||||||
lastActivity: { $lte: cutoff, $ne: null }
|
|
||||||
});
|
|
||||||
if (count >= CONFIG.SURGE_STALE_COUNT) {
|
|
||||||
const thresholdMs = shouldFireCooldownEscalating(key, getThresholdsMs('surge_stale'));
|
|
||||||
if (thresholdMs !== null) {
|
|
||||||
await pingStaff(client,
|
|
||||||
`${count} tickets have had no activity in the past ${CONFIG.SURGE_STALE_HOURS} hours.`,
|
|
||||||
[{ name: 'Action needed', value: 'Review and respond to stale tickets.', inline: false }]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
clearEscalating(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkNeedsResponseSurge(client) {
|
|
||||||
if (!isEnabled('surge_needs_response')) return;
|
|
||||||
const key = 'surge:needs_response';
|
|
||||||
const cutoff = new Date(Date.now() - CONFIG.SURGE_NEEDS_RESPONSE_HOURS * 3600000);
|
|
||||||
const count = await Ticket.countDocuments({
|
|
||||||
status: 'open',
|
|
||||||
lastMessageAuthorIsStaff: false,
|
|
||||||
lastActivity: { $lte: cutoff, $ne: null }
|
|
||||||
});
|
|
||||||
if (count >= CONFIG.SURGE_NEEDS_RESPONSE_COUNT) {
|
|
||||||
const thresholdMs = shouldFireCooldownEscalating(key, getThresholdsMs('surge_needs_response'));
|
|
||||||
if (thresholdMs !== null) {
|
|
||||||
await pingStaff(client,
|
|
||||||
`${count} tickets are waiting on a staff response for over ${CONFIG.SURGE_NEEDS_RESPONSE_HOURS} hour(s).`,
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
clearEscalating(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkUnclaimedSurge(client) {
|
|
||||||
if (!isEnabled('surge_unclaimed')) return;
|
|
||||||
const key = 'surge:unclaimed';
|
|
||||||
const cutoff = new Date(Date.now() - CONFIG.SURGE_UNCLAIMED_MINUTES * 60000);
|
|
||||||
const count = await Ticket.countDocuments({
|
|
||||||
status: 'open',
|
|
||||||
claimedBy: null,
|
|
||||||
createdAt: { $lte: cutoff, $ne: null }
|
|
||||||
});
|
|
||||||
if (count >= CONFIG.SURGE_UNCLAIMED_COUNT) {
|
|
||||||
const thresholdMs = shouldFireCooldownEscalating(key, getThresholdsMs('surge_unclaimed'));
|
|
||||||
if (thresholdMs !== null) {
|
|
||||||
await pingStaff(client,
|
|
||||||
`${count} tickets have been unclaimed for over ${CONFIG.SURGE_UNCLAIMED_MINUTES} minutes.`,
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
clearEscalating(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkTier3UnclaimedSurge(client) {
|
|
||||||
if (!isEnabled('surge_tier3_unclaimed')) return;
|
|
||||||
const key = 'surge:tier3_unclaimed';
|
|
||||||
const cutoff = new Date(Date.now() - CONFIG.SURGE_TIER3_UNCLAIMED_MINUTES * 60000);
|
|
||||||
const tickets = await Ticket.find({
|
|
||||||
status: 'open',
|
|
||||||
escalationTier: 2,
|
|
||||||
claimedBy: null,
|
|
||||||
createdAt: { $lte: cutoff, $ne: null }
|
|
||||||
}).lean();
|
|
||||||
if (tickets.length > 0) {
|
|
||||||
const thresholdMs = shouldFireCooldownEscalating(key, getThresholdsMs('surge_tier3_unclaimed'));
|
|
||||||
if (thresholdMs !== null) {
|
|
||||||
await pingStaff(client,
|
|
||||||
`${tickets.length} Tier 3 ticket(s) unclaimed for over ${CONFIG.SURGE_TIER3_UNCLAIMED_MINUTES} minutes.`,
|
|
||||||
tickets.map(t => ({ name: t.subject || 'No subject', value: `<#${t.discordThreadId}>`, inline: true }))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
clearEscalating(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkZeroStaffSurge(client) {
|
|
||||||
if (!isEnabled('surge_no_staff')) return;
|
|
||||||
const key = 'surge:no_staff';
|
|
||||||
if (!CONFIG.STAFF_IDS.length) {
|
|
||||||
clearEscalating(key);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const openCount = await Ticket.countDocuments({ status: 'open' });
|
|
||||||
if (openCount < CONFIG.SURGE_NO_STAFF_OPEN_TICKET_THRESHOLD) {
|
|
||||||
clearEscalating(key);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const guild = client.guilds.cache.get(CONFIG.DISCORD_GUILD_ID);
|
|
||||||
if (!guild) {
|
|
||||||
clearEscalating(key);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { available, source } = isAnyStaffAvailable(guild);
|
|
||||||
|
|
||||||
let noStaff = false;
|
|
||||||
let detailLine = '';
|
|
||||||
const { online, dnd, offline } = getStaffAvailability(guild);
|
|
||||||
|
|
||||||
if (source === 'unknown') {
|
|
||||||
const recentlyActive = CONFIG.STAFF_IDS.filter(id => isStaffRecentlyActive(id, 60));
|
|
||||||
if (recentlyActive.length === 0) {
|
|
||||||
noStaff = true;
|
|
||||||
detailLine = 'No staff active in the last 60 minutes (presence intent unavailable, using message activity fallback).';
|
|
||||||
}
|
|
||||||
} else if (!available) {
|
|
||||||
noStaff = true;
|
|
||||||
const dndNote = dnd.length > 0 ? ` (${dnd.length} on DND)` : '';
|
|
||||||
detailLine = `${offline.length} staff offline/invisible${dndNote}. ${online.length} online.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!noStaff) {
|
|
||||||
clearEscalating(key);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const thresholdMs = shouldFireCooldownEscalating(key, getThresholdsMs('surge_no_staff'));
|
|
||||||
if (thresholdMs === null) return;
|
|
||||||
|
|
||||||
const fields = [
|
|
||||||
{ name: 'Open tickets', value: String(openCount), inline: true },
|
|
||||||
{ name: 'Detection method', value: source === 'unknown' ? 'Message activity' : 'Presence', inline: true },
|
|
||||||
{ name: source === 'unknown' ? 'Note' : 'Staff status', value: detailLine, inline: false }
|
|
||||||
];
|
|
||||||
|
|
||||||
await pingStaff(client,
|
|
||||||
`${openCount} open ticket(s) with no staff available to respond.`,
|
|
||||||
fields
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function runSurgeChecks(client) {
|
|
||||||
try { await checkTicketSurge(client); } catch (e) { console.error('checkTicketSurge:', e); }
|
|
||||||
try { await checkGameSurge(client); } catch (e) { console.error('checkGameSurge:', e); }
|
|
||||||
try { await checkStaleSurge(client); } catch (e) { console.error('checkStaleSurge:', e); }
|
|
||||||
try { await checkNeedsResponseSurge(client); } catch (e) { console.error('checkNeedsResponseSurge:', e); }
|
|
||||||
try { await checkUnclaimedSurge(client); } catch (e) { console.error('checkUnclaimedSurge:', e); }
|
|
||||||
try { await checkTier3UnclaimedSurge(client); } catch (e) { console.error('checkTier3UnclaimedSurge:', e); }
|
|
||||||
try { await checkZeroStaffSurge(client); } catch (e) { console.error('checkZeroStaffSurge:', e); }
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { runSurgeChecks };
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,484 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
||||||
<title>Broccolini Settings</title>
|
|
||||||
<link rel="stylesheet" href="/css/main.css">
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div id="loading" class="loading"><div class="spinner"></div></div>
|
|
||||||
<div id="toast-container"></div>
|
|
||||||
|
|
||||||
<!-- Sidebar -->
|
|
||||||
<div class="sidebar-backdrop" id="sidebar-backdrop" aria-hidden="true"></div>
|
|
||||||
<nav class="sidebar" id="sidebar">
|
|
||||||
<div class="logo">Broccolini Settings</div>
|
|
||||||
<a href="/" class="active">Core</a>
|
|
||||||
<a href="/channels">Channels</a>
|
|
||||||
<a href="/categories">Categories</a>
|
|
||||||
<a href="/gmail">Gmail</a>
|
|
||||||
<a href="/behavior">Ticket Behavior</a>
|
|
||||||
<a href="/threads">Staff Threads</a>
|
|
||||||
<a href="/pins">Pin Messages</a>
|
|
||||||
<a href="/notifications">Notifications</a>
|
|
||||||
<a href="/logging">Logging</a>
|
|
||||||
<a href="/automation">Automation</a>
|
|
||||||
<a href="/appearance">Appearance</a>
|
|
||||||
<a href="/staff">Staff</a>
|
|
||||||
<a href="/advanced">Advanced</a>
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<!-- Top bar -->
|
|
||||||
<div class="topbar">
|
|
||||||
<button type="button" class="menu-toggle" id="menu-toggle" aria-label="Toggle navigation" aria-expanded="false" aria-controls="sidebar">
|
|
||||||
<span class="menu-toggle-bars" aria-hidden="true"></span>
|
|
||||||
</button>
|
|
||||||
<h1>Settings</h1>
|
|
||||||
<div class="status">
|
|
||||||
<span class="dot" id="bot-status-dot"></span>
|
|
||||||
<span id="bot-status-text">Checking...</span>
|
|
||||||
</div>
|
|
||||||
<div class="actions">
|
|
||||||
<button type="button" id="logout-btn">Logout</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Main content -->
|
|
||||||
<div class="main">
|
|
||||||
|
|
||||||
<!-- 1. Core -->
|
|
||||||
<div class="section" id="s-core">
|
|
||||||
<div class="section-header"><h2>Core</h2><p>Discord bot credentials and guild</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body"><div class="field-grid">
|
|
||||||
<div class="field"><label>Discord Token</label><input type="password" data-key="DISCORD_TOKEN" placeholder="Bot token"></div>
|
|
||||||
<div class="field"><label>Application ID</label><input type="text" data-key="DISCORD_APPLICATION_ID"></div>
|
|
||||||
<div class="field"><label>Guild ID</label><input type="text" data-key="DISCORD_GUILD_ID"></div>
|
|
||||||
</div></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 2. Channels -->
|
|
||||||
<div class="section" id="s-channels">
|
|
||||||
<div class="section-header"><h2>Channels</h2><p>Channel assignments for logging, transcripts, and alerts</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body"><div class="field-grid">
|
|
||||||
<div class="field"><label>Transcript Channel</label><input type="text" data-key="TRANSCRIPT_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Logging Channel</label><input type="text" data-key="LOGGING_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Debugging Channel</label><input type="text" data-key="DEBUGGING_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Backup/Export Channel</label><input type="text" data-key="BACKUP_EXPORT_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Account Info Channel</label><input type="text" data-key="ACCOUNT_INFO_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Gmail Log Channel</label><input type="text" data-key="GMAIL_LOG_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Automation Log Channel</label><input type="text" data-key="AUTOMATION_LOG_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Rename Log Channel</label><input type="text" data-key="RENAME_LOG_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Security Log Channel</label><input type="text" data-key="SECURITY_LOG_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>System Log Channel</label><input type="text" data-key="SYSTEM_LOG_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>All Staff Channel</label><input type="text" data-key="ALL_STAFF_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Chat Alert Channel</label><input type="text" data-key="ALL_STAFF_CHAT_ALERT_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>User Patterns Channel</label><input type="text" data-key="USER_PATTERNS_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Game Patterns Channel</label><input type="text" data-key="GAME_PATTERNS_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Tag Patterns Channel</label><input type="text" data-key="TAG_PATTERNS_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Escalation Patterns Channel</label><input type="text" data-key="ESCALATION_PATTERNS_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Staff Patterns Channel</label><input type="text" data-key="STAFF_PATTERNS_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Combined Patterns Channel</label><input type="text" data-key="COMBINED_PATTERNS_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
</div></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 3. Categories -->
|
|
||||||
<div class="section" id="s-categories">
|
|
||||||
<div class="section-header"><h2>Categories</h2><p>Ticket category assignments and escalation targets</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body"><div class="field-grid">
|
|
||||||
<div class="field"><label>Email Ticket Category</label><input type="text" data-key="TICKET_CATEGORY_ID" data-smart="category"></div>
|
|
||||||
<div class="field"><label>Discord Ticket Category</label><input type="text" data-key="DISCORD_TICKET_CATEGORY_ID" data-smart="category"></div>
|
|
||||||
<div class="field"><label>Email T2 Category</label><input type="text" data-key="EMAIL_ESCALATED2_CHANNEL_ID" data-smart="category"></div>
|
|
||||||
<div class="field"><label>Discord T2 Category</label><input type="text" data-key="DISCORD_ESCALATED2_CHANNEL_ID" data-smart="category"></div>
|
|
||||||
<div class="field"><label>Email T3 Category</label><input type="text" data-key="EMAIL_ESCALATED3_CHANNEL_ID" data-smart="category"></div>
|
|
||||||
<div class="field"><label>Discord T3 Category</label><input type="text" data-key="DISCORD_ESCALATED3_CHANNEL_ID" data-smart="category"></div>
|
|
||||||
<div class="field"><label>Staff Notification Category</label><input type="text" data-key="STAFF_NOTIFICATION_CATEGORY_ID" data-smart="category"></div>
|
|
||||||
<div class="field"><label>Category Name</label><input type="text" data-key="TICKET_CATEGORY_NAME"></div>
|
|
||||||
<div class="field"><label>T2 Category Name</label><input type="text" data-key="TICKET_T2_CATEGORY_NAME"></div>
|
|
||||||
<div class="field"><label>T3 Category Name</label><input type="text" data-key="TICKET_T3_CATEGORY_NAME"></div>
|
|
||||||
<div class="field"><label>Discord Thread Channel</label><input type="text" data-key="DISCORD_THREAD_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
<div class="field"><label>Email Thread Channel</label><input type="text" data-key="EMAIL_THREAD_CHANNEL_ID" data-smart="channel"></div>
|
|
||||||
</div></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 4. Gmail -->
|
|
||||||
<div class="section" id="s-gmail">
|
|
||||||
<div class="section-header"><h2>Gmail</h2><p>Google OAuth credentials and email settings</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body"><div class="field-grid">
|
|
||||||
<div class="field"><label>Google Client ID</label><input type="text" data-key="GOOGLE_CLIENT_ID"></div>
|
|
||||||
<div class="field"><label>Google Client Secret</label><input type="password" data-key="GOOGLE_CLIENT_SECRET"></div>
|
|
||||||
<div class="field"><label>Refresh Token</label><input type="password" data-key="REFRESH_TOKEN"></div>
|
|
||||||
<div class="field"><label>Support Email</label><input type="email" data-key="MY_EMAIL"></div>
|
|
||||||
</div></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 5. Ticket Behavior -->
|
|
||||||
<div class="section" id="s-behavior">
|
|
||||||
<div class="section-header"><h2>Ticket Behavior</h2><p>Automation, limits, and messages</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body"><div class="field-grid">
|
|
||||||
<div class="field"><label>Auto-Close</label><div class="toggle-wrap"><label class="toggle"><input type="checkbox" data-key="AUTO_CLOSE_ENABLED"><span class="slider"></span></label><span>Enabled</span></div></div>
|
|
||||||
<div class="field"><label>Auto-Close Hours</label><input type="number" data-key="AUTO_CLOSE_AFTER_HOURS"></div>
|
|
||||||
<div class="field"><label>Reminders</label><div class="toggle-wrap"><label class="toggle"><input type="checkbox" data-key="REMINDER_ENABLED"><span class="slider"></span></label><span>Enabled</span></div></div>
|
|
||||||
<div class="field"><label>Reminder Hours</label><input type="number" data-key="REMINDER_AFTER_HOURS"></div>
|
|
||||||
<div class="field"><label>Priority System</label><div class="toggle-wrap"><label class="toggle"><input type="checkbox" data-key="PRIORITY_ENABLED"><span class="slider"></span></label><span>Enabled</span></div></div>
|
|
||||||
<div class="field"><label>Claim Timeout</label><div class="toggle-wrap"><label class="toggle"><input type="checkbox" data-key="CLAIM_TIMEOUT_ENABLED"><span class="slider"></span></label><span>Enabled</span></div></div>
|
|
||||||
<div class="field"><label>Claim Timeout Hours</label><input type="number" data-key="CLAIM_TIMEOUT_HOURS"></div>
|
|
||||||
<div class="field"><label>Auto-Unclaim</label><div class="toggle-wrap"><label class="toggle"><input type="checkbox" data-key="AUTO_UNCLAIM_ENABLED"><span class="slider"></span></label><span>Enabled</span></div></div>
|
|
||||||
<div class="field"><label>Auto-Unclaim Hours</label><input type="number" data-key="AUTO_UNCLAIM_AFTER_HOURS"></div>
|
|
||||||
<div class="field"><label>Allow Claim Overwrite</label><div class="toggle-wrap"><label class="toggle"><input type="checkbox" data-key="ALLOW_CLAIM_OVERWRITE"><span class="slider"></span></label><span>Enabled</span></div></div>
|
|
||||||
<div class="field"><label>Global Ticket Limit</label><input type="number" data-key="GLOBAL_TICKET_LIMIT"></div>
|
|
||||||
<div class="field"><label>Rate Limit (per user)</label><input type="number" data-key="RATE_LIMIT_TICKETS_PER_USER"></div>
|
|
||||||
<div class="field"><label>Rate Limit Window (min)</label><input type="number" data-key="RATE_LIMIT_WINDOW_MINUTES"></div>
|
|
||||||
<div class="field"><label>Role to Ping</label><input type="text" data-key="ROLE_ID_TO_PING" data-smart="role"></div>
|
|
||||||
<div class="field full-width"><label>Welcome Message</label><textarea data-key="TICKET_WELCOME_MESSAGE" rows="3"></textarea></div>
|
|
||||||
<div class="field full-width"><label>Claimed Message</label><textarea data-key="TICKET_CLAIMED_MESSAGE" rows="2"></textarea><div class="hint">Variables: {staff_mention}, {staff_name}</div></div>
|
|
||||||
<div class="field full-width"><label>Unclaimed Message</label><textarea data-key="TICKET_UNCLAIMED_MESSAGE" rows="2"></textarea></div>
|
|
||||||
<div class="field full-width"><label>Escalation Message</label><textarea data-key="ESCALATION_MESSAGE" rows="3"></textarea><div class="hint">Variables: {support_name}</div></div>
|
|
||||||
<div class="field full-width"><label>Reminder Message</label><textarea data-key="REMINDER_MESSAGE" rows="2"></textarea><div class="hint">Variables: {ping}, {hours}</div></div>
|
|
||||||
</div></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 6. Staff Threads -->
|
|
||||||
<div class="section" id="s-threads">
|
|
||||||
<div class="section-header"><h2>Staff Threads</h2><p>Private staff discussion threads on ticket channels</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body"><div class="field-grid">
|
|
||||||
<div class="field"><label>Enabled</label><div class="toggle-wrap"><label class="toggle"><input type="checkbox" data-key="STAFF_THREAD_ENABLED"><span class="slider"></span></label><span>Enabled</span></div></div>
|
|
||||||
<div class="field"><label>Thread Name</label><input type="text" data-key="STAFF_THREAD_NAME"></div>
|
|
||||||
<div class="field"><label>Auto-Add Role</label><div class="toggle-wrap"><label class="toggle"><input type="checkbox" data-key="STAFF_THREAD_AUTO_ADD_ROLE"><span class="slider"></span></label><span>Enabled</span></div></div>
|
|
||||||
<div class="field"><label>Staff Thread Role</label><input type="text" data-key="STAFF_THREAD_ROLE_ID" data-smart="role"></div>
|
|
||||||
</div></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 7. Pin Messages -->
|
|
||||||
<div class="section" id="s-pins">
|
|
||||||
<div class="section-header"><h2>Pin Messages</h2><p>Auto-pin welcome and escalation messages</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body"><div class="field-grid">
|
|
||||||
<div class="field"><label>Pin Initial Message</label><div class="toggle-wrap"><label class="toggle"><input type="checkbox" data-key="PIN_INITIAL_MESSAGE_ENABLED"><span class="slider"></span></label><span>Enabled</span></div></div>
|
|
||||||
<div class="field"><label>Pin Escalation Message</label><div class="toggle-wrap"><label class="toggle"><input type="checkbox" data-key="PIN_ESCALATION_MESSAGE_ENABLED"><span class="slider"></span></label><span>Enabled</span></div></div>
|
|
||||||
<div class="field"><label>Suppress Pin Notice</label><div class="toggle-wrap"><label class="toggle"><input type="checkbox" data-key="PIN_SUPPRESS_SYSTEM_MESSAGE"><span class="slider"></span></label><span>Enabled</span></div></div>
|
|
||||||
</div></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 8. Notifications -->
|
|
||||||
<div class="section" id="s-notifications">
|
|
||||||
<div class="section-header"><h2>Notifications</h2><p>Threshold milestones and trigger conditions by alert category</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body">
|
|
||||||
<input type="hidden" data-key="NOTIFICATION_THRESHOLDS_JSON">
|
|
||||||
|
|
||||||
<div class="notif-tabs" role="tablist" aria-label="Notification categories">
|
|
||||||
<button type="button" class="notif-tab-btn active" data-notif-tab="surge">Surge</button>
|
|
||||||
<button type="button" class="notif-tab-btn" data-notif-tab="patterns">Patterns</button>
|
|
||||||
<button type="button" class="notif-tab-btn" data-notif-tab="unclaimed">Unclaimed</button>
|
|
||||||
<button type="button" class="notif-tab-btn" data-notif-tab="chat">Chat</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="notif-panel" data-notif-panel="surge">
|
|
||||||
<div class="notif-toggle-row">
|
|
||||||
<div class="notif-toggle-group">
|
|
||||||
<label class="toggle">
|
|
||||||
<input type="checkbox" data-notif-master>
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
<span class="notif-toggle-label">Master (all categories)</span>
|
|
||||||
</div>
|
|
||||||
<div class="notif-toggle-group">
|
|
||||||
<label class="toggle">
|
|
||||||
<input type="checkbox" data-notif-category-toggle="surge">
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
<span class="notif-toggle-label">All in category</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<p class="hint">Surge alerts fire when active ticket conditions cross thresholds — high volume, unclaimed queues, no staff online. Each alert escalates through its threshold list, spacing out pings as the condition persists. The counter resets when the condition clears.</p>
|
|
||||||
<div class="notif-editor">
|
|
||||||
<div class="field"><label>Alert key</label><select class="notif-alert-select" data-notif-category="surge"></select></div>
|
|
||||||
<div class="hint notif-alert-description" data-notif-description="surge"></div>
|
|
||||||
<div class="notif-per-alert-row">
|
|
||||||
<label class="toggle">
|
|
||||||
<input type="checkbox" data-notif-alert>
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
<span class="notif-toggle-label" data-notif-alert-label>Alert disabled</span>
|
|
||||||
</div>
|
|
||||||
<div class="notif-chips" data-notif-chips="surge"></div>
|
|
||||||
<div class="notif-input-row">
|
|
||||||
<input type="text" class="notif-threshold-input" data-notif-input="surge" placeholder="15m, 1h, 1d6h, 2d6h, 5">
|
|
||||||
<button type="button" class="notif-add-btn" data-notif-add="surge">Add</button>
|
|
||||||
</div>
|
|
||||||
<div class="notif-presets" data-notif-presets="surge"></div>
|
|
||||||
</div>
|
|
||||||
<details class="notif-trigger">
|
|
||||||
<summary>Trigger conditions</summary>
|
|
||||||
<div class="field-grid">
|
|
||||||
<div class="field"><label>Surge Role</label><input type="text" data-key="SURGE_ROLE_ID" data-smart="role"></div>
|
|
||||||
<div class="field"><label>Ticket Surge Count</label><input type="number" data-key="SURGE_TICKET_COUNT"></div>
|
|
||||||
<div class="field"><label>Ticket Window (min)</label><input type="number" data-key="SURGE_TICKET_WINDOW_MINUTES"></div>
|
|
||||||
<div class="field"><label>Game Surge Count</label><input type="number" data-key="SURGE_GAME_TICKET_COUNT"></div>
|
|
||||||
<div class="field"><label>Game Window (min)</label><input type="number" data-key="SURGE_GAME_TICKET_WINDOW_MINUTES"></div>
|
|
||||||
<div class="field"><label>Stale Count</label><input type="number" data-key="SURGE_STALE_COUNT"></div>
|
|
||||||
<div class="field"><label>Stale Hours</label><input type="number" data-key="SURGE_STALE_HOURS"></div>
|
|
||||||
<div class="field"><label>Needs Response Count</label><input type="number" data-key="SURGE_NEEDS_RESPONSE_COUNT"></div>
|
|
||||||
<div class="field"><label>Needs Response Hours</label><input type="number" data-key="SURGE_NEEDS_RESPONSE_HOURS"></div>
|
|
||||||
<div class="field"><label>Unclaimed Count</label><input type="number" data-key="SURGE_UNCLAIMED_COUNT"></div>
|
|
||||||
<div class="field"><label>Unclaimed Minutes</label><input type="number" data-key="SURGE_UNCLAIMED_MINUTES"></div>
|
|
||||||
<div class="field"><label>Tier 3 Unclaimed (min)</label><input type="number" data-key="SURGE_TIER3_UNCLAIMED_MINUTES"></div>
|
|
||||||
<div class="field"><label>Cooldown (min)</label><input type="number" data-key="SURGE_COOLDOWN_MINUTES"></div>
|
|
||||||
<div class="field"><label>DND = Available</label><div class="toggle-wrap"><label class="toggle"><input type="checkbox" data-key="STAFF_DND_COUNTS_AS_AVAILABLE"><span class="slider"></span></label><span>Enabled</span></div></div>
|
|
||||||
<div class="field"><label>No-Staff Cooldown (min)</label><input type="number" data-key="SURGE_NO_STAFF_COOLDOWN_MINUTES"></div>
|
|
||||||
<div class="field"><label>No-Staff Ticket Threshold</label><input type="number" data-key="SURGE_NO_STAFF_OPEN_TICKET_THRESHOLD"></div>
|
|
||||||
</div>
|
|
||||||
</details>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="notif-panel hidden" data-notif-panel="patterns">
|
|
||||||
<div class="notif-toggle-row">
|
|
||||||
<div class="notif-toggle-group">
|
|
||||||
<label class="toggle">
|
|
||||||
<input type="checkbox" data-notif-master>
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
<span class="notif-toggle-label">Master (all categories)</span>
|
|
||||||
</div>
|
|
||||||
<div class="notif-toggle-group">
|
|
||||||
<label class="toggle">
|
|
||||||
<input type="checkbox" data-notif-category-toggle="patterns">
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
<span class="notif-toggle-label">All in category</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<p class="hint">Pattern alerts detect trends over time — surges by game, escalation rates, staff behavior. Each alert fires once per threshold crossed within its window (daily/weekly/monthly) and won't repeat until the next window resets.</p>
|
|
||||||
<div class="notif-editor">
|
|
||||||
<div class="field"><label>Alert key</label><select class="notif-alert-select" data-notif-category="patterns"></select></div>
|
|
||||||
<div class="hint notif-alert-description" data-notif-description="patterns"></div>
|
|
||||||
<div class="notif-per-alert-row">
|
|
||||||
<label class="toggle">
|
|
||||||
<input type="checkbox" data-notif-alert>
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
<span class="notif-toggle-label" data-notif-alert-label>Alert disabled</span>
|
|
||||||
</div>
|
|
||||||
<div class="notif-chips" data-notif-chips="patterns"></div>
|
|
||||||
<div class="notif-input-row">
|
|
||||||
<input type="text" class="notif-threshold-input" data-notif-input="patterns" placeholder="15m, 1h, 1d6h, 2d6h, 5">
|
|
||||||
<button type="button" class="notif-add-btn" data-notif-add="patterns">Add</button>
|
|
||||||
</div>
|
|
||||||
<div class="notif-presets" data-notif-presets="patterns"></div>
|
|
||||||
</div>
|
|
||||||
<details class="notif-trigger">
|
|
||||||
<summary>Trigger conditions</summary>
|
|
||||||
<div class="field-grid">
|
|
||||||
<div class="field"><label>Check Interval (min)</label><input type="number" data-key="PATTERN_CHECK_INTERVAL_MINUTES"></div>
|
|
||||||
<div class="field"><label>User Ticket Threshold</label><input type="number" data-key="PATTERN_USER_TICKET_THRESHOLD"></div>
|
|
||||||
<div class="field"><label>Game Ticket Threshold</label><input type="number" data-key="PATTERN_GAME_TICKET_THRESHOLD"></div>
|
|
||||||
<div class="field"><label>Staff Stale Ping Threshold</label><input type="number" data-key="PATTERN_STAFF_STALE_PING_THRESHOLD"></div>
|
|
||||||
<div class="field"><label>Escalation Threshold</label><input type="number" data-key="PATTERN_ESCALATION_THRESHOLD"></div>
|
|
||||||
<div class="field"><label>Rapid Close Seconds</label><input type="number" data-key="PATTERN_RAPID_CLOSE_SECONDS"></div>
|
|
||||||
<div class="field"><label>Unclaimed Hours</label><input type="number" data-key="PATTERN_UNCLAIMED_HOURS"></div>
|
|
||||||
</div>
|
|
||||||
</details>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="notif-panel hidden" data-notif-panel="unclaimed">
|
|
||||||
<div class="notif-toggle-row">
|
|
||||||
<div class="notif-toggle-group">
|
|
||||||
<label class="toggle">
|
|
||||||
<input type="checkbox" data-notif-master>
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
<span class="notif-toggle-label">Master (all categories)</span>
|
|
||||||
</div>
|
|
||||||
<div class="notif-toggle-group">
|
|
||||||
<label class="toggle">
|
|
||||||
<input type="checkbox" data-notif-category-toggle="unclaimed">
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
<span class="notif-toggle-label">All in category</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<p class="hint">Per-ticket reminders sent to staff notification channels when a ticket remains unclaimed. Each threshold fires once per ticket. Escalating a ticket resets the threshold list so reminders restart for the new tier.</p>
|
|
||||||
<div class="notif-editor">
|
|
||||||
<div class="field"><label>Alert key</label><select class="notif-alert-select" data-notif-category="unclaimed"></select></div>
|
|
||||||
<div class="hint notif-alert-description" data-notif-description="unclaimed"></div>
|
|
||||||
<div class="notif-per-alert-row">
|
|
||||||
<label class="toggle">
|
|
||||||
<input type="checkbox" data-notif-alert>
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
<span class="notif-toggle-label" data-notif-alert-label>Alert disabled</span>
|
|
||||||
</div>
|
|
||||||
<div class="notif-chips" data-notif-chips="unclaimed"></div>
|
|
||||||
<div class="notif-input-row">
|
|
||||||
<input type="text" class="notif-threshold-input" data-notif-input="unclaimed" placeholder="15m, 1h, 1d6h, 2d6h, 5">
|
|
||||||
<button type="button" class="notif-add-btn" data-notif-add="unclaimed">Add</button>
|
|
||||||
</div>
|
|
||||||
<div class="notif-presets" data-notif-presets="unclaimed"></div>
|
|
||||||
</div>
|
|
||||||
<details class="notif-trigger">
|
|
||||||
<summary>Trigger conditions</summary>
|
|
||||||
<div class="field-grid">
|
|
||||||
<div class="field full-width"><p class="hint">Unclaimed notifications use threshold milestones only.</p></div>
|
|
||||||
</div>
|
|
||||||
</details>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="notif-panel hidden" data-notif-panel="chat">
|
|
||||||
<div class="notif-toggle-row">
|
|
||||||
<div class="notif-toggle-group">
|
|
||||||
<label class="toggle">
|
|
||||||
<input type="checkbox" data-notif-master>
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
<span class="notif-toggle-label">Master (all categories)</span>
|
|
||||||
</div>
|
|
||||||
<div class="notif-toggle-group">
|
|
||||||
<label class="toggle">
|
|
||||||
<input type="checkbox" data-notif-category-toggle="chat">
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
<span class="notif-toggle-label">All in category</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<p class="hint">Monitors configured chat channels for unresponded user messages. Fires at escalating intervals while the condition persists. Resets when a staff member responds.</p>
|
|
||||||
<div class="notif-editor">
|
|
||||||
<div class="field"><label>Alert key</label><select class="notif-alert-select" data-notif-category="chat"></select></div>
|
|
||||||
<div class="hint notif-alert-description" data-notif-description="chat"></div>
|
|
||||||
<div class="notif-per-alert-row">
|
|
||||||
<label class="toggle">
|
|
||||||
<input type="checkbox" data-notif-alert>
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
<span class="notif-toggle-label" data-notif-alert-label>Alert disabled</span>
|
|
||||||
</div>
|
|
||||||
<div class="notif-chips" data-notif-chips="chat"></div>
|
|
||||||
<div class="notif-input-row">
|
|
||||||
<input type="text" class="notif-threshold-input" data-notif-input="chat" placeholder="15m, 1h, 1d6h, 2d6h, 5">
|
|
||||||
<button type="button" class="notif-add-btn" data-notif-add="chat">Add</button>
|
|
||||||
</div>
|
|
||||||
<div class="notif-presets" data-notif-presets="chat"></div>
|
|
||||||
</div>
|
|
||||||
<details class="notif-trigger">
|
|
||||||
<summary>Trigger conditions</summary>
|
|
||||||
<div class="field-grid">
|
|
||||||
<div class="field"><label>Chat Alert Message Count</label><input type="number" data-key="CHAT_ALERT_MESSAGE_COUNT"></div>
|
|
||||||
<div class="field"><label>Chat No-Response Hours</label><input type="number" data-key="CHAT_ALERT_HOURS_WITHOUT_RESPONSE"></div>
|
|
||||||
<div class="field"><label>Chat Alert Cooldown (min)</label><input type="number" data-key="CHAT_ALERT_COOLDOWN_MINUTES"></div>
|
|
||||||
</div>
|
|
||||||
</details>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 10. Logging -->
|
|
||||||
<div class="section" id="s-logging">
|
|
||||||
<div class="section-header"><h2>Logging</h2><p>Log channel configuration (channels set in Channels section)</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body"><div class="field-grid">
|
|
||||||
<div class="field full-width"><p class="logging-hint">Log channels are configured in the <a href="/channels">Channels</a> section. This section shows which logs are active based on configured channels.</p></div>
|
|
||||||
</div></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 11. Automation -->
|
|
||||||
<div class="section" id="s-automation">
|
|
||||||
<div class="section-header"><h2>Automation</h2><p>Polling intervals and timer durations</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body"><div class="field-grid">
|
|
||||||
<div class="field"><label>Gmail Poll Interval (sec)</label><select data-key="GMAIL_POLL_INTERVAL_SECONDS">
|
|
||||||
<option value="5">5s</option><option value="10">10s</option><option value="30">30s</option><option value="45">45s</option>
|
|
||||||
<option value="60">1m</option><option value="120">2m</option><option value="180">3m</option><option value="240">4m</option>
|
|
||||||
<option value="300">5m</option><option value="600">10m</option>
|
|
||||||
</select></div>
|
|
||||||
<div class="field"><label>Force-Close Timer (sec)</label><select data-key="FORCE_CLOSE_TIMER_SECONDS">
|
|
||||||
<option value="5">5s</option><option value="10">10s</option><option value="30">30s</option><option value="45">45s</option>
|
|
||||||
<option value="60">1m</option><option value="120">2m</option><option value="180">3m</option><option value="240">4m</option>
|
|
||||||
<option value="300">5m</option><option value="600">10m</option>
|
|
||||||
</select></div>
|
|
||||||
</div></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 12. Appearance -->
|
|
||||||
<div class="section" id="s-appearance">
|
|
||||||
<div class="section-header"><h2>Appearance</h2><p>Embed colors, button labels, and emojis</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body"><div class="field-grid">
|
|
||||||
<div class="field"><label>Open Color</label><div class="color-field"><input type="color" data-key="EMBED_COLOR_OPEN"><span>Open tickets</span></div></div>
|
|
||||||
<div class="field"><label>Closed Color</label><div class="color-field"><input type="color" data-key="EMBED_COLOR_CLOSED"><span>Closed tickets</span></div></div>
|
|
||||||
<div class="field"><label>Claimed Color</label><div class="color-field"><input type="color" data-key="EMBED_COLOR_CLAIMED"><span>Claimed tickets</span></div></div>
|
|
||||||
<div class="field"><label>Escalated Color</label><div class="color-field"><input type="color" data-key="EMBED_COLOR_ESCALATED"><span>Escalated tickets</span></div></div>
|
|
||||||
<div class="field"><label>Info Color</label><div class="color-field"><input type="color" data-key="EMBED_COLOR_INFO"><span>Info embeds</span></div></div>
|
|
||||||
<div class="field"><label>Close Button Label</label><input type="text" data-key="BUTTON_LABEL_CLOSE"></div>
|
|
||||||
<div class="field"><label>Claim Button Label</label><input type="text" data-key="BUTTON_LABEL_CLAIM"></div>
|
|
||||||
<div class="field"><label>Unclaim Button Label</label><input type="text" data-key="BUTTON_LABEL_UNCLAIM"></div>
|
|
||||||
<div class="field"><label>Close Emoji</label><input type="text" data-key="BUTTON_EMOJI_CLOSE"></div>
|
|
||||||
<div class="field"><label>Claim Emoji</label><input type="text" data-key="BUTTON_EMOJI_CLAIM"></div>
|
|
||||||
<div class="field"><label>Unclaim Emoji</label><input type="text" data-key="BUTTON_EMOJI_UNCLAIM"></div>
|
|
||||||
<div class="field"><label>High Priority Emoji</label><input type="text" data-key="PRIORITY_HIGH_EMOJI"></div>
|
|
||||||
<div class="field"><label>Medium Priority Emoji</label><input type="text" data-key="PRIORITY_MEDIUM_EMOJI"></div>
|
|
||||||
<div class="field"><label>Low Priority Emoji</label><input type="text" data-key="PRIORITY_LOW_EMOJI"></div>
|
|
||||||
<div class="field"><label>Claimer Emoji Fallback</label><input type="text" data-key="CLAIMER_EMOJI_FALLBACK"></div>
|
|
||||||
</div></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 13. Staff -->
|
|
||||||
<div class="section" id="s-staff">
|
|
||||||
<div class="section-header"><h2>Staff</h2><p>Staff IDs, emojis, and admin settings</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body"><div class="field-grid">
|
|
||||||
<div class="field full-width"><label>Staff IDs (comma-separated)</label><input type="text" data-key="STAFF_IDS" data-smart="multi-member"></div>
|
|
||||||
<div class="field"><label>Admin ID</label><input type="text" data-key="ADMIN_ID" data-smart="member"></div>
|
|
||||||
<div class="field full-width"><label>Staff Emojis (userId:emoji, comma-separated)</label><input type="text" data-key="STAFF_EMOJIS"><div class="hint">Format: 123456:emoji,789012:emoji</div></div>
|
|
||||||
<div class="field full-width"><label>Additional Staff Roles (comma-separated)</label><input type="text" data-key="ADDITIONAL_STAFF_ROLES"><div class="hint">Role IDs with staff permissions</div></div>
|
|
||||||
<div class="field full-width"><label>Blacklisted Roles (comma-separated)</label><input type="text" data-key="BLACKLISTED_ROLES"><div class="hint">Role IDs that cannot open tickets</div></div>
|
|
||||||
<div class="field full-width"><label>Unclaimed Reminder Thresholds (hours, comma-separated)</label><input type="text" data-key="UNCLAIMED_REMINDER_THRESHOLDS"><div class="hint">e.g. 1,2,4</div></div>
|
|
||||||
</div></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 14. Advanced -->
|
|
||||||
<div class="section" id="s-advanced">
|
|
||||||
<div class="section-header"><h2>Advanced</h2><p>Ports, URLs, game list, branding</p><span class="chevron">▼</span></div>
|
|
||||||
<div class="section-body"><div class="field-grid">
|
|
||||||
<div class="field"><label>Bot Port</label><input type="number" data-key="DISCORD_ONLY_PORT"></div>
|
|
||||||
<div class="field"><label>Healthcheck Host</label><input type="text" data-key="HEALTHCHECK_HOST" placeholder="leave empty for all interfaces"></div>
|
|
||||||
<div class="field"><label>Settings Port</label><input type="number" data-key="SETTINGS_PORT"></div>
|
|
||||||
<div class="field"><label>Settings Domain</label><input type="text" data-key="SETTINGS_DOMAIN"></div>
|
|
||||||
<div class="field"><label>Internal API Port</label><input type="number" data-key="INTERNAL_API_PORT"></div>
|
|
||||||
<div class="field"><label>Support Name</label><input type="text" data-key="SUPPORT_NAME"></div>
|
|
||||||
<div class="field"><label>Logo URL</label><input type="text" data-key="LOGO_URL"></div>
|
|
||||||
<div class="field full-width"><label>Game List (comma-separated)</label><textarea data-key="GAME_LIST" rows="3"></textarea></div>
|
|
||||||
<div class="field full-width"><label>Email Signature (HTML, use \n for breaks)</label><textarea data-key="EMAIL_SIGNATURE" rows="3"></textarea></div>
|
|
||||||
<div class="field full-width"><label>Close Subject Prefix</label><input type="text" data-key="TICKET_CLOSE_SUBJECT_PREFIX"></div>
|
|
||||||
<div class="field full-width"><label>Close Message (email body)</label><textarea data-key="TICKET_CLOSE_MESSAGE" rows="2"></textarea></div>
|
|
||||||
<div class="field full-width"><label>Discord Close Message</label><textarea data-key="DISCORD_CLOSE_MESSAGE" rows="2"></textarea></div>
|
|
||||||
<div class="field full-width"><label>Transcript Message</label><textarea data-key="DISCORD_TRANSCRIPT_MESSAGE" rows="2"></textarea><div class="hint">Variables: {channel_name}, {email}, {date_opened}, {date_closed}</div></div>
|
|
||||||
<div class="field full-width"><label>Auto-Close Message</label><textarea data-key="DISCORD_AUTO_CLOSE_MESSAGE" rows="2"></textarea></div>
|
|
||||||
</div></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Save bar -->
|
|
||||||
<div id="save-bar" class="save-bar">
|
|
||||||
<span id="change-count">0 unsaved changes</span>
|
|
||||||
<div class="save-actions">
|
|
||||||
<button type="button" id="save-btn">Save</button>
|
|
||||||
<button type="button" id="save-restart-btn" class="danger">Save & Restart Now</button>
|
|
||||||
<button type="button" id="schedule-restart-btn" class="secondary">Schedule restart...</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Schedule modal -->
|
|
||||||
<div id="schedule-modal" class="modal hidden" role="dialog" aria-modal="true" aria-labelledby="schedule-modal-title">
|
|
||||||
<div class="modal-card">
|
|
||||||
<h3 id="schedule-modal-title">Schedule restart</h3>
|
|
||||||
<input type="datetime-local" id="schedule-datetime" aria-label="Restart date and time">
|
|
||||||
<div class="modal-actions">
|
|
||||||
<button type="button" id="schedule-confirm-btn">Schedule</button>
|
|
||||||
<button type="button" id="schedule-cancel-btn" class="secondary">Cancel</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script defer src="/js/util.js"></script>
|
|
||||||
<script defer src="/js/router.js"></script>
|
|
||||||
<script defer src="/js/fields.js"></script>
|
|
||||||
<script defer src="/js/notifications.js"></script>
|
|
||||||
<script defer src="/js/discord.js"></script>
|
|
||||||
<script defer src="/js/app.js"></script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,162 +0,0 @@
|
|||||||
(function () {
|
|
||||||
'use strict';
|
|
||||||
|
|
||||||
async function init() {
|
|
||||||
document.getElementById('loading').classList.remove('hidden');
|
|
||||||
try {
|
|
||||||
await Util.fetchCsrfToken();
|
|
||||||
const [config] = await Promise.all([
|
|
||||||
fetch('/api/config', { credentials: 'same-origin' }).then(r => r.json()),
|
|
||||||
DiscordFields.fetchGuildData()
|
|
||||||
]);
|
|
||||||
Fields.setSavedConfig(config);
|
|
||||||
document.getElementById('bot-status-dot').className = 'dot online';
|
|
||||||
document.getElementById('bot-status-text').textContent = 'Connected';
|
|
||||||
Fields.populateFields(config);
|
|
||||||
Notifications.initNotificationsEditor(config);
|
|
||||||
Fields.initSmartSelects(config);
|
|
||||||
} catch (e) {
|
|
||||||
document.getElementById('bot-status-dot').className = 'dot offline';
|
|
||||||
document.getElementById('bot-status-text').textContent = 'Unreachable';
|
|
||||||
}
|
|
||||||
document.getElementById('loading').classList.add('hidden');
|
|
||||||
setupSectionToggles();
|
|
||||||
Fields.setupSaveBar();
|
|
||||||
}
|
|
||||||
|
|
||||||
function setupSectionToggles() {
|
|
||||||
document.querySelectorAll('.section-header').forEach(header => {
|
|
||||||
header.addEventListener('click', () => {
|
|
||||||
header.closest('.section').classList.toggle('collapsed');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function openScheduleModal() {
|
|
||||||
const modal = document.getElementById('schedule-modal');
|
|
||||||
const dt = document.getElementById('schedule-datetime');
|
|
||||||
const min = Util.formatLocalDateTime(new Date(Date.now() + 60000));
|
|
||||||
dt.min = min;
|
|
||||||
dt.value = min;
|
|
||||||
Util.openModal(modal, { initialFocus: '#schedule-datetime' });
|
|
||||||
}
|
|
||||||
|
|
||||||
async function confirmScheduledRestart() {
|
|
||||||
const dt = document.getElementById('schedule-datetime').value;
|
|
||||||
if (!dt) return;
|
|
||||||
await fetch('/api/restart', {
|
|
||||||
method: 'POST',
|
|
||||||
credentials: 'same-origin',
|
|
||||||
headers: Util.csrfHeaders({ 'Content-Type': 'application/json' }),
|
|
||||||
body: JSON.stringify({ mode: 'scheduled', scheduledFor: new Date(dt).toISOString() })
|
|
||||||
});
|
|
||||||
Util.closeModal(document.getElementById('schedule-modal'));
|
|
||||||
Util.showToast(`Restart scheduled for ${new Date(dt).toLocaleString()}`, 'warning');
|
|
||||||
}
|
|
||||||
|
|
||||||
async function doLogout() {
|
|
||||||
try {
|
|
||||||
await fetch('/logout', {
|
|
||||||
method: 'POST',
|
|
||||||
credentials: 'same-origin',
|
|
||||||
headers: Util.csrfHeaders()
|
|
||||||
});
|
|
||||||
} catch (e) { /* ignore */ }
|
|
||||||
window.location.href = '/login';
|
|
||||||
}
|
|
||||||
|
|
||||||
function setupActionButtons() {
|
|
||||||
document.getElementById('save-btn')?.addEventListener('click', () => Fields.saveConfig('save'));
|
|
||||||
document.getElementById('save-restart-btn')?.addEventListener('click', () => Fields.saveConfig('restart'));
|
|
||||||
document.getElementById('schedule-restart-btn')?.addEventListener('click', openScheduleModal);
|
|
||||||
document.getElementById('schedule-confirm-btn')?.addEventListener('click', confirmScheduledRestart);
|
|
||||||
document.getElementById('schedule-cancel-btn')?.addEventListener('click', () => {
|
|
||||||
Util.closeModal(document.getElementById('schedule-modal'));
|
|
||||||
});
|
|
||||||
document.getElementById('logout-btn')?.addEventListener('click', doLogout);
|
|
||||||
}
|
|
||||||
|
|
||||||
function setupMobileNav() {
|
|
||||||
const toggle = document.getElementById('menu-toggle');
|
|
||||||
const backdrop = document.getElementById('sidebar-backdrop');
|
|
||||||
|
|
||||||
toggle?.addEventListener('click', () => {
|
|
||||||
Util.setSidebarOpen(!document.body.classList.contains('sidebar-open'));
|
|
||||||
});
|
|
||||||
backdrop?.addEventListener('click', () => Util.setSidebarOpen(false));
|
|
||||||
document.addEventListener('keydown', (e) => {
|
|
||||||
if (e.key === 'Escape' && document.body.classList.contains('sidebar-open')) {
|
|
||||||
Util.setSidebarOpen(false);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
window.addEventListener('resize', () => {
|
|
||||||
if (!Util.isMobileViewport() && document.body.classList.contains('sidebar-open')) {
|
|
||||||
Util.setSidebarOpen(false);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let healthPollHandle = null;
|
|
||||||
|
|
||||||
function setBotStatus(online) {
|
|
||||||
const dot = document.getElementById('bot-status-dot');
|
|
||||||
const text = document.getElementById('bot-status-text');
|
|
||||||
if (!dot || !text) return;
|
|
||||||
dot.className = online ? 'dot online' : 'dot offline';
|
|
||||||
text.textContent = online ? 'Connected' : 'Unreachable';
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pollHealth() {
|
|
||||||
try {
|
|
||||||
const res = await fetch('/healthz', { credentials: 'same-origin' });
|
|
||||||
if (res.ok) {
|
|
||||||
const data = await res.json();
|
|
||||||
setBotStatus(Boolean(data.bot));
|
|
||||||
} else {
|
|
||||||
setBotStatus(false);
|
|
||||||
}
|
|
||||||
} catch (_) {
|
|
||||||
setBotStatus(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function scheduleNextHealthPoll() {
|
|
||||||
if (document.hidden) return;
|
|
||||||
healthPollHandle = setTimeout(async () => {
|
|
||||||
await pollHealth();
|
|
||||||
scheduleNextHealthPoll();
|
|
||||||
}, 20000);
|
|
||||||
}
|
|
||||||
|
|
||||||
function startHealthPolling() {
|
|
||||||
if (healthPollHandle) clearTimeout(healthPollHandle);
|
|
||||||
scheduleNextHealthPoll();
|
|
||||||
}
|
|
||||||
|
|
||||||
function stopHealthPolling() {
|
|
||||||
if (healthPollHandle) {
|
|
||||||
clearTimeout(healthPollHandle);
|
|
||||||
healthPollHandle = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function setupHealthPolling() {
|
|
||||||
document.addEventListener('visibilitychange', () => {
|
|
||||||
if (document.hidden) stopHealthPolling();
|
|
||||||
else startHealthPolling();
|
|
||||||
});
|
|
||||||
window.addEventListener('pagehide', stopHealthPolling);
|
|
||||||
startHealthPolling();
|
|
||||||
}
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', async () => {
|
|
||||||
Router.setupSidebarRouting();
|
|
||||||
setupActionButtons();
|
|
||||||
setupMobileNav();
|
|
||||||
await init();
|
|
||||||
Router.navigate(location.pathname, false);
|
|
||||||
setupHealthPolling();
|
|
||||||
});
|
|
||||||
|
|
||||||
window.App = { init };
|
|
||||||
})();
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
(function () {
|
|
||||||
'use strict';
|
|
||||||
|
|
||||||
const ROUTES = {
|
|
||||||
'/': 's-core',
|
|
||||||
'/channels': 's-channels',
|
|
||||||
'/categories': 's-categories',
|
|
||||||
'/gmail': 's-gmail',
|
|
||||||
'/behavior': 's-behavior',
|
|
||||||
'/threads': 's-threads',
|
|
||||||
'/pins': 's-pins',
|
|
||||||
'/notifications': 's-notifications',
|
|
||||||
'/logging': 's-logging',
|
|
||||||
'/automation': 's-automation',
|
|
||||||
'/appearance': 's-appearance',
|
|
||||||
'/staff': 's-staff',
|
|
||||||
'/advanced': 's-advanced'
|
|
||||||
};
|
|
||||||
|
|
||||||
function navigate(path, updateHistory = true) {
|
|
||||||
const sectionId = ROUTES[path] || ROUTES['/'];
|
|
||||||
const normalizedPath = ROUTES[path] ? path : '/';
|
|
||||||
if (updateHistory) history.pushState({}, '', normalizedPath);
|
|
||||||
|
|
||||||
document.querySelectorAll('.section').forEach(section => {
|
|
||||||
section.classList.toggle('hidden', section.id !== sectionId);
|
|
||||||
});
|
|
||||||
|
|
||||||
document.querySelectorAll('.sidebar a').forEach(link => {
|
|
||||||
link.classList.toggle('active', link.getAttribute('href') === normalizedPath);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function setupSidebarRouting() {
|
|
||||||
const sidebar = document.querySelector('.sidebar');
|
|
||||||
if (!sidebar) return;
|
|
||||||
|
|
||||||
sidebar.addEventListener('click', e => {
|
|
||||||
const a = e.target.closest('a');
|
|
||||||
if (!a) return;
|
|
||||||
e.preventDefault();
|
|
||||||
navigate(a.getAttribute('href'));
|
|
||||||
if (Util.isMobileViewport()) Util.setSidebarOpen(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
window.addEventListener('popstate', () => {
|
|
||||||
navigate(location.pathname, false);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
window.Router = { ROUTES, navigate, setupSidebarRouting };
|
|
||||||
})();
|
|
||||||
10
utils.js
10
utils.js
@@ -3,7 +3,7 @@
|
|||||||
* priority helpers, template variables.
|
* priority helpers, template variables.
|
||||||
*/
|
*/
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
const { CONFIG, GAME_NAMES, GAME_ALIASES, TICKET_TAGS } = require('./config');
|
const { CONFIG, GAME_NAMES, GAME_ALIASES } = require('./config');
|
||||||
|
|
||||||
/** Constant-time string compare. Returns false for mismatched length or empty/nullish inputs without throwing. */
|
/** Constant-time string compare. Returns false for mismatched length or empty/nullish inputs without throwing. */
|
||||||
function safeEqual(a, b) {
|
function safeEqual(a, b) {
|
||||||
@@ -243,13 +243,6 @@ function getPriorityColor(priority) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Returns emoji for a ticket-tag key (e.g. server-down → ⬇️). Priority always comes first in channel name, then tag. */
|
|
||||||
function getTicketTagEmoji(tagKey) {
|
|
||||||
if (!tagKey) return '';
|
|
||||||
const t = (TICKET_TAGS || []).find(x => x.value === tagKey);
|
|
||||||
return t ? t.emoji : '';
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- TEMPLATE VARIABLES ---
|
// --- TEMPLATE VARIABLES ---
|
||||||
|
|
||||||
function replaceVariables(template, context = {}) {
|
function replaceVariables(template, context = {}) {
|
||||||
@@ -407,6 +400,5 @@ module.exports = {
|
|||||||
detectGame,
|
detectGame,
|
||||||
getPriorityEmoji,
|
getPriorityEmoji,
|
||||||
getPriorityColor,
|
getPriorityColor,
|
||||||
getTicketTagEmoji,
|
|
||||||
replaceVariables
|
replaceVariables
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user