more mvp strip
This commit is contained in:
@@ -21,7 +21,6 @@ const ALLOWED_CONFIG_KEYS = new Set([
|
||||
// Ticket settings
|
||||
'TICKET_CATEGORY_ID', 'TICKET_CATEGORY_NAME', 'TICKET_T2_CATEGORY_NAME', 'TICKET_T3_CATEGORY_NAME',
|
||||
'EMAIL_TICKET_OVERFLOW_CATEGORY_IDS', 'DISCORD_TICKET_CATEGORY_ID', 'DISCORD_TICKET_OVERFLOW_CATEGORY_IDS',
|
||||
'DISCORD_THREAD_CHANNEL_ID', 'EMAIL_THREAD_CHANNEL_ID', 'THREAD_PARENT_CHANNEL', 'USE_THREADS',
|
||||
// Escalation categories
|
||||
'EMAIL_ESCALATED2_CHANNEL_ID', 'DISCORD_ESCALATED2_CHANNEL_ID',
|
||||
'EMAIL_ESCALATED3_CHANNEL_ID', 'DISCORD_ESCALATED3_CHANNEL_ID',
|
||||
|
||||
@@ -239,16 +239,14 @@ async function sendTicketNotificationEmail(ticket, subjectLine, messageBody, fro
|
||||
* @param {string} replyText - Reply text
|
||||
* @param {string} recipientEmail - Recipient email
|
||||
* @param {string} subject - Subject line
|
||||
* @param {string} discordUser - Discord user name
|
||||
* @param {string} messageId - Message ID (optional)
|
||||
* @param {string} userId - Discord user ID for signature (optional)
|
||||
* @param {string} userId - Discord user ID for optional personal valediction/tagline (optional)
|
||||
*/
|
||||
async function sendGmailReply(
|
||||
threadId,
|
||||
replyText,
|
||||
recipientEmail,
|
||||
subject,
|
||||
discordUser,
|
||||
messageId,
|
||||
userId = null
|
||||
) {
|
||||
@@ -265,50 +263,44 @@ async function sendGmailReply(
|
||||
const utf8Subject = `=?utf-8?B?${Buffer.from(
|
||||
safeSubject
|
||||
).toString('base64')}?=`;
|
||||
const safeUser = escapeHtml(discordUser);
|
||||
const safeLogoUrl = escapeHtml(CONFIG.LOGO_URL || '');
|
||||
const companySignatureText = (CONFIG.SIGNATURE || '').replace(/<br>/g, '\n');
|
||||
|
||||
// Get staff signature if userId provided
|
||||
|
||||
let signatureBlocks = { text: '', html: '' };
|
||||
if (userId) {
|
||||
signatureBlocks = await getStaffSignatureBlocks(userId);
|
||||
}
|
||||
|
||||
// signatureBlocks.html must arrive pre-escaped; do not inject raw HTML here.
|
||||
const safeStaffSigHtml = signatureBlocks.html ? signatureBlocks.html.replace(/\n/g, '<br>') : '';
|
||||
const safeStaffSigText = signatureBlocks.text;
|
||||
const safeCompanySigHtml = escapeHtml(CONFIG.SIGNATURE || '').replace(/\n/g, '<br>');
|
||||
|
||||
const htmlBody = `
|
||||
<div style="font-family: sans-serif; font-size: 14px; color: #333;">
|
||||
<p>${escapeHtml(replyText).replace(/\n/g, '<br>')}</p>
|
||||
${safeStaffSigHtml ? `<p style="margin: 10px 0;">${safeStaffSigHtml}</p>` : ''}
|
||||
<hr style="border:none; border-top:1px solid #ddd; margin:20px 0;">
|
||||
<table border="0" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td style="padding-right: 12px;">
|
||||
${safeLogoUrl ? `<img src="${safeLogoUrl}" width="65">` : ''}
|
||||
</td>
|
||||
<td style="border-left: 1px solid #ddd; padding-left: 12px;">
|
||||
<p style="margin: 0; font-weight: bold;">${safeUser}</p>
|
||||
<div style="color: #666; font-size: 12px;">${safeCompanySigHtml}</div>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<div>
|
||||
${safeLogoUrl ? `<img src="${safeLogoUrl}" width="65" alt="Indifferent Broccoli"><br>` : ''}
|
||||
Indifferent Broccoli Support<br>
|
||||
<a href="https://indifferentbroccoli.com/">https://indifferentbroccoli.com/</a><br>
|
||||
Join us on <a href="https://discord.gg/2vmfrrtvJY">Discord</a><br>
|
||||
<br>
|
||||
<em>"We eat lag for breakfast. Whatever."</em>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
const boundary = '000000000000' + Date.now().toString(16);
|
||||
|
||||
const plainBody = [];
|
||||
plainBody.push(replyText);
|
||||
if (safeStaffSigText) {
|
||||
plainBody.push(safeStaffSigText);
|
||||
}
|
||||
plainBody.push('');
|
||||
plainBody.push('------------------------------');
|
||||
plainBody.push('');
|
||||
plainBody.push(companySignatureText);
|
||||
plainBody.push(replyText);
|
||||
if (safeStaffSigText) {
|
||||
plainBody.push('');
|
||||
plainBody.push(safeStaffSigText);
|
||||
}
|
||||
plainBody.push('');
|
||||
plainBody.push('Indifferent Broccoli Support');
|
||||
plainBody.push('https://indifferentbroccoli.com/');
|
||||
plainBody.push('Join us on Discord: https://discord.gg/2vmfrrtvJY');
|
||||
plainBody.push('');
|
||||
plainBody.push('"We eat lag for breakfast. Whatever."');
|
||||
|
||||
const raw = Buffer.from([
|
||||
`From: ${sanitizeHeaderValue(CONFIG.MY_EMAIL)}`,
|
||||
|
||||
346
services/gmail.js.bak3-20260421
Normal file
346
services/gmail.js.bak3-20260421
Normal file
@@ -0,0 +1,346 @@
|
||||
/**
|
||||
* Gmail service – OAuth client, send reply, send ticket-closed email.
|
||||
*/
|
||||
const { google } = require('googleapis');
|
||||
const { CONFIG } = require('../config');
|
||||
const { extractRawEmail, escapeHtml } = require('../utils');
|
||||
const { getStaffSignatureBlocks } = require('./staffSignature');
|
||||
const { logError } = require('./debugLog');
|
||||
const { readEnvFile } = require('./configPersistence');
|
||||
|
||||
function sanitizeHeaderValue(v) { return String(v || '').replace(/[\r\n]+/g, ' ').trim(); }
|
||||
const EMAIL_RE = /^[^@\s]+@[^@\s]+$/;
|
||||
|
||||
function getGmailClient() {
|
||||
const auth = new google.auth.OAuth2(
|
||||
process.env.GOOGLE_CLIENT_ID,
|
||||
process.env.GOOGLE_CLIENT_SECRET
|
||||
);
|
||||
auth.setCredentials({ refresh_token: CONFIG.REFRESH_TOKEN });
|
||||
return google.gmail({ version: 'v1', auth });
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-read REFRESH_TOKEN from .env, update in-memory config, and probe Google.
|
||||
* Used by the internal /gmail/reload endpoint so the weekly reauth chore does
|
||||
* not require a full container restart.
|
||||
*
|
||||
* Throws if the env file is missing the token, or if the probe call (getProfile)
|
||||
* fails — the caller surfaces the error so the UI can see why.
|
||||
*
|
||||
* @returns {Promise<{emailAddress: string}>}
|
||||
*/
|
||||
async function reloadGmailClient() {
|
||||
const envMap = readEnvFile();
|
||||
const newToken = envMap.get('REFRESH_TOKEN');
|
||||
if (!newToken) {
|
||||
const err = new Error('REFRESH_TOKEN not set in .env');
|
||||
err.code = 'ENOTOKEN';
|
||||
throw err;
|
||||
}
|
||||
process.env.REFRESH_TOKEN = newToken;
|
||||
CONFIG.REFRESH_TOKEN = newToken;
|
||||
const gmail = getGmailClient();
|
||||
const profile = await gmail.users.getProfile({ userId: 'me' });
|
||||
return { emailAddress: profile.data.emailAddress };
|
||||
}
|
||||
|
||||
async function sendTicketClosedEmail(ticket, discordDisplayName) {
|
||||
try {
|
||||
const gmail = getGmailClient();
|
||||
|
||||
// Send to the ticket sender (customer), not derived from thread (which can be support)
|
||||
const recipientEmail = sanitizeHeaderValue(extractRawEmail(ticket.senderEmail || '')).toLowerCase();
|
||||
if (!recipientEmail || recipientEmail === CONFIG.MY_EMAIL) return;
|
||||
if (!EMAIL_RE.test(recipientEmail)) {
|
||||
logError('sendTicketClosedEmail: invalid recipient', new Error(`Rejected: ${recipientEmail}`)).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
let subjectHeader = ticket.subject || 'Support';
|
||||
let msgId = null;
|
||||
try {
|
||||
const thread = await gmail.users.threads.get({
|
||||
userId: 'me',
|
||||
id: ticket.gmailThreadId
|
||||
});
|
||||
const messages = thread.data.messages || [];
|
||||
const lastMsg = [...messages].reverse()[0];
|
||||
if (lastMsg?.payload?.headers) {
|
||||
const subj = lastMsg.payload.headers.find(h => h.name === 'Subject')?.value;
|
||||
if (subj) subjectHeader = subj;
|
||||
msgId = sanitizeHeaderValue(lastMsg.payload.headers.find(h => h.name === 'Message-ID')?.value);
|
||||
}
|
||||
} catch (_) {
|
||||
/* use ticket.subject and no In-Reply-To if thread fetch fails */
|
||||
}
|
||||
|
||||
const finalSubject = sanitizeHeaderValue(`${CONFIG.TICKET_CLOSE_SUBJECT_PREFIX} ${subjectHeader}`);
|
||||
const utf8Subject = `=?utf-8?B?${Buffer.from(
|
||||
finalSubject
|
||||
).toString('base64')}?=`;
|
||||
|
||||
const serverDisplayName = escapeHtml(discordDisplayName || CONFIG.SUPPORT_NAME || 'Support');
|
||||
const safeLogoUrl = escapeHtml(CONFIG.LOGO_URL || '');
|
||||
const safeSignature = escapeHtml(CONFIG.SIGNATURE || '').replace(/\n/g, '<br>');
|
||||
const safeCloseMessage = escapeHtml(CONFIG.TICKET_CLOSE_MESSAGE || '').replace(/\n/g, '<br>');
|
||||
const safeCloseSignature = escapeHtml(CONFIG.TICKET_CLOSE_SIGNATURE || '').replace(/\n/g, '<br>');
|
||||
const htmlBody = `
|
||||
<div style="font-family: sans-serif; font-size: 14px; color: #333;">
|
||||
<p><strong>From:</strong> ${serverDisplayName} on Discord</p>
|
||||
<p><strong>Message:</strong></p>
|
||||
<p>${safeCloseMessage}</p>
|
||||
<p style="margin-top: 16px;">${safeCloseSignature}</p>
|
||||
<hr style="border:none; border-top:1px solid #ddd; margin:20px 0;">
|
||||
<table border="0" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td style="padding-right: 12px;">
|
||||
${safeLogoUrl ? `<img src="${safeLogoUrl}" width="65">` : ''}
|
||||
</td>
|
||||
<td style="border-left: 1px solid #ddd; padding-left: 12px;">
|
||||
<p style="margin: 0; font-weight: bold;">${serverDisplayName}</p>
|
||||
<div style="color: #666; font-size: 12px;">${safeSignature}</div>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>`;
|
||||
|
||||
const rawHeaders = [
|
||||
`From: ${sanitizeHeaderValue(CONFIG.MY_EMAIL)}`,
|
||||
`To: ${recipientEmail}`,
|
||||
`Subject: ${utf8Subject}`,
|
||||
msgId ? `In-Reply-To: ${msgId}` : '',
|
||||
msgId ? `References: ${msgId}` : '',
|
||||
'MIME-Version: 1.0',
|
||||
'Content-Type: text/html; charset="UTF-8"',
|
||||
'',
|
||||
htmlBody
|
||||
].filter(Boolean);
|
||||
|
||||
const raw = Buffer.from(rawHeaders.join('\r\n'))
|
||||
.toString('base64')
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/, '');
|
||||
|
||||
await gmail.users.messages.send({
|
||||
userId: 'me',
|
||||
requestBody: { raw, threadId: ticket.gmailThreadId }
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Ticket closed email error:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// StaffSignature model is registered in models.js; re-import here for use in this file
|
||||
const { mongoose } = require('../db-connection');
|
||||
const StaffSignature = mongoose.model('StaffSignature');
|
||||
|
||||
/**
|
||||
* Send a notification email in the ticket thread (e.g. escalation, high-priority).
|
||||
* @param {Object} ticket - Ticket with gmailThreadId, senderEmail, subject
|
||||
* @param {string} subjectLine - Subject line (e.g. "Ticket escalated" or "Priority updated")
|
||||
* @param {string} messageBody - Plain or HTML message body
|
||||
* @param {string} [fromLabel] - Label for "From" (e.g. "Support on Discord")
|
||||
* @param {string} [userId] - Discord user ID for signature (optional)
|
||||
*/
|
||||
async function sendTicketNotificationEmail(ticket, subjectLine, messageBody, fromLabel, userId = null) {
|
||||
try {
|
||||
const gmail = getGmailClient();
|
||||
const recipientEmail = sanitizeHeaderValue(extractRawEmail(ticket.senderEmail || '')).toLowerCase();
|
||||
if (!recipientEmail || recipientEmail === CONFIG.MY_EMAIL) return;
|
||||
if (!EMAIL_RE.test(recipientEmail)) {
|
||||
logError('sendTicketNotificationEmail: invalid recipient', new Error(`Rejected: ${recipientEmail}`)).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
let subjectHeader = ticket.subject || 'Support';
|
||||
let msgId = null;
|
||||
try {
|
||||
const thread = await gmail.users.threads.get({
|
||||
userId: 'me',
|
||||
id: ticket.gmailThreadId
|
||||
});
|
||||
const messages = thread.data.messages || [];
|
||||
const lastMsg = [...messages].reverse()[0];
|
||||
if (lastMsg?.payload?.headers) {
|
||||
const subj = lastMsg.payload.headers.find(h => h.name === 'Subject')?.value;
|
||||
if (subj) subjectHeader = subj;
|
||||
msgId = sanitizeHeaderValue(lastMsg.payload.headers.find(h => h.name === 'Message-ID')?.value);
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
const finalSubject = sanitizeHeaderValue(subjectLine || subjectHeader);
|
||||
const utf8Subject = `=?utf-8?B?${Buffer.from(finalSubject).toString('base64')}?=`;
|
||||
const label = escapeHtml(fromLabel || CONFIG.SUPPORT_NAME || 'Support');
|
||||
const safeBody = escapeHtml(messageBody || '').replace(/\n/g, '<br>');
|
||||
const safeLogoUrl = escapeHtml(CONFIG.LOGO_URL || '');
|
||||
|
||||
// Get staff signature if userId provided
|
||||
let signatureBlocks = { text: '', html: '' };
|
||||
if (userId) {
|
||||
signatureBlocks = await getStaffSignatureBlocks(userId);
|
||||
}
|
||||
|
||||
const safeSignature = escapeHtml(CONFIG.SIGNATURE || '').replace(/\n/g, '<br>');
|
||||
const serverDisplayName = label;
|
||||
const safeCloseMessage = safeBody;
|
||||
const safeCloseSignature = escapeHtml(CONFIG.TICKET_CLOSE_SIGNATURE || '').replace(/\n/g, '<br>');
|
||||
const htmlBody = `
|
||||
<div style="font-family: sans-serif; font-size: 14px; color: #333;">
|
||||
<p><strong>From:</strong> ${serverDisplayName} on Discord</p>
|
||||
<p><strong>Message:</strong></p>
|
||||
<p>${safeCloseMessage}</p>
|
||||
<p style="margin-top: 16px;">${safeCloseSignature}</p>
|
||||
<hr style="border:none; border-top:1px solid #ddd; margin:20px 0;">
|
||||
<table border="0" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td style="padding-right: 12px;">
|
||||
${safeLogoUrl ? `<img src="${safeLogoUrl}" width="65">` : ''}
|
||||
</td>
|
||||
<td style="border-left: 1px solid #ddd; padding-left: 12px;">
|
||||
<p style="margin: 0; font-weight: bold;">${serverDisplayName}</p>
|
||||
<div style="color: #666; font-size: 12px;">${safeSignature}</div>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>`;
|
||||
|
||||
const rawHeaders = [
|
||||
`From: ${sanitizeHeaderValue(CONFIG.MY_EMAIL)}`,
|
||||
`To: ${recipientEmail}`,
|
||||
`Subject: ${utf8Subject}`,
|
||||
msgId ? `In-Reply-To: ${msgId}` : '',
|
||||
msgId ? `References: ${msgId}` : '',
|
||||
'MIME-Version: 1.0',
|
||||
'Content-Type: text/html; charset="UTF-8"',
|
||||
'',
|
||||
htmlBody
|
||||
].filter(Boolean);
|
||||
|
||||
const raw = Buffer.from(rawHeaders.join('\r\n'))
|
||||
.toString('base64')
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/, '');
|
||||
|
||||
await gmail.users.messages.send({
|
||||
userId: 'me',
|
||||
requestBody: { raw, threadId: ticket.gmailThreadId }
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Ticket notification email error:', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a Gmail reply to a ticket
|
||||
* @param {string} threadId - Gmail thread ID
|
||||
* @param {string} replyText - Reply text
|
||||
* @param {string} recipientEmail - Recipient email
|
||||
* @param {string} subject - Subject line
|
||||
* @param {string} authorName - Replier's Discord server display name (caller resolves from member.displayName)
|
||||
* @param {string} messageId - Message ID (optional)
|
||||
* @param {string} userId - Discord user ID for optional personal valediction/tagline (optional)
|
||||
*/
|
||||
async function sendGmailReply(
|
||||
threadId,
|
||||
replyText,
|
||||
recipientEmail,
|
||||
subject,
|
||||
authorName,
|
||||
messageId,
|
||||
userId = null
|
||||
) {
|
||||
const gmail = getGmailClient();
|
||||
|
||||
const safeRecipient = sanitizeHeaderValue(extractRawEmail(recipientEmail || '')).toLowerCase();
|
||||
if (!EMAIL_RE.test(safeRecipient)) {
|
||||
logError('sendGmailReply: invalid recipient', new Error(`Rejected: ${safeRecipient}`)).catch(() => {});
|
||||
return null;
|
||||
}
|
||||
const safeMessageId = sanitizeHeaderValue(messageId);
|
||||
const safeSubject = sanitizeHeaderValue(`Re: ${subject}`);
|
||||
|
||||
const utf8Subject = `=?utf-8?B?${Buffer.from(
|
||||
safeSubject
|
||||
).toString('base64')}?=`;
|
||||
const safeAuthor = escapeHtml(authorName || '');
|
||||
|
||||
let signatureBlocks = { text: '', html: '' };
|
||||
if (userId) {
|
||||
signatureBlocks = await getStaffSignatureBlocks(userId);
|
||||
}
|
||||
// signatureBlocks.html must arrive pre-escaped; do not inject raw HTML here.
|
||||
const safeStaffSigHtml = signatureBlocks.html ? signatureBlocks.html.replace(/\n/g, '<br>') : '';
|
||||
const safeStaffSigText = signatureBlocks.text;
|
||||
|
||||
const htmlBody = `
|
||||
<div style="font-family: sans-serif; font-size: 14px; color: #333;">
|
||||
<p>${escapeHtml(replyText).replace(/\n/g, '<br>')}</p>
|
||||
${safeStaffSigHtml ? `<p style="margin: 10px 0;">${safeStaffSigHtml}</p>` : ''}
|
||||
<div>
|
||||
<strong>${safeAuthor}</strong><br>
|
||||
Indifferent Broccoli Support<br>
|
||||
<a href="https://indifferentbroccoli.com/">https://indifferentbroccoli.com/</a><br>
|
||||
Join us on <a href="https://discord.gg/2vmfrrtvJY">Discord</a><br>
|
||||
<br>
|
||||
<em>"We eat lag for breakfast. Whatever."</em>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
const boundary = '000000000000' + Date.now().toString(16);
|
||||
|
||||
const plainBody = [];
|
||||
plainBody.push(replyText);
|
||||
if (safeStaffSigText) {
|
||||
plainBody.push('');
|
||||
plainBody.push(safeStaffSigText);
|
||||
}
|
||||
plainBody.push('');
|
||||
plainBody.push(authorName || '');
|
||||
plainBody.push('Indifferent Broccoli Support');
|
||||
plainBody.push('https://indifferentbroccoli.com/');
|
||||
plainBody.push('Join us on Discord: https://discord.gg/2vmfrrtvJY');
|
||||
plainBody.push('');
|
||||
plainBody.push('"We eat lag for breakfast. Whatever."');
|
||||
|
||||
const raw = Buffer.from([
|
||||
`From: ${sanitizeHeaderValue(CONFIG.MY_EMAIL)}`,
|
||||
`To: ${safeRecipient}`,
|
||||
`Subject: ${utf8Subject}`,
|
||||
safeMessageId ? `In-Reply-To: ${safeMessageId}` : '',
|
||||
safeMessageId ? `References: ${safeMessageId}` : '',
|
||||
'MIME-Version: 1.0',
|
||||
'Content-Type: multipart/alternative; boundary="' + boundary + '"',
|
||||
'',
|
||||
'--' + boundary,
|
||||
'Content-Type: text/plain; charset="UTF-8"',
|
||||
'',
|
||||
...plainBody,
|
||||
'',
|
||||
'--' + boundary,
|
||||
'Content-Type: text/html; charset="UTF-8"',
|
||||
'',
|
||||
htmlBody,
|
||||
'',
|
||||
'--' + boundary + '--'
|
||||
].join('\r\n'))
|
||||
.toString('base64')
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/, '');
|
||||
|
||||
await gmail.users.messages.send({
|
||||
userId: 'me',
|
||||
requestBody: { raw, threadId }
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getGmailClient,
|
||||
reloadGmailClient,
|
||||
sendGmailReply,
|
||||
sendTicketClosedEmail,
|
||||
sendTicketNotificationEmail
|
||||
};
|
||||
@@ -1,33 +0,0 @@
|
||||
/**
|
||||
* Guild-specific settings (e.g. email ticket routing).
|
||||
*/
|
||||
const { mongoose } = require('../db-connection');
|
||||
|
||||
const GuildSettings = mongoose.model('GuildSettings');
|
||||
|
||||
/**
|
||||
* Get email ticket routing for a guild. Returns 'thread' or 'category'.
|
||||
* If not set, defaults to 'category'.
|
||||
* @param {string} guildId
|
||||
* @returns {Promise<'thread'|'category'>}
|
||||
*/
|
||||
async function getEmailRouting(guildId) {
|
||||
const doc = await GuildSettings.findOne({ guildId }).select('emailRouting').lean();
|
||||
if (doc && doc.emailRouting) return doc.emailRouting;
|
||||
return 'category';
|
||||
}
|
||||
|
||||
/**
|
||||
* Set email ticket routing for a guild.
|
||||
* @param {string} guildId
|
||||
* @param {'thread'|'category'} value
|
||||
*/
|
||||
async function setEmailRouting(guildId, value) {
|
||||
await GuildSettings.findOneAndUpdate(
|
||||
{ guildId },
|
||||
{ $set: { emailRouting: value, updatedAt: new Date() } },
|
||||
{ upsert: true, new: true }
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = { getEmailRouting, setEmailRouting };
|
||||
@@ -273,145 +273,49 @@ async function cleanupEmptyOverflowCategory(guild, categoryId, categoryName) {
|
||||
}
|
||||
|
||||
async function createTicketChannel(guild, ticketNumber, userId, subject, creatorNickname) {
|
||||
if (CONFIG.USE_THREADS && CONFIG.THREAD_PARENT_CHANNEL) {
|
||||
const parentChannel = guild.channels.cache.get(CONFIG.THREAD_PARENT_CHANNEL);
|
||||
if (!parentChannel) {
|
||||
throw new Error('Thread parent channel not found');
|
||||
}
|
||||
let parentId;
|
||||
try {
|
||||
parentId = await getOrCreateTicketCategory(guild, CONFIG.TICKET_CATEGORY_ID, CONFIG.TICKET_CATEGORY_NAME);
|
||||
} catch (e) {
|
||||
console.error('getOrCreateTicketCategory (createTicketChannel):', e);
|
||||
throw new Error('Ticket category not found or could not be allocated');
|
||||
}
|
||||
|
||||
const thread = await parentChannel.threads.create({
|
||||
name: `🎫・ticket-${ticketNumber}`,
|
||||
autoArchiveDuration: 1440,
|
||||
type: ChannelType.PrivateThread,
|
||||
invitable: false,
|
||||
reason: `Ticket #${ticketNumber}`
|
||||
});
|
||||
|
||||
await thread.members.add(userId);
|
||||
// Add all members with the support role so they can see and reply in the thread
|
||||
if (CONFIG.ROLE_ID_TO_PING) {
|
||||
const role = guild.roles.cache.get(CONFIG.ROLE_ID_TO_PING);
|
||||
if (role?.members?.size) {
|
||||
for (const [memberId] of role.members) {
|
||||
if (memberId === userId) continue; // already added
|
||||
await thread.members.add(memberId).catch(() => {});
|
||||
let channel;
|
||||
try {
|
||||
channel = await guild.channels.create({
|
||||
name: creatorNickname ? toDiscordSafeName(`unclaimed-${creatorNickname}-${ticketNumber}`) : `ticket-${ticketNumber}`,
|
||||
type: ChannelType.GuildText,
|
||||
parent: parentId,
|
||||
permissionOverwrites: [
|
||||
{
|
||||
id: guild.id,
|
||||
deny: [PermissionFlagsBits.ViewChannel]
|
||||
},
|
||||
{
|
||||
id: userId,
|
||||
allow: [
|
||||
PermissionFlagsBits.ViewChannel,
|
||||
PermissionFlagsBits.SendMessages,
|
||||
PermissionFlagsBits.ReadMessageHistory
|
||||
]
|
||||
},
|
||||
{
|
||||
id: CONFIG.ROLE_ID_TO_PING,
|
||||
allow: [
|
||||
PermissionFlagsBits.ViewChannel,
|
||||
PermissionFlagsBits.SendMessages,
|
||||
PermissionFlagsBits.ReadMessageHistory
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
return thread;
|
||||
} else {
|
||||
let parentId;
|
||||
try {
|
||||
parentId = await getOrCreateTicketCategory(guild, CONFIG.TICKET_CATEGORY_ID, CONFIG.TICKET_CATEGORY_NAME);
|
||||
} catch (e) {
|
||||
console.error('getOrCreateTicketCategory (createTicketChannel):', e);
|
||||
throw new Error('Ticket category not found or could not be allocated');
|
||||
}
|
||||
|
||||
let channel;
|
||||
try {
|
||||
channel = await guild.channels.create({
|
||||
name: creatorNickname ? toDiscordSafeName(`unclaimed-${creatorNickname}-${ticketNumber}`) : `ticket-${ticketNumber}`,
|
||||
type: ChannelType.GuildText,
|
||||
parent: parentId,
|
||||
permissionOverwrites: [
|
||||
{
|
||||
id: guild.id,
|
||||
deny: [PermissionFlagsBits.ViewChannel]
|
||||
},
|
||||
{
|
||||
id: userId,
|
||||
allow: [
|
||||
PermissionFlagsBits.ViewChannel,
|
||||
PermissionFlagsBits.SendMessages,
|
||||
PermissionFlagsBits.ReadMessageHistory
|
||||
]
|
||||
},
|
||||
{
|
||||
id: CONFIG.ROLE_ID_TO_PING,
|
||||
allow: [
|
||||
PermissionFlagsBits.ViewChannel,
|
||||
PermissionFlagsBits.SendMessages,
|
||||
PermissionFlagsBits.ReadMessageHistory
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('guild.channels.create (createTicketChannel):', e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
return channel;
|
||||
]
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('guild.channels.create (createTicketChannel):', e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a private Discord ticket thread under DISCORD_THREAD_CHANNEL_ID.
|
||||
* Adds creator and all members with ROLE_ID_TO_PING.
|
||||
* @param {import('discord.js').Guild} guild
|
||||
* @param {number} ticketNumber
|
||||
* @param {string} creatorUserId
|
||||
* @returns {Promise<import('discord.js').ThreadChannel>}
|
||||
*/
|
||||
async function createDiscordTicketAsThread(guild, ticketNumber, creatorUserId) {
|
||||
const parentId = CONFIG.DISCORD_THREAD_CHANNEL_ID;
|
||||
if (!parentId) throw new Error('DISCORD_THREAD_CHANNEL_ID is not set');
|
||||
const parentChannel = guild.channels.cache.get(parentId);
|
||||
if (!parentChannel) throw new Error('Discord thread parent channel not found');
|
||||
|
||||
const thread = await parentChannel.threads.create({
|
||||
name: `🎫・ticket-${ticketNumber}`,
|
||||
autoArchiveDuration: 1440,
|
||||
type: ChannelType.PrivateThread,
|
||||
invitable: false,
|
||||
reason: `Ticket #${ticketNumber}`
|
||||
});
|
||||
|
||||
await thread.members.add(creatorUserId);
|
||||
if (CONFIG.ROLE_ID_TO_PING) {
|
||||
const role = guild.roles.cache.get(CONFIG.ROLE_ID_TO_PING);
|
||||
if (role?.members?.size) {
|
||||
for (const [memberId] of role.members) {
|
||||
if (memberId === creatorUserId) continue;
|
||||
await thread.members.add(memberId).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
return thread;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a private email ticket thread under EMAIL_THREAD_CHANNEL_ID.
|
||||
* Adds all members with ROLE_ID_TO_PING (no creator; email tickets have no Discord user).
|
||||
* @param {import('discord.js').Guild} guild
|
||||
* @param {number} ticketNumber
|
||||
* @param {string} chanName
|
||||
* @returns {Promise<import('discord.js').ThreadChannel>}
|
||||
*/
|
||||
async function createEmailTicketAsThread(guild, ticketNumber, chanName) {
|
||||
const parentId = CONFIG.EMAIL_THREAD_CHANNEL_ID;
|
||||
if (!parentId) throw new Error('EMAIL_THREAD_CHANNEL_ID is not set');
|
||||
const parentChannel = guild.channels.cache.get(parentId);
|
||||
if (!parentChannel) throw new Error('Email thread parent channel not found');
|
||||
|
||||
const thread = await parentChannel.threads.create({
|
||||
name: chanName || `🎫・ticket-${ticketNumber}`,
|
||||
autoArchiveDuration: 1440,
|
||||
type: ChannelType.PrivateThread,
|
||||
invitable: false,
|
||||
reason: `Ticket #${ticketNumber}`
|
||||
});
|
||||
|
||||
if (CONFIG.ROLE_ID_TO_PING) {
|
||||
const role = guild.roles.cache.get(CONFIG.ROLE_ID_TO_PING);
|
||||
if (role?.members?.size) {
|
||||
for (const [memberId] of role.members) {
|
||||
await thread.members.add(memberId).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
return thread;
|
||||
return channel;
|
||||
}
|
||||
|
||||
// --- LIMITS & PERMISSIONS ---
|
||||
@@ -649,8 +553,6 @@ module.exports = {
|
||||
getNextTicketNumber,
|
||||
getOrCreateTicketCategory,
|
||||
cleanupEmptyOverflowCategory,
|
||||
createDiscordTicketAsThread,
|
||||
createEmailTicketAsThread,
|
||||
RENAME_WINDOW_MS,
|
||||
RENAME_LIMIT,
|
||||
getSenderLocal,
|
||||
|
||||
Reference in New Issue
Block a user