Inbound: - Gmail poll query is:unread in:inbox (was category:primary, which matched nothing on a no-tabs Workspace inbox) Outbound email: - Closed/escalation auto-emails editable via TICKET_CLOSE_MESSAGE and new TICKET_ESCALATION_EMAIL_MESSAGE; drop the staff signature from closing emails - Replies quote the customer's latest message (gmail_quote markup so clients collapse it), embed custom emoji inline via CID attachment, and strip Discord role mentions - Tagline spacing fix in the company signature Discord side: - Suppress all mentions in log + transcript posts (no more pinging on close) - Drop the staff-role ping from new-ticket and follow-up notifications - Ticket channels inherit category permissions instead of setting per-channel overwrites (removes the Manage Roles requirement) Gmail folders: - Folder/label routing (gmailLabels.js) with /folder; close files to Complete Config: - Remove ~56 stale .env keys for long-removed features; refresh stale copy Docs: - Design specs for folder routing, email-flow toggle, and per-staff metrics
120 lines
5.2 KiB
JavaScript
120 lines
5.2 KiB
JavaScript
/**
|
|
* Force-close flow: /force-close, /cancel-close, /closetimer, plus the
|
|
* countdown-elapses finalize step and transcript renderer that the
|
|
* countdown's setTimeout calls back into.
|
|
*
|
|
* Note: the button-driven close path lives in handlers/buttons.js
|
|
* (handleCloseButton / handleConfirmCloseRequest / runFinalClose).
|
|
* This module covers the slash-command-driven path only.
|
|
*/
|
|
const { AttachmentBuilder, MessageFlags } = require('discord.js');
|
|
const { mongoose } = require('../../db-connection');
|
|
const { CONFIG } = require('../../config');
|
|
const { enqueueSend } = require('../../services/channelQueue');
|
|
const { logTicketEvent, logError } = require('../../services/debugLog');
|
|
const { moveThreadToFolder } = require('../../services/gmailLabels');
|
|
const { pendingCloses } = require('../pendingCloses');
|
|
const { findTicketForChannel } = require('../sharedHelpers');
|
|
const { buildTranscriptText, formatDateForTranscript, renderTranscriptHeader } = require('../../services/transcript');
|
|
|
|
const Ticket = mongoose.model('Ticket');
|
|
|
|
async function handleCloseTimer(interaction) {
|
|
const seconds = parseInt(interaction.options.getString('seconds'), 10);
|
|
CONFIG.FORCE_CLOSE_TIMER = seconds;
|
|
logTicketEvent('Close timer updated', [
|
|
{ name: 'Duration', value: `${seconds}s` },
|
|
{ name: 'Set by', value: interaction.user.tag }
|
|
], interaction).catch(() => {});
|
|
return interaction.reply({ content: `Force-close timer set to ${seconds} seconds.`, flags: MessageFlags.Ephemeral });
|
|
}
|
|
|
|
async function handleCancelClose(interaction) {
|
|
const pending = pendingCloses.get(interaction.channel.id);
|
|
if (!pending) {
|
|
return interaction.reply({ content: 'No pending close for this channel.', flags: MessageFlags.Ephemeral });
|
|
}
|
|
clearTimeout(pending.timeout);
|
|
logTicketEvent('Force-close cancelled', [
|
|
{ name: 'Ticket', value: interaction.channel.name || interaction.channel.id },
|
|
{ name: 'Cancelled by', value: interaction.user.tag },
|
|
{ name: 'Original setter', value: pending.username || 'Unknown' }
|
|
], interaction).catch(() => {});
|
|
pendingCloses.delete(interaction.channel.id);
|
|
return interaction.reply({ content: 'Close cancelled.', flags: MessageFlags.Ephemeral });
|
|
}
|
|
|
|
async function handleForceClose(interaction) {
|
|
const ticket = await findTicketForChannel(interaction);
|
|
if (!ticket) return;
|
|
|
|
if (pendingCloses.has(interaction.channel.id)) {
|
|
return interaction.reply({ content: 'A close is already pending for this ticket.', flags: MessageFlags.Ephemeral });
|
|
}
|
|
|
|
const timerSeconds = CONFIG.FORCE_CLOSE_TIMER;
|
|
await interaction.reply(`Closing ticket in ${timerSeconds} seconds. Use \`/cancel-close\` to abort.`);
|
|
|
|
const channelRef = interaction.channel;
|
|
const clientRef = interaction.client;
|
|
const timerId = setTimeout(() => finalizeForceClose(channelRef, clientRef), timerSeconds * 1000);
|
|
pendingCloses.set(channelRef.id, { timeout: timerId, username: interaction.user.tag });
|
|
}
|
|
|
|
/** Performs the actual force-close work after the countdown elapses. */
|
|
async function finalizeForceClose(channelRef, clientRef) {
|
|
pendingCloses.delete(channelRef.id);
|
|
const freshTicket = await Ticket.findOne({ discordThreadId: channelRef.id }).lean();
|
|
if (!freshTicket || freshTicket.status === 'closed') return;
|
|
|
|
try {
|
|
// $unset welcomeMessageId so a future reopen on this thread doesn't carry
|
|
// a stale message ID pointing into the now-deleted channel.
|
|
await Ticket.updateOne(
|
|
{ gmailThreadId: freshTicket.gmailThreadId },
|
|
{ $set: { status: 'closed' }, $unset: { welcomeMessageId: '' } }
|
|
);
|
|
|
|
// File the email thread into the Resolved folder — non-fatal, email tickets only.
|
|
if (!freshTicket.gmailThreadId.startsWith('discord-')) {
|
|
moveThreadToFolder(freshTicket.gmailThreadId, 'RESOLVED')
|
|
.catch(err => logError('gmailLabels: resolved move', err).catch(() => {}));
|
|
}
|
|
|
|
await enqueueSend(channelRef, 'Ticket force-closed. Archiving...');
|
|
await postTranscript(channelRef, clientRef, freshTicket).catch(tErr =>
|
|
console.error('Transcript error (force-close):', tErr)
|
|
);
|
|
|
|
setTimeout(() => {
|
|
channelRef.delete('Ticket force-closed').catch(e =>
|
|
console.error('Failed to delete channel:', e)
|
|
);
|
|
}, 5000);
|
|
} catch (err) {
|
|
console.error('Force close error:', err);
|
|
}
|
|
}
|
|
|
|
/** Render and post a closing transcript for a ticket. */
|
|
async function postTranscript(channelRef, clientRef, freshTicket) {
|
|
await enqueueSend(channelRef, CONFIG.DISCORD_CLOSE_MESSAGE);
|
|
|
|
const log = await buildTranscriptText(channelRef, freshTicket);
|
|
const file = new AttachmentBuilder(Buffer.from(log), {
|
|
name: `transcript-${channelRef.name}.txt`
|
|
});
|
|
|
|
const transcriptChan = await clientRef.channels
|
|
.fetch(CONFIG.TRANSCRIPT_CHANNEL_ID)
|
|
.catch(() => null);
|
|
if (!transcriptChan) return;
|
|
|
|
const openedStr = formatDateForTranscript(freshTicket.createdAt);
|
|
const closedStr = formatDateForTranscript(new Date());
|
|
const transcriptContent = renderTranscriptHeader(channelRef.name, freshTicket.senderEmail, openedStr, closedStr);
|
|
await enqueueSend(transcriptChan, { content: transcriptContent, files: [file], allowedMentions: { parse: [] } });
|
|
}
|
|
|
|
module.exports = { handleCloseTimer, handleCancelClose, handleForceClose };
|