From b72394231b62c4d8aa622ec44b2281d92dd705ee Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 14:35:46 -0400 Subject: [PATCH 01/59] Add automatic settings migration for missing defaults --- src/config.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/config.js b/src/config.js index 6646e11..d5f7c84 100644 --- a/src/config.js +++ b/src/config.js @@ -2,6 +2,7 @@ import 'dotenv/config'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; +import { addMissingDefaults } from './utils/settings-migration.js'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const configPath = path.resolve(root, process.env.TICKETS_CONFIG || './config/settings.json'); @@ -20,6 +21,16 @@ try { throw new Error(`Unable to read JSON settings at ${configPath}: ${error.message}`); } +const sampleSettings = JSON.parse(fs.readFileSync(examplePath, 'utf8')); +if (addMissingDefaults(settings, sampleSettings)) { + fs.writeFileSync(configPath, `${JSON.stringify(settings, null, 2)}\n`, 'utf8'); + console.info(`[config] Migrated ${path.relative(root, configPath)} with missing defaults.`); +} + +if (typeof settings?.ticketing?.channelPrefix !== 'string') { + throw new Error('settings.ticketing.channelPrefix must be a string.'); +} + const categories = settings?.ticketing?.categories; if (!Array.isArray(categories) || categories.length < 1) { throw new Error('settings.ticketing.categories must contain at least one category.'); From 449a7f34b3ac166796fb3a394d2d2ac65f984a1d Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 14:35:51 -0400 Subject: [PATCH 02/59] Add configurable ticket channel prefix --- config/settings.example.json | 1 + 1 file changed, 1 insertion(+) diff --git a/config/settings.example.json b/config/settings.example.json index 0c5c3c4..54b3103 100644 --- a/config/settings.example.json +++ b/config/settings.example.json @@ -7,6 +7,7 @@ "defaultColor": "#6D5AE6" }, "ticketing": { + "channelPrefix": "ticket-", "maxOpenPerUser": 3, "creationCooldownSeconds": 20, "queue": { From 88fb3b37c4d226283cf5a5c92c78353b47e2fed9 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 14:36:00 -0400 Subject: [PATCH 03/59] Use configured prefix for ticket channel names --- src/services/tickets.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index fdfeb1b..3060289 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -40,7 +40,8 @@ export async function createTicket({ guild, user, member, categoryId, answers, d if (description) normalizedAnswers['Additional details'] = truncate(description, 1000); const safeOwner = safeChannelName(user.username || 'member').slice(0, 32); - const channelName = `ticket-${safeOwner}`; + const channelPrefix = config.ticketing.channelPrefix ?? 'ticket-'; + const channelName = safeChannelName(`${channelPrefix}${safeOwner}`); const overwrites = [ { id: guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel] }, { id: user.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.EmbedLinks] }, @@ -246,7 +247,9 @@ export async function reopenTicket({ ticket, channel, member, db, config }) { if (!isStaff(member, config, category) && ticket.owner_id !== memberId(member)) throw new Error('You cannot reopen this ticket.'); const nextStatus = config.ticketing.queue?.enabled ? 'queued' : 'open'; db.updateTicket(ticket.id, { status: nextStatus, claimed_by: null, closed_at: null, closed_by: null, close_reason: null, last_activity_at: Date.now() }); - await channel.setName(safeChannelName(`ticket-${ticket.id}-${(await channel.guild.client.users.fetch(ticket.owner_id).catch(() => null))?.username || 'member'}`).slice(0, 100)).catch(() => {}); + const ownerName = (await channel.guild.client.users.fetch(ticket.owner_id).catch(() => null))?.username || 'member'; + const channelPrefix = config.ticketing.channelPrefix ?? 'ticket-'; + await channel.setName(safeChannelName(`${channelPrefix}${ticket.id}-${ownerName}`).slice(0, 100)).catch(() => {}); await channel.permissionOverwrites.edit(ticket.owner_id, { ViewChannel: true, SendMessages: true, ReadMessageHistory: true }).catch(() => {}); for (const userId of db.listParticipants(ticket.id)) { if (userId !== ticket.owner_id) await channel.permissionOverwrites.edit(userId, { ViewChannel: true, SendMessages: true, ReadMessageHistory: true }).catch(() => {}); From 4b44f57d86e3a804afa0a551d96452110a0bcd4c Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 14:36:06 -0400 Subject: [PATCH 04/59] Add additive settings migration helper --- src/utils/settings-migration.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/utils/settings-migration.js diff --git a/src/utils/settings-migration.js b/src/utils/settings-migration.js new file mode 100644 index 0000000..9557b9c --- /dev/null +++ b/src/utils/settings-migration.js @@ -0,0 +1,29 @@ +function isObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** + * Fill missing settings from the current sample config without replacing any + * existing values. Arrays are treated as user-configured values and are copied + * only when the entire setting is missing. + */ +export function addMissingDefaults(settings, defaults) { + if (!isObject(settings) || !isObject(defaults)) { + throw new TypeError('Settings and defaults must be JSON objects.'); + } + + let changed = false; + for (const [key, defaultValue] of Object.entries(defaults)) { + if (!Object.hasOwn(settings, key)) { + settings[key] = structuredClone(defaultValue); + changed = true; + continue; + } + + if (isObject(settings[key]) && isObject(defaultValue)) { + changed = addMissingDefaults(settings[key], defaultValue) || changed; + } + } + + return changed; +} From 74305e01107af4622231f047051e945338ee13b8 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 14:36:12 -0400 Subject: [PATCH 05/59] Test additive settings migration --- tests/settings-migration.test.js | 46 ++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 tests/settings-migration.test.js diff --git a/tests/settings-migration.test.js b/tests/settings-migration.test.js new file mode 100644 index 0000000..04ab1f8 --- /dev/null +++ b/tests/settings-migration.test.js @@ -0,0 +1,46 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { addMissingDefaults } from '../src/utils/settings-migration.js'; + +test('settings migration adds missing defaults without replacing custom values', () => { + const settings = { + app: { name: 'Custom Tickets' }, + ticketing: { + maxOpenPerUser: 7, + categories: [{ id: 'custom' }] + } + }; + const defaults = { + app: { name: 'Default Tickets', footer: 'Support' }, + ticketing: { + channelPrefix: 'ticket-', + maxOpenPerUser: 3, + categories: [{ id: 'general' }] + }, + features: { reviews: true } + }; + + assert.equal(addMissingDefaults(settings, defaults), true); + assert.equal(settings.app.name, 'Custom Tickets'); + assert.equal(settings.app.footer, 'Support'); + assert.equal(settings.ticketing.channelPrefix, 'ticket-'); + assert.equal(settings.ticketing.maxOpenPerUser, 7); + assert.deepEqual(settings.ticketing.categories, [{ id: 'custom' }]); + assert.deepEqual(settings.features, { reviews: true }); + assert.equal(addMissingDefaults(settings, defaults), false); +}); + +test('settings migration clones missing arrays instead of sharing defaults', () => { + const settings = {}; + const defaults = { ticketing: { channelPrefix: 'ticket-', categories: [{ id: 'general' }] } }; + + addMissingDefaults(settings, defaults); + settings.ticketing.categories[0].id = 'changed'; + + assert.equal(defaults.ticketing.categories[0].id, 'general'); +}); + +test('settings migration rejects non-object inputs', () => { + assert.throws(() => addMissingDefaults(null, {}), TypeError); + assert.throws(() => addMissingDefaults({}, []), TypeError); +}); From 81c8b057234f228fa31649eb412c6e6bcb6daf8c Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 14:36:19 -0400 Subject: [PATCH 06/59] Document ticket channel prefix and config migration --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 88c4ed4..cd642b1 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,8 @@ DISCORD_CLIENT_ID=your_application_id On first start, `config/settings.json` is created automatically from `config/settings.example.json`. Open it and set your role IDs, channel IDs, and ticket category parent channel IDs before inviting the bot to your server. +On later starts, missing settings are automatically added from the sample config without overwriting existing custom values. + Deploy slash commands: ```sh @@ -76,6 +78,7 @@ Once online, run `/ticket-panel` in the channel where users should open tickets. | `permissions.adminRoleIds` | Roles with full admin access | | `channels.ticketLogsId` | Channel where ticket events are logged | | `ticketing.categories` | The ticket categories shown in the panel | +| `ticketing.channelPrefix` | Prefix for new and reopened ticket channels (default: `ticket-`; for example, `support-`) | | `ticketing.maxOpenPerUser` | Max open tickets per user (`0` = unlimited) | | `ticketing.creationCooldownSeconds` | Minimum seconds between ticket opens | | `ticketing.queue.enabled` | Turn the persistent queue on or off | From a30ceda00116c0b519b2bd6f3c78b271508169df Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:04:20 -0400 Subject: [PATCH 07/59] Add configurable priority ordering helpers --- src/utils/priority.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/utils/priority.js diff --git a/src/utils/priority.js b/src/utils/priority.js new file mode 100644 index 0000000..228af41 --- /dev/null +++ b/src/utils/priority.js @@ -0,0 +1,29 @@ +export function getPriorityLevel(priorityId, priorityLevels = []) { + return priorityLevels.find((level) => level.id === priorityId) ?? null; +} + +export function getPriorityRank(priorityId, priorityLevels = []) { + const rank = Number(getPriorityLevel(priorityId, priorityLevels)?.rank ?? 0); + return Number.isFinite(rank) ? rank : 0; +} + +export function formatPriority(priorityId, priorityLevels = []) { + const level = getPriorityLevel(priorityId, priorityLevels); + if (!level) return String(priorityId || 'unknown'); + return [level.emoji, level.label || level.id].filter(Boolean).join(' '); +} + +export function compareTicketsByPriority(a, b, priorityLevels = []) { + const rankDifference = getPriorityRank(b.priority, priorityLevels) - getPriorityRank(a.priority, priorityLevels); + if (rankDifference) return rankDifference; + + const aCreated = Number(a.created_at ?? a.createdAt ?? 0); + const bCreated = Number(b.created_at ?? b.createdAt ?? 0); + if (aCreated !== bCreated) return aCreated - bCreated; + + return Number(a.id ?? 0) - Number(b.id ?? 0); +} + +export function sortTicketsByPriority(tickets, priorityLevels = []) { + return [...tickets].sort((a, b) => compareTicketsByPriority(a, b, priorityLevels)); +} From 6e78a9fcde51f4c7f5c9055ec359feb3deaa313b Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:04:29 -0400 Subject: [PATCH 08/59] Test configurable priority ordering --- tests/priority.test.js | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 tests/priority.test.js diff --git a/tests/priority.test.js b/tests/priority.test.js new file mode 100644 index 0000000..ad67bfa --- /dev/null +++ b/tests/priority.test.js @@ -0,0 +1,41 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { compareTicketsByPriority, formatPriority, getPriorityRank, sortTicketsByPriority } from '../src/utils/priority.js'; + +const priorityLevels = [ + { id: 'low', label: 'Low', rank: 1, emoji: '🟢' }, + { id: 'normal', label: 'Normal', rank: 2, emoji: '🔵' }, + { id: 'high', label: 'High', rank: 3, emoji: '🟠' }, + { id: 'urgent', label: 'Urgent', rank: 4, emoji: '🔴' } +]; + +test('tickets sort from highest configured priority to lowest, FIFO within each priority', () => { + const tickets = [ + { id: 1, priority: 'normal', created_at: 1 }, + { id: 2, priority: 'urgent', created_at: 3 }, + { id: 3, priority: 'low', created_at: 0 }, + { id: 4, priority: 'high', created_at: 4 }, + { id: 5, priority: 'urgent', created_at: 2 } + ]; + + assert.deepEqual(sortTicketsByPriority(tickets, priorityLevels).map((ticket) => ticket.id), [5, 2, 4, 1, 3]); + assert.deepEqual(tickets.map((ticket) => ticket.id), [1, 2, 3, 4, 5], 'sorting does not mutate the caller array'); +}); + +test('priority sorting uses configured ranks rather than hard-coded priority names', () => { + const levels = [{ id: 'p3', label: 'P3', rank: 30 }, { id: 'p1', label: 'P1', rank: 10 }]; + assert.deepEqual(sortTicketsByPriority([ + { id: 1, priority: 'p1', created_at: 1 }, + { id: 2, priority: 'p3', created_at: 2 } + ], levels).map((ticket) => ticket.id), [2, 1]); +}); + +test('unknown or unranked priorities fall below configured priorities', () => { + assert.ok(getPriorityRank('unknown', priorityLevels) < getPriorityRank('low', priorityLevels)); + assert.equal(compareTicketsByPriority({ priority: 'unknown' }, { priority: 'also-unknown' }, []), 0); +}); + +test('priority display uses configured emoji and label', () => { + assert.equal(formatPriority('urgent', priorityLevels), '🔴 Urgent'); + assert.equal(formatPriority('custom', priorityLevels), 'custom'); +}); From 52abdb78d67d03a034e42a973a32f6105eb27b53 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:04:50 -0400 Subject: [PATCH 09/59] Add persistent editable queue status embed --- src/services/queue-display.js | 71 +++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/services/queue-display.js diff --git a/src/services/queue-display.js b/src/services/queue-display.js new file mode 100644 index 0000000..79460e1 --- /dev/null +++ b/src/services/queue-display.js @@ -0,0 +1,71 @@ +import { EmbedBuilder } from 'discord.js'; +import { formatPriority } from '../utils/priority.js'; + +function isUnknownMessage(error) { + return Number(error?.code ?? error?.rawError?.code) === 10008; +} + +function buildQueueEmbed({ guild, queued, config, display }) { + const maxTickets = Math.min(25, Math.max(1, Number(display.maxTickets ?? 15))); + const shown = queued.slice(0, maxTickets); + const lines = shown.map((ticket, index) => { + const category = config.ticketing.categories.find((item) => item.id === ticket.category_id); + const channel = guild.channels.cache.get(ticket.channel_id); + const channelLabel = channel ? \`<#\${channel.id}>\` : \`Ticket #\${ticket.id}\`; + const categoryLabel = category?.name ?? ticket.category_id; + return \`**\${index + 1}.** \${formatPriority(ticket.priority, config.priorityLevels)} · \${channelLabel} · \${categoryLabel} · <@\${ticket.owner_id}>\`; + }); + if (queued.length === 0) lines.push('There are currently no tickets waiting for support.'); + if (queued.length > shown.length) lines.push(\`\\n…and \${queued.length - shown.length} more waiting ticket(s).\`); + + return new EmbedBuilder() + .setColor(config.app.defaultColor || '#6D5AE6') + .setTitle(String(display.title || 'Support Queue').slice(0, 256)) + .setDescription(lines.join('\\n').slice(0, 4096)) + .setFooter({ text: \`\${queued.length} waiting · Updates every \${Math.max(15, Number(display.refreshIntervalSeconds ?? 60))} seconds\` }) + .setTimestamp(); +} + +/** + * Creates or edits this guild's persistent queue embed. Its message ID is kept + * in SQLite so a bot restart edits the existing message instead of duplicating it. + */ +export async function refreshQueueDisplay({ guild, db, config }) { + const display = config.ticketing.queue?.display; + if (!display?.enabled || !display.channelId) return false; + if ((display.type || 'embed') !== 'embed') throw new Error('ticketing.queue.display.type currently supports only "embed".'); + + const channel = await guild.channels.fetch(display.channelId).catch((error) => { + console.warn(\`[queue-display] Unable to fetch configured channel \${display.channelId} in guild \${guild.id}: \${error.message}\`); + return null; + }); + if (!channel?.isTextBased?.() || typeof channel.send !== 'function') { + console.warn(\`[queue-display] Configured channel \${display.channelId} is not a sendable text channel in guild \${guild.id}.\`); + return false; + } + + const queued = db.queueList(guild.id, config.priorityLevels); + const payload = { + embeds: [buildQueueEmbed({ guild, queued, config, display })], + allowedMentions: { parse: [] } + }; + const stored = db.getQueueStatusMessage(guild.id); + let message = null; + + if (stored?.channel_id === channel.id && stored.message_id) { + try { + message = await channel.messages.fetch(stored.message_id); + } catch (error) { + if (!isUnknownMessage(error)) throw error; + } + } + + if (message) { + await message.edit(payload); + return true; + } + + const created = await channel.send(payload); + db.saveQueueStatusMessage(guild.id, channel.id, created.id); + return true; +} From cc2bd0a30d373de4ef97bf19b97096b8432ca8e0 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:05:01 -0400 Subject: [PATCH 10/59] Migrate new defaults into existing category and priority entries --- src/utils/settings-migration.js | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/utils/settings-migration.js b/src/utils/settings-migration.js index 9557b9c..31ad175 100644 --- a/src/utils/settings-migration.js +++ b/src/utils/settings-migration.js @@ -4,8 +4,8 @@ function isObject(value) { /** * Fill missing settings from the current sample config without replacing any - * existing values. Arrays are treated as user-configured values and are copied - * only when the entire setting is missing. + * existing values. Arrays of keyed objects receive missing fields only on + * matching IDs; user-added or removed categories and priority levels are kept. */ export function addMissingDefaults(settings, defaults) { if (!isObject(settings) || !isObject(defaults)) { @@ -20,8 +20,22 @@ export function addMissingDefaults(settings, defaults) { continue; } - if (isObject(settings[key]) && isObject(defaultValue)) { - changed = addMissingDefaults(settings[key], defaultValue) || changed; + const currentValue = settings[key]; + if (isObject(currentValue) && isObject(defaultValue)) { + changed = addMissingDefaults(currentValue, defaultValue) || changed; + continue; + } + + if (Array.isArray(currentValue) && Array.isArray(defaultValue)) { + const keyedDefaults = new Map( + defaultValue.filter((item) => isObject(item) && item.id !== undefined) + .map((item) => [String(item.id), item]) + ); + for (const item of currentValue) { + if (!isObject(item) || item.id === undefined) continue; + const matchingDefault = keyedDefaults.get(String(item.id)); + if (matchingDefault) changed = addMissingDefaults(item, matchingDefault) || changed; + } } } From 77ffcec787edaee4f310d3d148362d631d5e4c04 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:05:13 -0400 Subject: [PATCH 11/59] Add priority-based ticket channel ordering --- src/services/ticket-ordering.js | 43 +++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/services/ticket-ordering.js diff --git a/src/services/ticket-ordering.js b/src/services/ticket-ordering.js new file mode 100644 index 0000000..401b913 --- /dev/null +++ b/src/services/ticket-ordering.js @@ -0,0 +1,43 @@ +import { sortTicketsByPriority } from '../utils/priority.js'; + +/** + * Reorders only the positions already occupied by ticket channels in each + * parent category. Unrelated channels keep their own positions. + */ +export function buildPriorityPositionUpdates(entries, priorityLevels = []) { + const groups = new Map(); + for (const entry of entries) { + const parentId = entry.channel.parentId ?? ''; + if (!groups.has(parentId)) groups.set(parentId, []); + groups.get(parentId).push(entry); + } + + const updates = []; + for (const group of groups.values()) { + if (group.length < 2) continue; + const slots = group.map((entry) => Number(entry.channel.position)).sort((a, b) => a - b); + const orderedTickets = sortTicketsByPriority(group.map((entry) => entry.ticket), priorityLevels); + const entriesById = new Map(group.map((entry) => [Number(entry.ticket.id), entry])); + + orderedTickets.forEach((ticket, index) => { + const entry = entriesById.get(Number(ticket.id)); + const position = slots[index]; + if (Number(entry.channel.position) !== position) { + updates.push({ channel: entry.channel.id, position }); + } + }); + } + return updates; +} + +export async function sortTicketChannelsByPriority({ guild, db, config }) { + const tickets = db.ticketsForGuild(guild.id); + const entries = tickets.map((ticket) => ({ + ticket, + channel: guild.channels.cache.get(ticket.channel_id) + })).filter((entry) => entry.channel && Number.isFinite(Number(entry.channel.position))); + + const updates = buildPriorityPositionUpdates(entries, config.priorityLevels); + if (updates.length) await guild.channels.setPositions(updates); + return updates.length; +} From 1b0de599bbed1fed20e0411b2f950db011d8291c Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:05:26 -0400 Subject: [PATCH 12/59] Use configured priorities for queue order and persist queue display messages --- src/db/database.js | 41 +++++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/src/db/database.js b/src/db/database.js index 575eba3..0c47bf6 100644 --- a/src/db/database.js +++ b/src/db/database.js @@ -1,6 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; import Sqlite from 'better-sqlite3'; +import { sortTicketsByPriority } from '../utils/priority.js'; const now = () => Date.now(); const asJson = (value, fallback = []) => { @@ -107,6 +108,13 @@ export class Database { created_at INTEGER NOT NULL ); + CREATE TABLE IF NOT EXISTS queue_status_messages ( + guild_id TEXT PRIMARY KEY, + channel_id TEXT NOT NULL, + message_id TEXT NOT NULL, + updated_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS invoices ( id INTEGER PRIMARY KEY AUTOINCREMENT, guild_id TEXT NOT NULL, @@ -145,6 +153,11 @@ export class Database { return ticket; } + ticketsForGuild(guildId) { + return this.sqlite.prepare('SELECT * FROM tickets WHERE guild_id=? ORDER BY created_at ASC, id ASC') + .all(guildId).map((row) => this.hydrateTicket(row)); + } + getTicketById(id) { const row = this.sqlite.prepare('SELECT * FROM tickets WHERE id = ?').get(Number(id)); return this.hydrateTicket(row); @@ -174,7 +187,7 @@ export class Database { return this.getTicketById(id); } - claimTicketAtomically({ ticketId, staffId, guildId, capacity = 0, strictOrder = false, allowQueueJump = false }) { + claimTicketAtomically({ ticketId, staffId, guildId, capacity = 0, strictOrder = false, allowQueueJump = false, priorityLevels = [] }) { const transaction = this.sqlite.transaction(() => { const ticket = this.sqlite.prepare('SELECT * FROM tickets WHERE id=? AND guild_id=?').get(Number(ticketId), guildId); if (!ticket) return { ok: false, reason: 'missing' }; @@ -188,8 +201,9 @@ export class Database { } if (strictOrder && !allowQueueJump) { - const first = this.sqlite.prepare(`SELECT id FROM tickets WHERE guild_id=? AND status='queued' AND claimed_by IS NULL - ORDER BY CASE priority WHEN 'urgent' THEN 4 WHEN 'high' THEN 3 WHEN 'normal' THEN 2 ELSE 1 END DESC, created_at ASC LIMIT 1`).get(guildId); + const waiting = this.sqlite.prepare("SELECT * FROM tickets WHERE guild_id=? AND status='queued' AND claimed_by IS NULL") + .all(guildId).map((row) => this.hydrateTicket(row)); + const first = sortTicketsByPriority(waiting, priorityLevels)[0]; if (first && Number(first.id) !== Number(ticketId)) return { ok: false, reason: 'order', nextTicketId: Number(first.id) }; } @@ -268,10 +282,25 @@ export class Database { .all(staleBefore, ...guildIds).map((row) => this.hydrateTicket(row)); } - queueList(guildId) { - return this.sqlite.prepare(`SELECT * FROM tickets WHERE guild_id=? AND status='queued' AND claimed_by IS NULL - ORDER BY CASE priority WHEN 'urgent' THEN 4 WHEN 'high' THEN 3 WHEN 'normal' THEN 2 ELSE 1 END DESC, created_at ASC`) + queueList(guildId, priorityLevels = []) { + const rows = this.sqlite.prepare("SELECT * FROM tickets WHERE guild_id=? AND status='queued' AND claimed_by IS NULL") .all(guildId).map((row) => this.hydrateTicket(row)); + return sortTicketsByPriority(rows, priorityLevels); + } + + getQueueStatusMessage(guildId) { + return this.sqlite.prepare('SELECT guild_id, channel_id, message_id, updated_at FROM queue_status_messages WHERE guild_id=?') + .get(guildId) ?? null; + } + + saveQueueStatusMessage(guildId, channelId, messageId) { + const stamp = now(); + this.sqlite.prepare(`INSERT INTO queue_status_messages(guild_id, channel_id, message_id, updated_at) + VALUES(?,?,?,?) + ON CONFLICT(guild_id) DO UPDATE SET + channel_id=excluded.channel_id, message_id=excluded.message_id, updated_at=excluded.updated_at`) + .run(guildId, channelId, messageId, stamp); + return this.getQueueStatusMessage(guildId); } reserveCreationCooldown(guildId, userId, cooldownMs) { From 6dcf9f8c72259aa7d194e1f7f6eb597770420d88 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:05:37 -0400 Subject: [PATCH 13/59] Add per-category prefix and queue embed settings --- config/settings.example.json | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/config/settings.example.json b/config/settings.example.json index 54b3103..03d5c1f 100644 --- a/config/settings.example.json +++ b/config/settings.example.json @@ -13,7 +13,15 @@ "queue": { "enabled": false, "strictOrder": true, - "staffCapacity": 3 + "staffCapacity": 3, + "display": { + "enabled": false, + "type": "embed", + "channelId": "", + "refreshIntervalSeconds": 60, + "maxTickets": 15, + "title": "Support Queue" + } }, "claims": { "lockOwnerAfterClaim": false, @@ -48,6 +56,7 @@ "categories": [ { "id": "general", + "channelPrefix": "", "name": "General Support", "description": "Questions and general help", "emoji": "🎫", @@ -61,6 +70,7 @@ }, { "id": "technical", + "channelPrefix": "", "name": "Technical Support", "description": "Report a technical problem", "emoji": "🛠️", @@ -75,6 +85,7 @@ }, { "id": "billing", + "channelPrefix": "", "name": "Billing and Purchases", "description": "Questions about purchases or payments", "emoji": "🧾", From 57f3dba826d20356d76024fbc75555d118eb4c67 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:05:48 -0400 Subject: [PATCH 14/59] Validate category prefixes and queue display configuration --- src/config.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/config.js b/src/config.js index d5f7c84..957b9b0 100644 --- a/src/config.js +++ b/src/config.js @@ -31,6 +31,27 @@ if (typeof settings?.ticketing?.channelPrefix !== 'string') { throw new Error('settings.ticketing.channelPrefix must be a string.'); } +const queueDisplay = settings?.ticketing?.queue?.display; +if (queueDisplay?.enabled) { + if (!settings.ticketing.queue?.enabled) { + throw new Error('ticketing.queue.display.enabled requires ticketing.queue.enabled to be true.'); + } + if (!/^\d{17,20}$/.test(String(queueDisplay.channelId ?? ''))) { + throw new Error('ticketing.queue.display.channelId must be a valid Discord channel ID when the queue display is enabled.'); + } + if ((queueDisplay.type ?? 'embed') !== 'embed') { + throw new Error('ticketing.queue.display.type currently supports only "embed".'); + } + const refreshSeconds = Number(queueDisplay.refreshIntervalSeconds ?? 60); + if (!Number.isFinite(refreshSeconds) || refreshSeconds < 15 || refreshSeconds > 86400) { + throw new Error('ticketing.queue.display.refreshIntervalSeconds must be between 15 and 86400.'); + } + const maxTickets = Number(queueDisplay.maxTickets ?? 15); + if (!Number.isInteger(maxTickets) || maxTickets < 1 || maxTickets > 25) { + throw new Error('ticketing.queue.display.maxTickets must be an integer between 1 and 25.'); + } +} + const categories = settings?.ticketing?.categories; if (!Array.isArray(categories) || categories.length < 1) { throw new Error('settings.ticketing.categories must contain at least one category.'); @@ -46,6 +67,9 @@ for (const category of categories) { } if (categoryIds.has(category.id)) throw new Error(`Duplicate ticket category id: ${category.id}`); categoryIds.add(category.id); + if (category.channelPrefix !== undefined && typeof category.channelPrefix !== 'string') { + throw new Error(`Category ${category.id} channelPrefix must be a string.`); + } if (!Array.isArray(category.questions)) category.questions = []; if (category.questions.length > 3) category.questions = category.questions.slice(0, 3); for (const question of category.questions) { From 37df09bd6ff74fc3c0229de083580bacaa3e51b0 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:05:55 -0400 Subject: [PATCH 15/59] Use configured priority order when rank values are omitted --- src/utils/priority.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/utils/priority.js b/src/utils/priority.js index 228af41..169063e 100644 --- a/src/utils/priority.js +++ b/src/utils/priority.js @@ -3,8 +3,10 @@ export function getPriorityLevel(priorityId, priorityLevels = []) { } export function getPriorityRank(priorityId, priorityLevels = []) { - const rank = Number(getPriorityLevel(priorityId, priorityLevels)?.rank ?? 0); - return Number.isFinite(rank) ? rank : 0; + const index = priorityLevels.findIndex((level) => level.id === priorityId); + if (index < 0) return 0; + const configuredRank = Number(priorityLevels[index].rank); + return Number.isFinite(configuredRank) ? configuredRank : index + 1; } export function formatPriority(priorityId, priorityLevels = []) { From b3fb4b8d583fd50f4b389c9bc6ae44e3c6450a26 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:06:05 -0400 Subject: [PATCH 16/59] Coordinate ticket ordering and queue display updates --- src/services/ticket-presentation.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/services/ticket-presentation.js diff --git a/src/services/ticket-presentation.js b/src/services/ticket-presentation.js new file mode 100644 index 0000000..d4a73db --- /dev/null +++ b/src/services/ticket-presentation.js @@ -0,0 +1,29 @@ +import { refreshQueueDisplay } from './queue-display.js'; +import { sortTicketChannelsByPriority } from './ticket-ordering.js'; + +/** + * Best-effort synchronization of visible channel order and the persistent + * queue embed. Presentation failures must never roll back ticket operations. + */ +export async function syncTicketPresentation({ guild, db, config, sortChannels = true }) { + const jobs = []; + if (sortChannels) jobs.push(['channel ordering', () => sortTicketChannelsByPriority({ guild, db, config })]); + jobs.push(['queue display', () => refreshQueueDisplay({ guild, db, config })]); + + const results = await Promise.allSettled(jobs.map(([, run]) => run())); + for (let index = 0; index < results.length; index += 1) { + const result = results[index]; + if (result.status === 'rejected') { + console.warn(\`[ticket-presentation] Unable to update \${jobs[index][0]} for guild \${guild.id}: \${result.reason?.message ?? result.reason}\`); + } + } + return results.every((result) => result.status === 'fulfilled'); +} + +export async function syncQueueDisplaysForClient(client, db, config) { + const guilds = [...client.guilds.cache.values()]; + await Promise.all(guilds.map((guild) => syncTicketPresentation({ + guild, db, config, sortChannels: true + }))); + return guilds.length; +} From 989f21659f886628b5a9eed7a2bcea0a71989f3c Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:07:45 -0400 Subject: [PATCH 17/59] Apply category prefixes and synchronize queue on creation and claims --- src/services/tickets.js | 51 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 47 insertions(+), 4 deletions(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index 3060289..ad36869 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -9,12 +9,51 @@ import { summarizeTicket } from './ai.js'; import { safeChannelName, truncate } from '../utils/text.js'; import { categoryForTicket, hasRequiredRoles, isAdmin, isStaff, memberId } from './permissions.js'; import { isWithinWorkingHours } from './schedule.js'; +import { formatPriority } from '../utils/priority.js'; +import { syncTicketPresentation } from './ticket-presentation.js'; const activeStatuses = new Set(['open', 'queued']); export function getCategory(config, categoryId) { return config.ticketing.categories.find((category) => category.id === categoryId) ?? null; } +function getChannelPrefix(config, category) { + const categoryPrefix = category?.channelPrefix; + if (typeof categoryPrefix === 'string' && categoryPrefix.trim()) return categoryPrefix; + return config.ticketing.channelPrefix ?? 'ticket-'; +} + +function ticketChannelName(config, category, ticketId, username) { + const idPart = ticketId === null || ticketId === undefined ? '' : `${ticketId}-`; + return safeChannelName(`${getChannelPrefix(config, category)}${idPart}${username || 'member'}`).slice(0, 100); +} + +async function updateOpeningTicketPriority(channel, ticketId, priority, config) { + try { + const messages = await channel.messages.fetch({ limit: 100 }); + const opening = [...messages.values()].find((message) => message.author.id === channel.client.user.id + && message.embeds.some((embed) => embed.fields?.some((field) => field.name === 'Ticket' && field.value === `#${ticketId}`))); + if (!opening) { + console.warn(`[tickets] Could not find the opening embed for ticket #${ticketId} to refresh its priority.`); + return false; + } + + const embeds = opening.embeds.map((existing) => { + if (!existing.fields?.some((field) => field.name === 'Ticket' && field.value === `#${ticketId}`)) return EmbedBuilder.from(existing); + const embed = EmbedBuilder.from(existing); + embed.setFields(existing.fields.map((field) => field.name === 'Priority' + ? { name: field.name, value: formatPriority(priority, config.priorityLevels), inline: field.inline } + : { name: field.name, value: field.value, inline: field.inline })); + return embed; + }); + await opening.edit({ embeds }); + return true; + } catch (error) { + console.warn(`[tickets] Unable to update the opening embed for ticket #${ticketId}: ${error.message}`); + return false; + } +} + export async function createTicket({ guild, user, member, categoryId, answers, db, config }) { const category = getCategory(config, categoryId); if (!category) throw new Error('That ticket category is no longer available. Re-open the panel and try again.'); @@ -40,8 +79,7 @@ export async function createTicket({ guild, user, member, categoryId, answers, d if (description) normalizedAnswers['Additional details'] = truncate(description, 1000); const safeOwner = safeChannelName(user.username || 'member').slice(0, 32); - const channelPrefix = config.ticketing.channelPrefix ?? 'ticket-'; - const channelName = safeChannelName(`${channelPrefix}${safeOwner}`); + const channelName = ticketChannelName(config, category, null, safeOwner); const overwrites = [ { id: guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel] }, { id: user.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.EmbedLinks] }, @@ -66,6 +104,7 @@ export async function createTicket({ guild, user, member, categoryId, answers, d const status = config.ticketing.queue?.enabled ? 'queued' : 'open'; const ticket = db.createTicket({ guildId: guild.id, channelId: channel.id, ownerId: user.id, categoryId: category.id, status, intake: normalizedAnswers }); savedTicket = ticket; + await channel.setName(ticketChannelName(config, category, ticket.id, safeOwner)); await channel.setTopic(`Ticket #${ticket.id} · Owner ${user.id} · Category ${category.id}`.slice(0, 1024)); const descriptionLines = Object.entries(normalizedAnswers).map(([label, value]) => `**${label}**\n${truncate(value, 700)}`); @@ -76,7 +115,7 @@ export async function createTicket({ guild, user, member, categoryId, answers, d .addFields( { name: 'Ticket', value: `#${ticket.id}`, inline: true }, { name: 'Status', value: status === 'queued' ? 'Waiting in queue' : 'Open', inline: true }, - { name: 'Priority', value: 'Normal', inline: true } + { name: 'Priority', value: formatPriority(ticket.priority, config.priorityLevels), inline: true } ) .setFooter({ text: config.app.footer || config.app.name }); const buttons = new ActionRowBuilder().addComponents( @@ -85,6 +124,7 @@ export async function createTicket({ guild, user, member, categoryId, answers, d ); const roleMentions = (category.supportRoleIds ?? []).filter((id) => guild.roles.cache.has(id)).map((id) => `<@&${id}>`).join(' '); await channel.send({ content: [roleMentions, `<@${user.id}>`].filter(Boolean).join(' '), embeds: [embed], components: [buttons], allowedMentions: { users: [user.id], roles: category.supportRoleIds ?? [] } }); + await syncTicketPresentation({ guild, db, config }); return { ticket, channel }; } catch (error) { if (savedTicket) db.deleteTicket(savedTicket.id); @@ -131,7 +171,8 @@ export async function claimTicket({ ticket, channel, member, db, config, allowQu guildId: ticket.guild_id, capacity: queueEnabled ? Number(config.ticketing.queue?.staffCapacity ?? 0) : 0, strictOrder: queueEnabled && Boolean(config.ticketing.queue?.strictOrder), - allowQueueJump + allowQueueJump, + priorityLevels: config.priorityLevels }); if (!result.ok) { if (result.reason === 'missing') throw new Error('This ticket record could not be found.'); @@ -145,6 +186,7 @@ export async function claimTicket({ ticket, channel, member, db, config, allowQu await channel.permissionOverwrites.edit(ticket.owner_id, { SendMessages: false }).catch(() => {}); } await channel.send({ embeds: [new EmbedBuilder().setColor(config.app.defaultColor || '#6D5AE6').setDescription(`🙋 This ticket was claimed by <@${memberId(member)}>.`)], allowedMentions: { users: [memberId(member)] } }); + await syncTicketPresentation({ guild: channel.guild, db, config, sortChannels: false }); return db.getTicketById(ticket.id); } @@ -161,6 +203,7 @@ export async function unclaimTicket({ ticket, channel, member, db, config }) { db.logStaffEvent({ guildId: ticket.guild_id, ticketId: ticket.id, staffId: memberId(member), action: 'unclaim' }); if (config.ticketing.claims?.lockOwnerAfterClaim) await channel.permissionOverwrites.edit(ticket.owner_id, { SendMessages: true }).catch(() => {}); await channel.send(`Ticket #${ticket.id} is back in the available queue. Previously claimed by <@${old}>.`); + await syncTicketPresentation({ guild: channel.guild, db, config, sortChannels: false }); } export async function closeTicket({ ticket, channel, member, reason = 'No reason provided.', db, config, guild }) { From f4f4407521bfa86f7293104b9622603de8bd1a85 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:08:13 -0400 Subject: [PATCH 18/59] Apply priority updates, category transitions, and lifecycle synchronization --- src/services/tickets.js | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index ad36869..3a58f72 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -281,6 +281,7 @@ export async function closeTicket({ ticket, channel, member, reason = 'No reason }).catch(() => {}); } } + await syncTicketPresentation({ guild, db, config }); return { ticket: db.getTicketById(ticket.id), transcript, summary }; } @@ -317,6 +318,7 @@ export async function deleteTicket({ ticket, channel, member, db, config, guild } await channel.delete(`Ticket #${ticket.id} deleted by ${member.user?.tag || memberId(member)}`); db.deleteTicket(ticket.id); + await syncTicketPresentation({ guild, db, config }); return ticket.id; } @@ -325,9 +327,13 @@ export async function setPriority({ ticket, channel, member, priority, db, confi if (!isStaff(member, config, category)) throw new Error('Only support staff can change priority.'); const configured = config.priorityLevels ?? []; if (!configured.some((item) => item.id === priority)) throw new Error('That priority is not configured.'); - db.updateTicket(ticket.id, { priority, last_activity_at: Date.now() }); - await channel.send(`Priority for ticket #${ticket.id} was changed to **${priority}** by <@${memberId(member)}>.`); - return db.getTicketById(ticket.id); + const updated = db.updateTicket(ticket.id, { priority, last_activity_at: Date.now() }); + await updateOpeningTicketPriority(channel, ticket.id, priority, config); + await channel.send(`Ticket #${ticket.id} priority changed to **${formatPriority(priority, configured)}** by <@${memberId(member)}>.`).catch((error) => { + console.warn(`[tickets] Unable to post priority change for ticket #${ticket.id}: ${error.message}`); + }); + await syncTicketPresentation({ guild: channel.guild, db, config }); + return updated; } export async function setCategory({ ticket, channel, member, categoryId, db, config }) { @@ -346,7 +352,12 @@ export async function setCategory({ ticket, channel, member, categoryId, db, con if (channel.guild.roles.cache.has(roleId)) await channel.permissionOverwrites.edit(roleId, { ViewChannel: true, SendMessages: true, ReadMessageHistory: true }).catch(() => {}); } db.updateTicket(ticket.id, { category_id: next.id, last_activity_at: Date.now() }); + const ownerName = (await channel.guild.client.users.fetch(ticket.owner_id).catch(() => null))?.username || 'member'; + await channel.setName(ticketChannelName(config, next, ticket.id, ownerName)).catch((error) => { + console.warn(`[tickets] Unable to apply category prefix for ticket #${ticket.id}: ${error.message}`); + }); await channel.send(`Ticket category changed to **${next.name}** by <@${memberId(member)}>.`); + await syncTicketPresentation({ guild: channel.guild, db, config }); return db.getTicketById(ticket.id); } @@ -438,6 +449,5 @@ export async function runInactivityMonitor(client) { export function formatTicketSummary(ticket, config) { const category = getCategory(config, ticket.category_id); - const priority = config.priorityLevels.find((level) => level.id === ticket.priority); - return `#${ticket.id} · ${category?.name ?? ticket.category_id} · ${priority?.emoji ?? ''} ${ticket.priority} · <@${ticket.owner_id}>`; + return `#${ticket.id} · ${category?.name ?? ticket.category_id} · ${formatPriority(ticket.priority, config.priorityLevels)} · <@${ticket.owner_id}>`; } From 15d44b6e544e55efc0e72ad5cf90a40fd3981aac Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:08:30 -0400 Subject: [PATCH 19/59] Apply category prefix and resynchronize queue on reopen --- src/services/tickets.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index 3a58f72..55e3fb5 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -292,13 +292,13 @@ export async function reopenTicket({ ticket, channel, member, db, config }) { const nextStatus = config.ticketing.queue?.enabled ? 'queued' : 'open'; db.updateTicket(ticket.id, { status: nextStatus, claimed_by: null, closed_at: null, closed_by: null, close_reason: null, last_activity_at: Date.now() }); const ownerName = (await channel.guild.client.users.fetch(ticket.owner_id).catch(() => null))?.username || 'member'; - const channelPrefix = config.ticketing.channelPrefix ?? 'ticket-'; - await channel.setName(safeChannelName(`${channelPrefix}${ticket.id}-${ownerName}`).slice(0, 100)).catch(() => {}); + await channel.setName(ticketChannelName(config, category, ticket.id, ownerName)).catch(() => {}); await channel.permissionOverwrites.edit(ticket.owner_id, { ViewChannel: true, SendMessages: true, ReadMessageHistory: true }).catch(() => {}); for (const userId of db.listParticipants(ticket.id)) { if (userId !== ticket.owner_id) await channel.permissionOverwrites.edit(userId, { ViewChannel: true, SendMessages: true, ReadMessageHistory: true }).catch(() => {}); } await channel.send(`🔓 Ticket #${ticket.id} was reopened by <@${memberId(member)}>. Status: **${nextStatus}**.`); + await syncTicketPresentation({ guild: channel.guild, db, config }); return db.getTicketById(ticket.id); } From 52eb30dc5ecc74adb8e568fcc0a767a28bbdd3ed Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:08:43 -0400 Subject: [PATCH 20/59] Refresh sorted tickets and queue embed on startup and schedule --- src/bot.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/bot.js b/src/bot.js index 89d3569..45948d0 100644 --- a/src/bot.js +++ b/src/bot.js @@ -3,6 +3,7 @@ import { config, validateRuntimeConfig } from './config.js'; import { Database } from './db/database.js'; import { handleInteraction } from './handlers/interactions.js'; import { markActivity, runInactivityMonitor } from './services/tickets.js'; +import { syncTicketPresentation, syncQueueDisplaysForClient } from './services/ticket-presentation.js'; validateRuntimeConfig(); const db = new Database(config.databasePath); @@ -16,6 +17,23 @@ client.config = config; client.once(Events.ClientReady, (readyClient) => { console.log(`[ready] ${readyClient.user.tag} online · shard ${readyClient.shard?.ids?.join(',') ?? 'single'} · db=${config.databasePath}`); console.log(`[ready] Queue ${config.ticketing.queue?.enabled ? 'enabled' : 'disabled'} · ${config.ticketing.categories.length} ticket categories loaded.`); + syncQueueDisplaysForClient(client, db, config).catch((error) => { + console.error('[ticket-presentation] Startup synchronization failed:', error); + }); + + const queueDisplay = config.ticketing.queue?.display; + if (queueDisplay?.enabled) { + const intervalMs = Math.max(15, Number(queueDisplay.refreshIntervalSeconds ?? 60)) * 1000; + const timer = setInterval(() => { + for (const guild of client.guilds.cache.values()) { + syncTicketPresentation({ guild, db, config, sortChannels: false }).catch((error) => { + console.error(`[queue-display] Refresh failed for guild ${guild.id}:`, error); + }); + } + }, intervalMs); + timer.unref(); + } + if (config.ticketing.inactivityMonitor?.enabled) { const intervalMs = Math.max(1, Number(config.ticketing.inactivityMonitor.checkIntervalMinutes ?? 5)) * 60_000; const timer = setInterval(() => runInactivityMonitor(client).catch((error) => console.error('[inactivity]', error)), intervalMs); @@ -43,6 +61,9 @@ client.on(Events.ChannelDelete, (channel) => { const ticket = db.getTicketByChannel(channel.id); if (ticket && ['open', 'queued'].includes(ticket.status)) { db.updateTicket(ticket.id, { status: 'closed', closed_at: Date.now(), close_reason: 'Ticket channel was deleted outside the bot.' }); + syncTicketPresentation({ guild: channel.guild, db, config }).catch((error) => { + console.error('[ticket-presentation] Failed after an external channel deletion:', error); + }); } } catch (error) { console.error('[channelDelete] Could not reconcile deleted ticket:', error); From 48ddd7e286bb77975cece5c1ec81e768682462e2 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:09:08 -0400 Subject: [PATCH 21/59] Fix queue-display.js template literals --- src/services/queue-display.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/services/queue-display.js b/src/services/queue-display.js index 79460e1..5398beb 100644 --- a/src/services/queue-display.js +++ b/src/services/queue-display.js @@ -11,18 +11,18 @@ function buildQueueEmbed({ guild, queued, config, display }) { const lines = shown.map((ticket, index) => { const category = config.ticketing.categories.find((item) => item.id === ticket.category_id); const channel = guild.channels.cache.get(ticket.channel_id); - const channelLabel = channel ? \`<#\${channel.id}>\` : \`Ticket #\${ticket.id}\`; + const channelLabel = channel ? `<#${channel.id}>` : `Ticket #${ticket.id}`; const categoryLabel = category?.name ?? ticket.category_id; - return \`**\${index + 1}.** \${formatPriority(ticket.priority, config.priorityLevels)} · \${channelLabel} · \${categoryLabel} · <@\${ticket.owner_id}>\`; + return `**${index + 1}.** ${formatPriority(ticket.priority, config.priorityLevels)} · ${channelLabel} · ${categoryLabel} · <@${ticket.owner_id}>`; }); if (queued.length === 0) lines.push('There are currently no tickets waiting for support.'); - if (queued.length > shown.length) lines.push(\`\\n…and \${queued.length - shown.length} more waiting ticket(s).\`); + if (queued.length > shown.length) lines.push(`\n…and ${queued.length - shown.length} more waiting ticket(s).`); return new EmbedBuilder() .setColor(config.app.defaultColor || '#6D5AE6') .setTitle(String(display.title || 'Support Queue').slice(0, 256)) - .setDescription(lines.join('\\n').slice(0, 4096)) - .setFooter({ text: \`\${queued.length} waiting · Updates every \${Math.max(15, Number(display.refreshIntervalSeconds ?? 60))} seconds\` }) + .setDescription(lines.join('\n').slice(0, 4096)) + .setFooter({ text: `${queued.length} waiting · Updates every ${Math.max(15, Number(display.refreshIntervalSeconds ?? 60))} seconds` }) .setTimestamp(); } @@ -36,11 +36,11 @@ export async function refreshQueueDisplay({ guild, db, config }) { if ((display.type || 'embed') !== 'embed') throw new Error('ticketing.queue.display.type currently supports only "embed".'); const channel = await guild.channels.fetch(display.channelId).catch((error) => { - console.warn(\`[queue-display] Unable to fetch configured channel \${display.channelId} in guild \${guild.id}: \${error.message}\`); + console.warn(`[queue-display] Unable to fetch configured channel ${display.channelId} in guild ${guild.id}: ${error.message}`); return null; }); if (!channel?.isTextBased?.() || typeof channel.send !== 'function') { - console.warn(\`[queue-display] Configured channel \${display.channelId} is not a sendable text channel in guild \${guild.id}.\`); + console.warn(`[queue-display] Configured channel ${display.channelId} is not a sendable text channel in guild ${guild.id}.`); return false; } From 1146227d828946f2b608edf923a27fe430d2a552 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:09:10 -0400 Subject: [PATCH 22/59] Fix ticket-presentation.js template literals --- src/services/ticket-presentation.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/ticket-presentation.js b/src/services/ticket-presentation.js index d4a73db..a79e645 100644 --- a/src/services/ticket-presentation.js +++ b/src/services/ticket-presentation.js @@ -14,7 +14,7 @@ export async function syncTicketPresentation({ guild, db, config, sortChannels = for (let index = 0; index < results.length; index += 1) { const result = results[index]; if (result.status === 'rejected') { - console.warn(\`[ticket-presentation] Unable to update \${jobs[index][0]} for guild \${guild.id}: \${result.reason?.message ?? result.reason}\`); + console.warn(`[ticket-presentation] Unable to update ${jobs[index][0]} for guild ${guild.id}: ${result.reason?.message ?? result.reason}`); } } return results.every((result) => result.status === 'fulfilled'); From 4d5a8f4a03b9810053055c68d63dbb0b6908550c Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:09:20 -0400 Subject: [PATCH 23/59] Test migration of new settings into existing categories --- tests/settings-migration.test.js | 36 ++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/tests/settings-migration.test.js b/tests/settings-migration.test.js index 04ab1f8..341f748 100644 --- a/tests/settings-migration.test.js +++ b/tests/settings-migration.test.js @@ -44,3 +44,39 @@ test('settings migration rejects non-object inputs', () => { assert.throws(() => addMissingDefaults(null, {}), TypeError); assert.throws(() => addMissingDefaults({}, []), TypeError); }); + +test('settings migration adds new fields to existing keyed category objects', () => { + const settings = { + ticketing: { + categories: [ + { id: 'general', name: 'My General Queue', customValue: true }, + { id: 'custom', name: 'Custom Category' } + ] + }, + priorityLevels: [ + { id: 'urgent', label: 'Critical', emoji: '‼️' }, + { id: 'custom-priority', label: 'Custom' } + ] + }; + const defaults = { + ticketing: { + categories: [ + { id: 'general', name: 'General Support', channelPrefix: '' }, + { id: 'technical', name: 'Technical Support', channelPrefix: '' } + ] + }, + priorityLevels: [ + { id: 'urgent', label: 'Urgent', rank: 4, emoji: '🔴' }, + { id: 'normal', label: 'Normal', rank: 2, emoji: '🔵' } + ] + }; + + assert.equal(addMissingDefaults(settings, defaults), true); + assert.equal(settings.ticketing.categories[0].name, 'My General Queue'); + assert.equal(settings.ticketing.categories[0].channelPrefix, ''); + assert.equal(settings.ticketing.categories[0].customValue, true); + assert.deepEqual(settings.ticketing.categories[1], { id: 'custom', name: 'Custom Category' }); + assert.equal(settings.priorityLevels[0].label, 'Critical'); + assert.equal(settings.priorityLevels[0].rank, 4); + assert.deepEqual(settings.priorityLevels[1], { id: 'custom-priority', label: 'Custom' }); +}); From 278d1b14b96b00bf00aeee41bc663fdef92b3f38 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:09:31 -0400 Subject: [PATCH 24/59] Test priority-based Discord channel ordering --- tests/priority.test.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/priority.test.js b/tests/priority.test.js index ad67bfa..76b0711 100644 --- a/tests/priority.test.js +++ b/tests/priority.test.js @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { compareTicketsByPriority, formatPriority, getPriorityRank, sortTicketsByPriority } from '../src/utils/priority.js'; +import { buildPriorityPositionUpdates } from '../src/services/ticket-ordering.js'; const priorityLevels = [ { id: 'low', label: 'Low', rank: 1, emoji: '🟢' }, @@ -39,3 +40,20 @@ test('priority display uses configured emoji and label', () => { assert.equal(formatPriority('urgent', priorityLevels), '🔴 Urgent'); assert.equal(formatPriority('custom', priorityLevels), 'custom'); }); + +test('channel ordering sorts tickets into their existing positions within each parent', () => { + const entries = [ + { ticket: { id: 1, priority: 'low', created_at: 1 }, channel: { id: 'low-channel', parentId: 'support', position: 2 } }, + { ticket: { id: 2, priority: 'urgent', created_at: 2 }, channel: { id: 'urgent-channel', parentId: 'support', position: 4 } }, + { ticket: { id: 3, priority: 'high', created_at: 3 }, channel: { id: 'high-channel', parentId: 'support', position: 3 } }, + { ticket: { id: 4, priority: 'urgent', created_at: 4 }, channel: { id: 'other-category', parentId: 'billing', position: 1 } } + ]; + + assert.deepEqual( + buildPriorityPositionUpdates(entries, priorityLevels), + [ + { channel: 'urgent-channel', position: 2 }, + { channel: 'low-channel', position: 4 } + ] + ); +}); From c75b773811cc59cdef579d8e77ba5def0c681732 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:09:42 -0400 Subject: [PATCH 25/59] Use configured priority order in queue commands --- src/services/tickets.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index 55e3fb5..4b8a024 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -401,7 +401,7 @@ export async function markActivity({ ticket, author, db, config }) { } export async function takeNextQueuedTicket({ guild, member, db, config }) { - const queue = db.queueList(guild.id).filter((item) => isStaff(member, config, categoryForTicket(item, config))); + const queue = db.queueList(guild.id, config.priorityLevels).filter((item) => isStaff(member, config, categoryForTicket(item, config))); if (!queue.length) { if (!isStaff(member, config)) throw new Error('Only support staff can take queued tickets.'); throw new Error('There are no queued tickets assigned to a support category you can access.'); @@ -417,7 +417,7 @@ export async function takeNextQueuedTicket({ guild, member, db, config }) { } export function listQueue(db, guildId, config) { - return db.queueList(guildId).map((ticket, index) => ({ ...ticket, position: index + 1, category: getCategory(config, ticket.category_id)?.name ?? ticket.category_id })); + return db.queueList(guildId, config.priorityLevels).map((ticket, index) => ({ ...ticket, position: index + 1, category: getCategory(config, ticket.category_id)?.name ?? ticket.category_id })); } export async function runInactivityMonitor(client) { From 5db87b1888480ead0d774a8337f37d43e02b886d Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:10:24 -0400 Subject: [PATCH 26/59] Document category prefixes, priority ordering, and queue embed --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cd642b1..db84a0c 100644 --- a/README.md +++ b/README.md @@ -79,9 +79,13 @@ Once online, run `/ticket-panel` in the channel where users should open tickets. | `channels.ticketLogsId` | Channel where ticket events are logged | | `ticketing.categories` | The ticket categories shown in the panel | | `ticketing.channelPrefix` | Prefix for new and reopened ticket channels (default: `ticket-`; for example, `support-`) | +| `ticketing.categories[].channelPrefix` | Optional per-category prefix such as `general-`; an empty value inherits `ticketing.channelPrefix` | | `ticketing.maxOpenPerUser` | Max open tickets per user (`0` = unlimited) | | `ticketing.creationCooldownSeconds` | Minimum seconds between ticket opens | | `ticketing.queue.enabled` | Turn the persistent queue on or off | +| `ticketing.queue.strictOrder` | Only allow claiming the highest-ranked waiting ticket | +| `ticketing.queue.display` | Optional priority-ordered queue embed, automatically created/edited in `channelId` and refreshed on the configured interval; its message ID is persisted in SQLite so restarts edit the same message | +| `priorityLevels[].rank` | Numeric priority weight; higher ranks sort before lower ranks, with oldest tickets first within the same rank | | `ticketing.queue.staffCapacity` | Max active claims per staff member (`0` = no cap) | | `ticketing.workingHours` | Restrict ticket opening to a time schedule | | `ticketing.inactivityMonitor` | Alert staff on stale tickets | @@ -90,7 +94,7 @@ Once online, run `/ticket-panel` in the channel where users should open tickets. | `features.suggestions` | Enable the suggestion workflow | | `features.reviews` | Let users rate their support experience | -Category IDs must be letters, digits, underscores, or hyphens (max 40 chars). Each category can have a `parentCategoryId`, `supportRoleIds`, `requiredRoleIds`, and up to three `questions`. +Category IDs must be letters, digits, underscores, or hyphens (max 40 chars). Each category can have a `parentCategoryId`, `supportRoleIds`, `requiredRoleIds`, and up to three `questions`. Each category can also set `channelPrefix` to override the global prefix; for example, `channelPrefix`: `general-` gives that category channels such as `general-12-someone`. Configure the optional queue embed under `ticketing.queue.display`; set `enabled`, `type: "embed"`, and a text `channelId`. The bot creates the message on first use and edits the stored message on restarts and at `refreshIntervalSeconds`. ## Commands From 7aa085ba723fb0aae66f3331a97a6f208614f5a8 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:11:27 -0400 Subject: [PATCH 27/59] Persist ticket opening embed message IDs --- src/db/database.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/db/database.js b/src/db/database.js index 0c47bf6..9c4cf93 100644 --- a/src/db/database.js +++ b/src/db/database.js @@ -38,7 +38,8 @@ export class Database { close_reason TEXT, last_activity_at INTEGER NOT NULL, inactivity_alerted_at INTEGER, - transcript_path TEXT + transcript_path TEXT, + opening_message_id TEXT ); CREATE INDEX IF NOT EXISTS idx_tickets_owner_status ON tickets(guild_id, owner_id, status); CREATE INDEX IF NOT EXISTS idx_tickets_queue ON tickets(guild_id, status, priority, created_at); @@ -139,6 +140,9 @@ export class Database { if (!ticketColumns.has('transcript_path')) { this.sqlite.exec('ALTER TABLE tickets ADD COLUMN transcript_path TEXT'); } + if (!ticketColumns.has('opening_message_id')) { + this.sqlite.exec('ALTER TABLE tickets ADD COLUMN opening_message_id TEXT'); + } } createTicket(data) { @@ -178,7 +182,7 @@ export class Database { } updateTicket(id, patch) { - const allowed = new Set(['status','priority','tags_json','intake_json','claimed_by','first_response_at','closed_at','closed_by','close_reason','last_activity_at','inactivity_alerted_at','transcript_path']); + const allowed = new Set(['status','priority','tags_json','intake_json','claimed_by','first_response_at','closed_at','closed_by','close_reason','last_activity_at','inactivity_alerted_at','transcript_path','opening_message_id']); const entries = Object.entries(patch).filter(([key]) => allowed.has(key)); if (!entries.length) return this.getTicketById(id); const sql = entries.map(([key]) => `${key}=@${key}`).join(', '); From 9c2a0da78c2e637972fd96425e504758d4501e1d Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:11:42 -0400 Subject: [PATCH 28/59] Update ticket priority embeds by persisted message ID --- src/services/tickets.js | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index 4b8a024..34a6d97 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -28,18 +28,25 @@ function ticketChannelName(config, category, ticketId, username) { return safeChannelName(`${getChannelPrefix(config, category)}${idPart}${username || 'member'}`).slice(0, 100); } -async function updateOpeningTicketPriority(channel, ticketId, priority, config) { +async function updateOpeningTicketPriority(channel, ticket, priority, config, db) { try { - const messages = await channel.messages.fetch({ limit: 100 }); - const opening = [...messages.values()].find((message) => message.author.id === channel.client.user.id - && message.embeds.some((embed) => embed.fields?.some((field) => field.name === 'Ticket' && field.value === `#${ticketId}`))); + let opening = null; + if (ticket.opening_message_id) { + opening = await channel.messages.fetch(ticket.opening_message_id).catch(() => null); + } + if (!opening) { + const messages = await channel.messages.fetch({ limit: 100 }); + opening = [...messages.values()].find((message) => message.author.id === channel.client.user.id + && message.embeds.some((embed) => embed.fields?.some((field) => field.name === 'Ticket' && field.value === `#${ticket.id}`))); + } if (!opening) { - console.warn(`[tickets] Could not find the opening embed for ticket #${ticketId} to refresh its priority.`); + console.warn(`[tickets] Could not find the opening embed for ticket #${ticket.id} to refresh its priority.`); return false; } + if (!ticket.opening_message_id) db.updateTicket(ticket.id, { opening_message_id: opening.id }); const embeds = opening.embeds.map((existing) => { - if (!existing.fields?.some((field) => field.name === 'Ticket' && field.value === `#${ticketId}`)) return EmbedBuilder.from(existing); + if (!existing.fields?.some((field) => field.name === 'Ticket' && field.value === `#${ticket.id}`)) return EmbedBuilder.from(existing); const embed = EmbedBuilder.from(existing); embed.setFields(existing.fields.map((field) => field.name === 'Priority' ? { name: field.name, value: formatPriority(priority, config.priorityLevels), inline: field.inline } @@ -49,7 +56,7 @@ async function updateOpeningTicketPriority(channel, ticketId, priority, config) await opening.edit({ embeds }); return true; } catch (error) { - console.warn(`[tickets] Unable to update the opening embed for ticket #${ticketId}: ${error.message}`); + console.warn(`[tickets] Unable to update the opening embed for ticket #${ticket.id}: ${error.message}`); return false; } } @@ -123,7 +130,8 @@ export async function createTicket({ guild, user, member, categoryId, answers, d new ButtonBuilder().setCustomId('ticket:close').setLabel('Close').setStyle(ButtonStyle.Secondary).setEmoji('🔒') ); const roleMentions = (category.supportRoleIds ?? []).filter((id) => guild.roles.cache.has(id)).map((id) => `<@&${id}>`).join(' '); - await channel.send({ content: [roleMentions, `<@${user.id}>`].filter(Boolean).join(' '), embeds: [embed], components: [buttons], allowedMentions: { users: [user.id], roles: category.supportRoleIds ?? [] } }); + const openingMessage = await channel.send({ content: [roleMentions, `<@${user.id}>`].filter(Boolean).join(' '), embeds: [embed], components: [buttons], allowedMentions: { users: [user.id], roles: category.supportRoleIds ?? [] } }); + db.updateTicket(ticket.id, { opening_message_id: openingMessage.id }); await syncTicketPresentation({ guild, db, config }); return { ticket, channel }; } catch (error) { @@ -328,7 +336,7 @@ export async function setPriority({ ticket, channel, member, priority, db, confi const configured = config.priorityLevels ?? []; if (!configured.some((item) => item.id === priority)) throw new Error('That priority is not configured.'); const updated = db.updateTicket(ticket.id, { priority, last_activity_at: Date.now() }); - await updateOpeningTicketPriority(channel, ticket.id, priority, config); + await updateOpeningTicketPriority(channel, ticket, priority, config, db); await channel.send(`Ticket #${ticket.id} priority changed to **${formatPriority(priority, configured)}** by <@${memberId(member)}>.`).catch((error) => { console.warn(`[tickets] Unable to post priority change for ticket #${ticket.id}: ${error.message}`); }); From 9e4bedbe2209fcb8efad680211e7430dc01bade8 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:11:54 -0400 Subject: [PATCH 29/59] Order priority command choices from highest to lowest --- src/commands/definitions.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/commands/definitions.js b/src/commands/definitions.js index 0fea13a..24e7657 100644 --- a/src/commands/definitions.js +++ b/src/commands/definitions.js @@ -1,8 +1,9 @@ import { SlashCommandBuilder } from 'discord.js'; +import { getPriorityRank } from '../utils/priority.js'; export function buildCommands(config) { const categoryChoices = config.ticketing.categories.slice(0, 25).map((item) => ({ name: item.name, value: item.id })); - const priorities = config.priorityLevels.slice(0, 25).map((item) => ({ name: `${item.emoji ?? ''} ${item.label}`.trim(), value: item.id })); + const priorities = [...config.priorityLevels].sort((a, b) => getPriorityRank(b.id, config.priorityLevels) - getPriorityRank(a.id, config.priorityLevels)).slice(0, 25).map((item) => ({ name: `${item.emoji ?? ''} ${item.label}`.trim(), value: item.id })); const commands = [ new SlashCommandBuilder().setName('ping').setDescription('Check the bot response time.'), new SlashCommandBuilder().setName('help').setDescription('Show the support bot command guide.'), From 69842bff443f66e56388360599859f9077145a4f Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:12:01 -0400 Subject: [PATCH 30/59] Show priority label and reorder confirmation to staff --- src/handlers/interactions.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/handlers/interactions.js b/src/handlers/interactions.js index f0d4930..3f10d68 100644 --- a/src/handlers/interactions.js +++ b/src/handlers/interactions.js @@ -9,6 +9,7 @@ import { renderTranscript } from '../services/transcripts.js'; import { canManageTicket, isAdmin, isStaff, requireStaff, categoryForTicket } from '../services/permissions.js'; import { formatDuration, parseMoneyToMinorUnits, truncate } from '../utils/text.js'; import { calculate } from '../utils/calculator.js'; +import { formatPriority } from '../utils/priority.js'; const ephemeral = { ephemeral: true }; const errorText = (error) => error instanceof Error ? error.message : 'An unexpected error occurred.'; @@ -138,7 +139,7 @@ async function handleSlashCommand(interaction) { if (name === 'ticket-priority') { const priority = interaction.options.getString('level', true); await setPriority({ ticket, channel, member, priority, db, config }); - return sendReply(interaction, `Ticket #${ticket.id} priority is now **${priority}**.`); + return sendReply(interaction, `Ticket #${ticket.id} priority is now **${formatPriority(priority, config.priorityLevels)}**. Ticket channels and queue order have been refreshed.`); } if (name === 'ticket-category') { const categoryId = interaction.options.getString('category', true); From 6a570821049050b629640a1fcbea56b6ac1226c1 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:15:55 -0400 Subject: [PATCH 31/59] Export and harden queue embed formatting --- src/services/queue-display.js | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/services/queue-display.js b/src/services/queue-display.js index 5398beb..012bca2 100644 --- a/src/services/queue-display.js +++ b/src/services/queue-display.js @@ -5,23 +5,32 @@ function isUnknownMessage(error) { return Number(error?.code ?? error?.rawError?.code) === 10008; } -function buildQueueEmbed({ guild, queued, config, display }) { +export function buildQueueEmbed({ guild, queued, config, display }) { const maxTickets = Math.min(25, Math.max(1, Number(display.maxTickets ?? 15))); - const shown = queued.slice(0, maxTickets); - const lines = shown.map((ticket, index) => { + const lines = []; + let shownCount = 0; + + for (const ticket of queued.slice(0, maxTickets)) { const category = config.ticketing.categories.find((item) => item.id === ticket.category_id); const channel = guild.channels.cache.get(ticket.channel_id); const channelLabel = channel ? `<#${channel.id}>` : `Ticket #${ticket.id}`; const categoryLabel = category?.name ?? ticket.category_id; - return `**${index + 1}.** ${formatPriority(ticket.priority, config.priorityLevels)} · ${channelLabel} · ${categoryLabel} · <@${ticket.owner_id}>`; - }); - if (queued.length === 0) lines.push('There are currently no tickets waiting for support.'); - if (queued.length > shown.length) lines.push(`\n…and ${queued.length - shown.length} more waiting ticket(s).`); + const line = `**${shownCount + 1}.** ${formatPriority(ticket.priority, config.priorityLevels)} · ${channelLabel} · ${categoryLabel} · <@${ticket.owner_id}>`; + if ([...lines, line].join('\\n').length > 3900) break; + lines.push(line); + shownCount += 1; + } + + if (queued.length === 0) { + lines.push('There are currently no tickets waiting for support.'); + } else if (shownCount < queued.length) { + lines.push(`\\n…and ${queued.length - shownCount} more waiting ticket(s).`); + } return new EmbedBuilder() .setColor(config.app.defaultColor || '#6D5AE6') .setTitle(String(display.title || 'Support Queue').slice(0, 256)) - .setDescription(lines.join('\n').slice(0, 4096)) + .setDescription(lines.join('\\n').slice(0, 4096)) .setFooter({ text: `${queued.length} waiting · Updates every ${Math.max(15, Number(display.refreshIntervalSeconds ?? 60))} seconds` }) .setTimestamp(); } From 022c7cbf7de4fff1c0830d2c01fe6c059754196c Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:16:10 -0400 Subject: [PATCH 32/59] Fix queue embed newline separators --- src/services/queue-display.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/services/queue-display.js b/src/services/queue-display.js index 012bca2..72ed66f 100644 --- a/src/services/queue-display.js +++ b/src/services/queue-display.js @@ -16,7 +16,7 @@ export function buildQueueEmbed({ guild, queued, config, display }) { const channelLabel = channel ? `<#${channel.id}>` : `Ticket #${ticket.id}`; const categoryLabel = category?.name ?? ticket.category_id; const line = `**${shownCount + 1}.** ${formatPriority(ticket.priority, config.priorityLevels)} · ${channelLabel} · ${categoryLabel} · <@${ticket.owner_id}>`; - if ([...lines, line].join('\\n').length > 3900) break; + if ([...lines, line].join('\n').length > 3900) break; lines.push(line); shownCount += 1; } @@ -24,13 +24,13 @@ export function buildQueueEmbed({ guild, queued, config, display }) { if (queued.length === 0) { lines.push('There are currently no tickets waiting for support.'); } else if (shownCount < queued.length) { - lines.push(`\\n…and ${queued.length - shownCount} more waiting ticket(s).`); + lines.push(`\n…and ${queued.length - shownCount} more waiting ticket(s).`); } return new EmbedBuilder() .setColor(config.app.defaultColor || '#6D5AE6') .setTitle(String(display.title || 'Support Queue').slice(0, 256)) - .setDescription(lines.join('\\n').slice(0, 4096)) + .setDescription(lines.join('\n').slice(0, 4096)) .setFooter({ text: `${queued.length} waiting · Updates every ${Math.max(15, Number(display.refreshIntervalSeconds ?? 60))} seconds` }) .setTimestamp(); } From d063826e32543e55916aea844c6aabc22f6c29b3 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:16:27 -0400 Subject: [PATCH 33/59] Test persistent queue embed creation and editing --- tests/queue-display.test.js | 117 ++++++++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 tests/queue-display.test.js diff --git a/tests/queue-display.test.js b/tests/queue-display.test.js new file mode 100644 index 0000000..0ed0b84 --- /dev/null +++ b/tests/queue-display.test.js @@ -0,0 +1,117 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { buildQueueEmbed, refreshQueueDisplay } from '../src/services/queue-display.js'; + +const config = { + app: { defaultColor: '#6D5AE6' }, + priorityLevels: [ + { id: 'low', label: 'Low', rank: 1, emoji: '🟢' }, + { id: 'normal', label: 'Normal', rank: 2, emoji: '🔵' }, + { id: 'high', label: 'High', rank: 3, emoji: '🟠' }, + { id: 'urgent', label: 'Urgent', rank: 4, emoji: '🔴' } + ], + ticketing: { + categories: [ + { id: 'general', name: 'General Support' }, + { id: 'billing', name: 'Billing' } + ], + queue: { + enabled: true, + display: { + enabled: true, + type: 'embed', + channelId: '12345678901234567', + refreshIntervalSeconds: 60, + maxTickets: 15, + title: 'Support Queue' + } + } + } +}; + +function makeTicket(id, priority, category = 'general') { + return { id, owner_id: String(9000 + id), channel_id: String(8000 + id), category_id: category, priority, created_at: id }; +} + +test('queue embed displays queued tickets in the supplied priority order', () => { + const queued = [ + makeTicket(2, 'urgent', 'billing'), + makeTicket(1, 'high'), + makeTicket(3, 'low') + ]; + const guild = { + channels: { + cache: new Map([ + ['8002', { id: '8002' }], + ['8001', { id: '8001' }], + ['8003', { id: '8003' }] + ]) + } + }; + + const embed = buildQueueEmbed({ guild, queued, config, display: config.ticketing.queue.display }).toJSON(); + assert.equal(embed.title, 'Support Queue'); + assert.ok(embed.description.indexOf('Urgent') < embed.description.indexOf('High')); + assert.ok(embed.description.indexOf('High') < embed.description.indexOf('Low')); + assert.match(embed.description, /Billing/); + assert.match(embed.footer.text, /3 waiting/); +}); + +test('queue embed reports an empty queue clearly', () => { + const embed = buildQueueEmbed({ + guild: { channels: { cache: new Map() } }, + queued: [], + config, + display: config.ticketing.queue.display + }).toJSON(); + assert.match(embed.description, /no tickets waiting/); +}); + +test('refresh edits the saved queue message instead of posting a duplicate', async () => { + let editedPayload; + let created = false; + const savedMessage = { + id: '77777777777777777', + async edit(payload) { editedPayload = payload; } + }; + const channel = { + id: config.ticketing.queue.display.channelId, + isTextBased: () => true, + async send() { created = true; throw new Error('Should edit the stored message'); }, + messages: { async fetch(id) { assert.equal(id, savedMessage.id); return savedMessage; } } + }; + const db = { + queueList: () => [makeTicket(10, 'urgent')], + getQueueStatusMessage: () => ({ channel_id: channel.id, message_id: savedMessage.id }), + saveQueueStatusMessage() { throw new Error('Existing message should not be replaced'); } + }; + const guild = { id: 'guild-id', channels: { fetch: async () => channel, cache: new Map() } }; + + assert.equal(await refreshQueueDisplay({ guild, db, config }), true); + assert.equal(created, false); + assert.ok(editedPayload.embeds[0].toJSON().description.includes('Urgent')); + assert.deepEqual(editedPayload.allowedMentions, { parse: [] }); +}); + +test('refresh recreates and stores a message that was deleted', async () => { + let stored; + let saved = null; + const missing = Object.assign(new Error('Unknown Message'), { code: 10008 }); + const createdMessage = { id: '88888888888888888' }; + const channel = { + id: config.ticketing.queue.display.channelId, + isTextBased: () => true, + async send(payload) { stored = payload; return createdMessage; }, + messages: { async fetch() { throw missing; } } + }; + const db = { + queueList: () => [], + getQueueStatusMessage: () => ({ channel_id: channel.id, message_id: 'old-message' }), + saveQueueStatusMessage(guildId, channelId, messageId) { saved = { guildId, channelId, messageId }; } + }; + const guild = { id: 'guild-id', channels: { fetch: async () => channel, cache: new Map() } }; + + assert.equal(await refreshQueueDisplay({ guild, db, config }), true); + assert.equal(saved.messageId, createdMessage.id); + assert.match(stored.embeds[0].toJSON().description, /no tickets waiting/); +}); From 3d43d2e6d868b20a45faec29ad60d1eed2741aad Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:16:50 -0400 Subject: [PATCH 34/59] Test database priority ordering and strict claims --- tests/database-priority.test.js | 63 +++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 tests/database-priority.test.js diff --git a/tests/database-priority.test.js b/tests/database-priority.test.js new file mode 100644 index 0000000..6fda0e5 --- /dev/null +++ b/tests/database-priority.test.js @@ -0,0 +1,63 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { Database } from '../src/db/database.js'; + +const priorityLevels = [ + { id: 'low', label: 'Low', rank: 1 }, + { id: 'normal', label: 'Normal', rank: 2 }, + { id: 'high', label: 'High', rank: 3 }, + { id: 'urgent', label: 'Urgent', rank: 4 } +]; + +async function createTestDatabase(t) { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'realms-tickets-priority-')); + const db = new Database(path.join(directory, 'tickets.sqlite')); + t.after(async () => { + db.close(); + await fs.rm(directory, { recursive: true, force: true }); + }); + return db; +} + +test('database queue list follows configured ranks and keeps FIFO ordering within a rank', async (t) => { + const db = await createTestDatabase(t); + const priorities = ['low', 'urgent', 'high', 'urgent', 'normal']; + priorities.forEach((priority, index) => { + const ticket = db.createTicket({ + guildId: 'guild', + channelId: 'channel-' + (index + 1), + ownerId: 'owner-' + (index + 1), + categoryId: 'general', + status: 'queued' + }); + db.updateTicket(ticket.id, { priority }); + }); + + assert.deepEqual(db.queueList('guild', priorityLevels).map((ticket) => ticket.priority), + ['urgent', 'urgent', 'high', 'normal', 'low']); + assert.deepEqual(db.queueList('guild', priorityLevels).map((ticket) => ticket.id), + [2, 4, 3, 5, 1]); +}); + +test('strict queue claiming rejects a lower-priority ticket until the highest one is claimed', async (t) => { + const db = await createTestDatabase(t); + const low = db.createTicket({ guildId: 'guild', channelId: 'low', ownerId: 'owner-low', categoryId: 'general', status: 'queued' }); + const urgent = db.createTicket({ guildId: 'guild', channelId: 'urgent', ownerId: 'owner-urgent', categoryId: 'general', status: 'queued' }); + db.updateTicket(low.id, { priority: 'low' }); + db.updateTicket(urgent.id, { priority: 'urgent' }); + + const rejected = db.claimTicketAtomically({ + ticketId: low.id, staffId: 'staff', guildId: 'guild', strictOrder: true, priorityLevels + }); + assert.deepEqual(rejected, { ok: false, reason: 'order', nextTicketId: urgent.id }); + + const claimed = db.claimTicketAtomically({ + ticketId: urgent.id, staffId: 'staff', guildId: 'guild', strictOrder: true, priorityLevels + }); + assert.equal(claimed.ok, true); + assert.equal(claimed.ticket.status, 'open'); + assert.deepEqual(db.queueList('guild', priorityLevels).map((ticket) => ticket.id), [low.id]); +}); From e90f5efacf0740031c31a75b02a6743c7a3d0b57 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:17:06 -0400 Subject: [PATCH 35/59] Add robust ticket channel prefix and name builder --- src/utils/ticket-channel-name.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/utils/ticket-channel-name.js diff --git a/src/utils/ticket-channel-name.js b/src/utils/ticket-channel-name.js new file mode 100644 index 0000000..73ca79b --- /dev/null +++ b/src/utils/ticket-channel-name.js @@ -0,0 +1,24 @@ +function slug(value = '') { + return String(value).normalize('NFKD').toLowerCase() + .replace(/[^a-z0-9 -]/g, '').trim().replace(/[\s-]+/g, '-').replace(/^-+|-+$/g, ''); +} + +export function getConfiguredChannelPrefix(config, category) { + const categoryPrefix = category?.channelPrefix; + if (typeof categoryPrefix === 'string' && categoryPrefix.trim()) return categoryPrefix; + return config.ticketing.channelPrefix ?? 'ticket-'; +} + +/** + * Keeps the ticket ID and owner visible even if a configured prefix is long. + * Discord channel names are limited to 100 characters; this bot's safe slug + * convention uses a 90-character ceiling for additional room. + */ +export function buildTicketChannelName(prefix, username, ticketId = null) { + const safePrefix = slug(prefix); + const safeOwner = slug(username) || 'member'; + const idPart = ticketId === null || ticketId === undefined ? '' : String(ticketId).replace(/[^0-9]/g, ''); + const suffix = [idPart, safeOwner].filter(Boolean).join('-'); + const prefixBudget = Math.max(0, 90 - suffix.length - (safePrefix ? 1 : 0)); + return [safePrefix.slice(0, prefixBudget), suffix].filter(Boolean).join('-').slice(0, 90) || 'ticket'; +} From eda438fd1d5509119ec3f4cd034e700f128b15e6 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:17:13 -0400 Subject: [PATCH 36/59] Use tested safe channel-name builder for category prefixes --- src/services/tickets.js | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index 34a6d97..8c0969f 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -10,6 +10,7 @@ import { safeChannelName, truncate } from '../utils/text.js'; import { categoryForTicket, hasRequiredRoles, isAdmin, isStaff, memberId } from './permissions.js'; import { isWithinWorkingHours } from './schedule.js'; import { formatPriority } from '../utils/priority.js'; +import { buildTicketChannelName, getConfiguredChannelPrefix } from '../utils/ticket-channel-name.js'; import { syncTicketPresentation } from './ticket-presentation.js'; const activeStatuses = new Set(['open', 'queued']); @@ -17,15 +18,8 @@ export function getCategory(config, categoryId) { return config.ticketing.categories.find((category) => category.id === categoryId) ?? null; } -function getChannelPrefix(config, category) { - const categoryPrefix = category?.channelPrefix; - if (typeof categoryPrefix === 'string' && categoryPrefix.trim()) return categoryPrefix; - return config.ticketing.channelPrefix ?? 'ticket-'; -} - function ticketChannelName(config, category, ticketId, username) { - const idPart = ticketId === null || ticketId === undefined ? '' : `${ticketId}-`; - return safeChannelName(`${getChannelPrefix(config, category)}${idPart}${username || 'member'}`).slice(0, 100); + return buildTicketChannelName(getConfiguredChannelPrefix(config, category), username, ticketId); } async function updateOpeningTicketPriority(channel, ticket, priority, config, db) { From f0a451de47ad77761dc7b025c58c147a2b80245d Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:17:20 -0400 Subject: [PATCH 37/59] Test global and category channel prefix naming --- tests/ticket-channel-name.test.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 tests/ticket-channel-name.test.js diff --git a/tests/ticket-channel-name.test.js b/tests/ticket-channel-name.test.js new file mode 100644 index 0000000..ff4bc61 --- /dev/null +++ b/tests/ticket-channel-name.test.js @@ -0,0 +1,26 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { buildTicketChannelName, getConfiguredChannelPrefix } from '../src/utils/ticket-channel-name.js'; + +test('a non-empty category prefix overrides the global prefix', () => { + const config = { ticketing: { channelPrefix: 'ticket-' } }; + assert.equal(getConfiguredChannelPrefix(config, { channelPrefix: 'general-' }), 'general-'); + assert.equal(buildTicketChannelName(getConfiguredChannelPrefix(config, { channelPrefix: 'general-' }), 'Some User', 12), 'general-12-some-user'); +}); + +test('an empty category prefix inherits the global prefix', () => { + const config = { ticketing: { channelPrefix: 'support-' } }; + assert.equal(getConfiguredChannelPrefix(config, { channelPrefix: '' }), 'support-'); + assert.equal(buildTicketChannelName(getConfiguredChannelPrefix(config, { channelPrefix: '' }), 'Some User', 4), 'support-4-some-user'); +}); + +test('long prefixes cannot truncate the ticket ID or owner from the channel name', () => { + const prefix = 'support'.repeat(40); + const channelName = buildTicketChannelName(prefix, 'very-long-owner-name', 1234); + assert.ok(channelName.length <= 90); + assert.match(channelName, /1234-very-long-owner-name$/); +}); + +test('channel names are normalized and empty owner names receive a safe fallback', () => { + assert.equal(buildTicketChannelName('General Help', '你好', 22), 'general-help-22-ticket'); +}); From ba1764f9a83b8b78a2a01bb85738466460412d13 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:17:38 -0400 Subject: [PATCH 38/59] Ensure removed priorities always sort below configured levels --- src/utils/priority.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/utils/priority.js b/src/utils/priority.js index 169063e..add2d82 100644 --- a/src/utils/priority.js +++ b/src/utils/priority.js @@ -4,8 +4,10 @@ export function getPriorityLevel(priorityId, priorityLevels = []) { export function getPriorityRank(priorityId, priorityLevels = []) { const index = priorityLevels.findIndex((level) => level.id === priorityId); - if (index < 0) return 0; - const configuredRank = Number(priorityLevels[index].rank); + if (index < 0) return Number.NEGATIVE_INFINITY; + const configured = priorityLevels[index].rank; + if (configured === undefined || configured === null) return index + 1; + const configuredRank = Number(configured); return Number.isFinite(configuredRank) ? configuredRank : index + 1; } From 5b91c6a882bf3c5e844ac45155d6f823e1de6c6b Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:17:44 -0400 Subject: [PATCH 39/59] Keep active tickets above closed tickets when sorting channels --- src/services/ticket-ordering.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/services/ticket-ordering.js b/src/services/ticket-ordering.js index 401b913..8883b69 100644 --- a/src/services/ticket-ordering.js +++ b/src/services/ticket-ordering.js @@ -1,4 +1,4 @@ -import { sortTicketsByPriority } from '../utils/priority.js'; +import { compareTicketsByPriority } from '../utils/priority.js'; /** * Reorders only the positions already occupied by ticket channels in each @@ -16,7 +16,12 @@ export function buildPriorityPositionUpdates(entries, priorityLevels = []) { for (const group of groups.values()) { if (group.length < 2) continue; const slots = group.map((entry) => Number(entry.channel.position)).sort((a, b) => a - b); - const orderedTickets = sortTicketsByPriority(group.map((entry) => entry.ticket), priorityLevels); + const orderedTickets = group.map((entry) => entry.ticket).sort((a, b) => { + const aActive = a.status === 'open' || a.status === 'queued'; + const bActive = b.status === 'open' || b.status === 'queued'; + if (aActive !== bActive) return aActive ? -1 : 1; + return compareTicketsByPriority(a, b, priorityLevels); + }); const entriesById = new Map(group.map((entry) => [Number(entry.ticket.id), entry])); orderedTickets.forEach((ticket, index) => { From fbb44a7b114b4dc1f492bf771c3b82455f209ec0 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:18:10 -0400 Subject: [PATCH 40/59] Pass guild context for auto-claim queue refresh --- src/bot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bot.js b/src/bot.js index 45948d0..1ed9558 100644 --- a/src/bot.js +++ b/src/bot.js @@ -50,7 +50,7 @@ client.on(Events.MessageCreate, async (message) => { if (!message.guild || message.author.bot) return; try { const ticket = db.getTicketByChannel(message.channel.id); - if (ticket) await markActivity({ ticket, author: message.member ?? message.author, db, config }); + if (ticket) await markActivity({ ticket, author: message.member ?? message.author, db, config, guild: message.guild }); } catch (error) { console.error('[messageCreate] Could not update ticket activity:', error); } From 0afac624cbd6b15f2874d31cdb6832ece00049f6 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:18:19 -0400 Subject: [PATCH 41/59] Fix auto-claim status and immediately refresh queue state --- src/services/tickets.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index 8c0969f..e39b186 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -387,19 +387,25 @@ export async function renameTicket({ ticket, channel, member, name, db, config } await channel.send(`Ticket renamed to **#${newName}** by <@${memberId(member)}>.`); } -export async function markActivity({ ticket, author, db, config }) { +export async function markActivity({ ticket, author, db, config, guild = null }) { if (!ticket || !activeStatuses.has(ticket.status)) return; const stamp = Date.now(); const patch = { last_activity_at: stamp, inactivity_alerted_at: null }; + let autoClaimed = false; if (!ticket.first_response_at && author.id !== ticket.owner_id && isStaff(author, config, categoryForTicket(ticket, config))) { patch.first_response_at = stamp; db.logStaffEvent({ guildId: ticket.guild_id, ticketId: ticket.id, staffId: author.id, action: 'response' }); if (config.ticketing.claims?.autoClaimOnFirstResponse && !ticket.claimed_by) { patch.claimed_by = author.id; + patch.status = 'open'; + autoClaimed = true; db.logStaffEvent({ guildId: ticket.guild_id, ticketId: ticket.id, staffId: author.id, action: 'claim' }); } } db.updateTicket(ticket.id, patch); + if (autoClaimed && guild) { + await syncTicketPresentation({ guild, db, config }); + } } export async function takeNextQueuedTicket({ guild, member, db, config }) { From 4b9e057cc098b0fe0572b70a1730843170c722c7 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:18:49 -0400 Subject: [PATCH 42/59] Make queue refresh resilient to announcement send failures --- src/services/tickets.js | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index e39b186..534dc89 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -187,7 +187,9 @@ export async function claimTicket({ ticket, channel, member, db, config, allowQu if (config.ticketing.claims?.lockOwnerAfterClaim) { await channel.permissionOverwrites.edit(ticket.owner_id, { SendMessages: false }).catch(() => {}); } - await channel.send({ embeds: [new EmbedBuilder().setColor(config.app.defaultColor || '#6D5AE6').setDescription(`🙋 This ticket was claimed by <@${memberId(member)}>.`)], allowedMentions: { users: [memberId(member)] } }); + await channel.send({ embeds: [new EmbedBuilder().setColor(config.app.defaultColor || '#6D5AE6').setDescription(`🙋 This ticket was claimed by <@${memberId(member)}>.`)], allowedMentions: { users: [memberId(member)] } }).catch((error) => { + console.warn(`[tickets] Unable to post claim announcement for #${ticket.id}: ${error.message}`); + }); await syncTicketPresentation({ guild: channel.guild, db, config, sortChannels: false }); return db.getTicketById(ticket.id); } @@ -204,7 +206,9 @@ export async function unclaimTicket({ ticket, channel, member, db, config }) { db.updateTicket(ticket.id, { claimed_by: null, status: config.ticketing.queue?.enabled ? 'queued' : 'open', last_activity_at: Date.now() }); db.logStaffEvent({ guildId: ticket.guild_id, ticketId: ticket.id, staffId: memberId(member), action: 'unclaim' }); if (config.ticketing.claims?.lockOwnerAfterClaim) await channel.permissionOverwrites.edit(ticket.owner_id, { SendMessages: true }).catch(() => {}); - await channel.send(`Ticket #${ticket.id} is back in the available queue. Previously claimed by <@${old}>.`); + await channel.send(`Ticket #${ticket.id} is back in the available queue. Previously claimed by <@${old}>.`).catch((error) => { + console.warn(`[tickets] Unable to post unclaim announcement for #${ticket.id}: ${error.message}`); + }); await syncTicketPresentation({ guild: channel.guild, db, config, sortChannels: false }); } @@ -299,7 +303,9 @@ export async function reopenTicket({ ticket, channel, member, db, config }) { for (const userId of db.listParticipants(ticket.id)) { if (userId !== ticket.owner_id) await channel.permissionOverwrites.edit(userId, { ViewChannel: true, SendMessages: true, ReadMessageHistory: true }).catch(() => {}); } - await channel.send(`🔓 Ticket #${ticket.id} was reopened by <@${memberId(member)}>. Status: **${nextStatus}**.`); + await channel.send(`🔓 Ticket #${ticket.id} was reopened by <@${memberId(member)}>. Status: **${nextStatus}**.`).catch((error) => { + console.warn(`[tickets] Unable to post reopen announcement for #${ticket.id}: ${error.message}`); + }); await syncTicketPresentation({ guild: channel.guild, db, config }); return db.getTicketById(ticket.id); } @@ -358,7 +364,9 @@ export async function setCategory({ ticket, channel, member, categoryId, db, con await channel.setName(ticketChannelName(config, next, ticket.id, ownerName)).catch((error) => { console.warn(`[tickets] Unable to apply category prefix for ticket #${ticket.id}: ${error.message}`); }); - await channel.send(`Ticket category changed to **${next.name}** by <@${memberId(member)}>.`); + await channel.send(`Ticket category changed to **${next.name}** by <@${memberId(member)}>.`).catch((error) => { + console.warn(`[tickets] Unable to post category-change announcement for #${ticket.id}: ${error.message}`); + }); await syncTicketPresentation({ guild: channel.guild, db, config }); return db.getTicketById(ticket.id); } From b1e7d3d813f22e27a6bb0ccc33b093b504d8b1d9 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:18:55 -0400 Subject: [PATCH 43/59] Keep priorities absent from config at the bottom of the queue From dbb1ff35dd12d76bc3e8490ace161eba8513729e Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:19:02 -0400 Subject: [PATCH 44/59] Validate priority configuration and IDs --- src/config.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/config.js b/src/config.js index 957b9b0..c793449 100644 --- a/src/config.js +++ b/src/config.js @@ -60,6 +60,21 @@ if (categories.length > 25) throw new Error('Discord select menus support at mos if (!Array.isArray(settings.priorityLevels) || settings.priorityLevels.length < 1 || settings.priorityLevels.length > 25) { throw new Error('settings.priorityLevels must contain between 1 and 25 priority levels.'); } + +const priorityIds = new Set(); +for (const level of settings.priorityLevels) { + if (!level?.id || typeof level.id !== 'string' || !/^[a-z0-9_-]{1,40}$/i.test(level.id)) { + throw new Error('Every priority level needs a unique id (letters, digits, _ and - only; max 40 characters).'); + } + if (priorityIds.has(level.id)) throw new Error(`Duplicate priority level id: ${level.id}`); + priorityIds.add(level.id); + if (level.rank !== undefined && (typeof level.rank !== 'number' || !Number.isFinite(level.rank))) { + throw new Error(`Priority level ${level.id} rank must be a finite number when provided.`); + } + if (level.label !== undefined && (typeof level.label !== 'string' || !level.label.trim())) { + throw new Error(`Priority level ${level.id} label must be a non-empty string.`); + } +} const categoryIds = new Set(); for (const category of categories) { if (!category?.id || !/^[a-z0-9_-]{1,40}$/i.test(category.id)) { From 11edc24f5d90597f6fde29145375671e8f98dd8d Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:19:09 -0400 Subject: [PATCH 45/59] Test active channels sorting above closed tickets --- tests/priority.test.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/priority.test.js b/tests/priority.test.js index 76b0711..2a5e298 100644 --- a/tests/priority.test.js +++ b/tests/priority.test.js @@ -57,3 +57,19 @@ test('channel ordering sorts tickets into their existing positions within each p ] ); }); + +test('active ticket channels sort above closed channels regardless of closed priority', () => { + const entries = [ + { ticket: { id: 1, status: 'open', priority: 'low', created_at: 1 }, channel: { id: 'active-low', parentId: 'support', position: 2 } }, + { ticket: { id: 2, status: 'closed', priority: 'urgent', created_at: 2 }, channel: { id: 'closed-urgent', parentId: 'support', position: 1 } }, + { ticket: { id: 3, status: 'open', priority: 'high', created_at: 3 }, channel: { id: 'active-high', parentId: 'support', position: 3 } } + ]; + + assert.deepEqual( + buildPriorityPositionUpdates(entries, priorityLevels), + [ + { channel: 'active-high', position: 1 }, + { channel: 'closed-urgent', position: 3 } + ] + ); +}); From 4f40b3319c24358d1705c65dcb060be1ef967c39 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:19:36 -0400 Subject: [PATCH 46/59] Keep ticket fallback consistent with existing channel names --- src/utils/ticket-channel-name.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/ticket-channel-name.js b/src/utils/ticket-channel-name.js index 73ca79b..096a90d 100644 --- a/src/utils/ticket-channel-name.js +++ b/src/utils/ticket-channel-name.js @@ -16,7 +16,7 @@ export function getConfiguredChannelPrefix(config, category) { */ export function buildTicketChannelName(prefix, username, ticketId = null) { const safePrefix = slug(prefix); - const safeOwner = slug(username) || 'member'; + const safeOwner = slug(username) || 'ticket'; const idPart = ticketId === null || ticketId === undefined ? '' : String(ticketId).replace(/[^0-9]/g, ''); const suffix = [idPart, safeOwner].filter(Boolean).join('-'); const prefixBudget = Math.max(0, 90 - suffix.length - (safePrefix ? 1 : 0)); From c40ee101a58afc8d4b7e318e47578a54b456cb22 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:21:34 -0400 Subject: [PATCH 47/59] Serialize queue panel refreshes and recover deleted messages --- src/services/queue-display.js | 40 ++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/src/services/queue-display.js b/src/services/queue-display.js index 72ed66f..bad8817 100644 --- a/src/services/queue-display.js +++ b/src/services/queue-display.js @@ -39,7 +39,7 @@ export function buildQueueEmbed({ guild, queued, config, display }) { * Creates or edits this guild's persistent queue embed. Its message ID is kept * in SQLite so a bot restart edits the existing message instead of duplicating it. */ -export async function refreshQueueDisplay({ guild, db, config }) { +async function refreshQueueDisplayOnce({ guild, db, config }) { const display = config.ticketing.queue?.display; if (!display?.enabled || !display.channelId) return false; if ((display.type || 'embed') !== 'embed') throw new Error('ticketing.queue.display.type currently supports only "embed".'); @@ -70,11 +70,45 @@ export async function refreshQueueDisplay({ guild, db, config }) { } if (message) { - await message.edit(payload); - return true; + try { + await message.edit(payload); + return true; + } catch (error) { + if (!isUnknownMessage(error)) throw error; + } } const created = await channel.send(payload); db.saveQueueStatusMessage(guild.id, channel.id, created.id); return true; } + + +const inFlightRefreshes = new Map(); + +/** + * Serialize queue panel updates per guild. If another event arrives while a + * refresh is running, run one more pass afterwards to publish the latest DB state. + */ +export function refreshQueueDisplay(args) { + const guildId = String(args.guild.id); + const inFlight = inFlightRefreshes.get(guildId); + if (inFlight) { + inFlight.dirty = true; + return inFlight.promise; + } + + const state = { dirty: false, promise: null }; + state.promise = (async () => { + let result = false; + do { + state.dirty = false; + result = await refreshQueueDisplayOnce(args); + } while (state.dirty); + return result; + })().finally(() => { + if (inFlightRefreshes.get(guildId) === state) inFlightRefreshes.delete(guildId); + }); + inFlightRefreshes.set(guildId, state); + return state.promise; +} From c55ccefbc10d63da582785c106711c21212f6665 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:21:54 -0400 Subject: [PATCH 48/59] Test concurrent queue refresh and deleted-message recovery --- tests/queue-display.test.js | 73 +++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/tests/queue-display.test.js b/tests/queue-display.test.js index 0ed0b84..2c57c9f 100644 --- a/tests/queue-display.test.js +++ b/tests/queue-display.test.js @@ -115,3 +115,76 @@ test('refresh recreates and stores a message that was deleted', async () => { assert.equal(saved.messageId, createdMessage.id); assert.match(stored.embeds[0].toJSON().description, /no tickets waiting/); }); + +test('concurrent refreshes reuse one message creation and publish the latest state', async () => { + let stored = null; + let sendCalls = 0; + let editCalls = 0; + let startSend; + let releaseSend; + const sendStarted = new Promise((resolve) => { startSend = resolve; }); + const sendGate = new Promise((resolve) => { releaseSend = resolve; }); + const createdMessage = { + id: '99999999999999999', + async edit() { editCalls += 1; } + }; + const channel = { + id: config.ticketing.queue.display.channelId, + isTextBased: () => true, + async send() { + sendCalls += 1; + startSend(); + await sendGate; + return createdMessage; + }, + messages: { async fetch(id) { assert.equal(id, createdMessage.id); return createdMessage; } } + }; + const db = { + queueList: () => [], + getQueueStatusMessage: () => stored, + saveQueueStatusMessage(guildId, channelId, messageId) { + stored = { guild_id: guildId, channel_id: channelId, message_id: messageId }; + } + }; + const guild = { id: 'concurrent-guild', channels: { fetch: async () => channel, cache: new Map() } }; + + const first = refreshQueueDisplay({ guild, db, config }); + await sendStarted; + const second = refreshQueueDisplay({ guild, db, config }); + releaseSend(); + await Promise.all([first, second]); + + assert.equal(sendCalls, 1, 'only one message should be created'); + assert.equal(editCalls, 1, 'the queued refresh should edit the newly created message'); + assert.equal(stored.message_id, createdMessage.id); +}); + +test('refresh recreates the queue embed if the saved message disappears during edit', async () => { + let saved = { channel_id: config.ticketing.queue.display.channelId, message_id: 'old-message' }; + let newMessages = 0; + const missing = Object.assign(new Error('Unknown Message'), { code: 10008 }); + const channel = { + id: config.ticketing.queue.display.channelId, + isTextBased: () => true, + async send() { newMessages += 1; return { id: '10101010101010101' }; }, + messages: { + async fetch() { + return { + async edit() { throw missing; } + }; + } + } + }; + const db = { + queueList: () => [], + getQueueStatusMessage: () => saved, + saveQueueStatusMessage(guildId, channelId, messageId) { + saved = { guild_id: guildId, channel_id: channelId, message_id: messageId }; + } + }; + const guild = { id: 'edit-race-guild', channels: { fetch: async () => channel, cache: new Map() } }; + + assert.equal(await refreshQueueDisplay({ guild, db, config }), true); + assert.equal(newMessages, 1); + assert.equal(saved.message_id, '10101010101010101'); +}); From e6262670fec22b5291180be343eb23e062ea052f Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:22:18 -0400 Subject: [PATCH 49/59] Return the persisted ticket after priority embed migration --- src/services/tickets.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index 534dc89..2f4bd9c 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -341,7 +341,7 @@ export async function setPriority({ ticket, channel, member, priority, db, confi console.warn(`[tickets] Unable to post priority change for ticket #${ticket.id}: ${error.message}`); }); await syncTicketPresentation({ guild: channel.guild, db, config }); - return updated; + return db.getTicketById(ticket.id); } export async function setCategory({ ticket, channel, member, categoryId, db, config }) { From 80dc534513617229a072e111bac7616c29f49f6c Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:22:26 -0400 Subject: [PATCH 50/59] Clarify queue display setup and category prefix examples --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index db84a0c..d66b40c 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ Once online, run `/ticket-panel` in the channel where users should open tickets. | `features.suggestions` | Enable the suggestion workflow | | `features.reviews` | Let users rate their support experience | -Category IDs must be letters, digits, underscores, or hyphens (max 40 chars). Each category can have a `parentCategoryId`, `supportRoleIds`, `requiredRoleIds`, and up to three `questions`. Each category can also set `channelPrefix` to override the global prefix; for example, `channelPrefix`: `general-` gives that category channels such as `general-12-someone`. Configure the optional queue embed under `ticketing.queue.display`; set `enabled`, `type: "embed"`, and a text `channelId`. The bot creates the message on first use and edits the stored message on restarts and at `refreshIntervalSeconds`. +Category IDs must be letters, digits, underscores, or hyphens (max 40 chars). Each category can have a `parentCategoryId`, `supportRoleIds`, `requiredRoleIds`, and up to three `questions`. Each category can also set `channelPrefix` to override the global prefix; for example, set `channelPrefix` to `general-` to create channels such as `general-12-someone`. To enable the optional queue embed, set `ticketing.queue.enabled` and `ticketing.queue.display.enabled` to `true`, choose `type: "embed"`, and set a text `channelId`. The bot creates the message on first use, stores its message ID in SQLite, then edits that same message after restarts and at `refreshIntervalSeconds`. Higher `priorityLevels[].rank` values appear first; tickets with equal priority stay FIFO, and closed ticket channels are placed below active tickets. ## Commands From ddcc5308c13ebfad9f7c4739354ac2d20666101d Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:23:02 -0400 Subject: [PATCH 51/59] Avoid recursive missing-channel queue processing and refresh the display --- src/services/tickets.js | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index 2f4bd9c..73e524c 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -417,19 +417,25 @@ export async function markActivity({ ticket, author, db, config, guild = null }) } export async function takeNextQueuedTicket({ guild, member, db, config }) { - const queue = db.queueList(guild.id, config.priorityLevels).filter((item) => isStaff(member, config, categoryForTicket(item, config))); - if (!queue.length) { - if (!isStaff(member, config)) throw new Error('Only support staff can take queued tickets.'); - throw new Error('There are no queued tickets assigned to a support category you can access.'); - } - const ticket = queue[0]; - const channel = await guild.channels.fetch(ticket.channel_id).catch(() => null); - if (!channel) { - db.updateTicket(ticket.id, { status: 'closed', closed_at: Date.now(), close_reason: 'Ticket channel was missing during queue processing.' }); - return takeNextQueuedTicket({ guild, member, db, config }); + while (true) { + const queue = db.queueList(guild.id, config.priorityLevels) + .filter((item) => isStaff(member, config, categoryForTicket(item, config))); + if (!queue.length) { + if (!isStaff(member, config)) throw new Error('Only support staff can take queued tickets.'); + throw new Error('There are no queued tickets assigned to a support category you can access.'); + } + + const ticket = queue[0]; + const channel = await guild.channels.fetch(ticket.channel_id).catch(() => null); + if (!channel) { + db.updateTicket(ticket.id, { status: 'closed', closed_at: Date.now(), close_reason: 'Ticket channel was missing during queue processing.' }); + await syncTicketPresentation({ guild, db, config }); + continue; + } + + const claimed = await claimTicket({ ticket, channel, member, db, config, allowQueueJump: true }); + return { ticket: claimed, channel, position: 1 }; } - const claimed = await claimTicket({ ticket, channel, member, db, config, allowQueueJump: true }); - return { ticket: claimed, channel, position: 1 }; } export function listQueue(db, guildId, config) { From daa24f431f30585f47fdb6e1891048690bd6cd4e Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:24:50 -0400 Subject: [PATCH 52/59] Serialize concurrent priority-based channel reordering --- src/services/ticket-ordering.js | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/services/ticket-ordering.js b/src/services/ticket-ordering.js index 8883b69..fe1715e 100644 --- a/src/services/ticket-ordering.js +++ b/src/services/ticket-ordering.js @@ -35,7 +35,7 @@ export function buildPriorityPositionUpdates(entries, priorityLevels = []) { return updates; } -export async function sortTicketChannelsByPriority({ guild, db, config }) { +async function sortTicketChannelsByPriorityOnce({ guild, db, config }) { const tickets = db.ticketsForGuild(guild.id); const entries = tickets.map((ticket) => ({ ticket, @@ -46,3 +46,32 @@ export async function sortTicketChannelsByPriority({ guild, db, config }) { if (updates.length) await guild.channels.setPositions(updates); return updates.length; } + +const inFlightSorts = new Map(); + +/** + * Serialize position edits per guild so concurrent ticket changes cannot leave + * the visible order reflecting an older priority snapshot. + */ +export function sortTicketChannelsByPriority(args) { + const guildId = String(args.guild.id); + const inFlight = inFlightSorts.get(guildId); + if (inFlight) { + inFlight.dirty = true; + return inFlight.promise; + } + + const state = { dirty: false, promise: null }; + state.promise = (async () => { + let changed = 0; + do { + state.dirty = false; + changed = await sortTicketChannelsByPriorityOnce(args); + } while (state.dirty); + return changed; + })().finally(() => { + if (inFlightSorts.get(guildId) === state) inFlightSorts.delete(guildId); + }); + inFlightSorts.set(guildId, state); + return state.promise; +} From bf79490b3971febbd00b906c9006edc64bece791 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:24:59 -0400 Subject: [PATCH 53/59] Test concurrent channel priority changes --- tests/priority.test.js | 48 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/tests/priority.test.js b/tests/priority.test.js index 2a5e298..25ad406 100644 --- a/tests/priority.test.js +++ b/tests/priority.test.js @@ -1,7 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { compareTicketsByPriority, formatPriority, getPriorityRank, sortTicketsByPriority } from '../src/utils/priority.js'; -import { buildPriorityPositionUpdates } from '../src/services/ticket-ordering.js'; +import { buildPriorityPositionUpdates, sortTicketChannelsByPriority } from '../src/services/ticket-ordering.js'; const priorityLevels = [ { id: 'low', label: 'Low', rank: 1, emoji: '🟢' }, @@ -73,3 +73,49 @@ test('active ticket channels sort above closed channels regardless of closed pri ] ); }); + +test('concurrent channel sorts finish using the latest priority snapshot', async () => { + let tickets = [ + { id: 1, channel_id: 'channel-low', status: 'open', priority: 'low', created_at: 1 }, + { id: 2, channel_id: 'channel-high', status: 'open', priority: 'urgent', created_at: 2 } + ]; + const channels = new Map([ + ['channel-low', { id: 'channel-low', parentId: 'support', position: 0 }], + ['channel-high', { id: 'channel-high', parentId: 'support', position: 1 }] + ]); + let releaseFirst; + let firstStarted; + const firstStartedPromise = new Promise((resolve) => { firstStarted = resolve; }); + const firstGate = new Promise((resolve) => { releaseFirst = resolve; }); + let calls = 0; + const guild = { + id: 'priority-race-guild', + channels: { + cache: channels, + async setPositions(updates) { + calls += 1; + if (calls === 1) { + firstStarted(); + await firstGate; + } + for (const update of updates) channels.get(update.channel).position = update.position; + } + } + }; + const db = { ticketsForGuild: () => tickets }; + const args = { guild, db, config: { priorityLevels } }; + + const first = sortTicketChannelsByPriority(args); + await firstStartedPromise; + tickets = [ + { ...tickets[0], priority: 'urgent' }, + { ...tickets[1], priority: 'low' } + ]; + const second = sortTicketChannelsByPriority(args); + releaseFirst(); + await Promise.all([first, second]); + + assert.ok(calls >= 2, 'a change received during an in-flight reorder should trigger a fresh pass'); + assert.equal(channels.get('channel-low').position, 0); + assert.equal(channels.get('channel-high').position, 1); +}); From 0b216cef7c11b975663cf763daaee0c50baf2023 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:25:27 -0400 Subject: [PATCH 54/59] Report queue panel refresh failures accurately --- src/services/ticket-presentation.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/services/ticket-presentation.js b/src/services/ticket-presentation.js index a79e645..17341e3 100644 --- a/src/services/ticket-presentation.js +++ b/src/services/ticket-presentation.js @@ -11,13 +11,20 @@ export async function syncTicketPresentation({ guild, db, config, sortChannels = jobs.push(['queue display', () => refreshQueueDisplay({ guild, db, config })]); const results = await Promise.allSettled(jobs.map(([, run]) => run())); + let successful = true; for (let index = 0; index < results.length; index += 1) { const result = results[index]; if (result.status === 'rejected') { + successful = false; console.warn(`[ticket-presentation] Unable to update ${jobs[index][0]} for guild ${guild.id}: ${result.reason?.message ?? result.reason}`); + continue; + } + if (jobs[index][0] === 'queue display' && config.ticketing.queue?.display?.enabled && result.value === false) { + successful = false; + console.warn(`[ticket-presentation] Queue display is enabled but could not be refreshed for guild ${guild.id}.`); } } - return results.every((result) => result.status === 'fulfilled'); + return successful; } export async function syncQueueDisplaysForClient(client, db, config) { From 94a898e3f22c6f6f2e3d033f993a558b477ab179 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:25:34 -0400 Subject: [PATCH 55/59] Expose priority presentation synchronization result --- src/services/tickets.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index 73e524c..a3a1d4c 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -340,8 +340,8 @@ export async function setPriority({ ticket, channel, member, priority, db, confi await channel.send(`Ticket #${ticket.id} priority changed to **${formatPriority(priority, configured)}** by <@${memberId(member)}>.`).catch((error) => { console.warn(`[tickets] Unable to post priority change for ticket #${ticket.id}: ${error.message}`); }); - await syncTicketPresentation({ guild: channel.guild, db, config }); - return db.getTicketById(ticket.id); + const presentationSynced = await syncTicketPresentation({ guild: channel.guild, db, config }); + return { ticket: db.getTicketById(ticket.id), presentationSynced }; } export async function setCategory({ ticket, channel, member, categoryId, db, config }) { From a7aa552437553afd05b510df9f2e63b7cfad6736 Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:25:42 -0400 Subject: [PATCH 56/59] Report priority presentation failures in the command response --- src/handlers/interactions.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/handlers/interactions.js b/src/handlers/interactions.js index 3f10d68..15ef6ba 100644 --- a/src/handlers/interactions.js +++ b/src/handlers/interactions.js @@ -138,8 +138,11 @@ async function handleSlashCommand(interaction) { } if (name === 'ticket-priority') { const priority = interaction.options.getString('level', true); - await setPriority({ ticket, channel, member, priority, db, config }); - return sendReply(interaction, `Ticket #${ticket.id} priority is now **${formatPriority(priority, config.priorityLevels)}**. Ticket channels and queue order have been refreshed.`); + const result = await setPriority({ ticket, channel, member, priority, db, config }); + const presentation = result.presentationSynced + ? 'Ticket channel order and the configured queue display are up to date.' + : 'The priority was saved, but one or more views could not refresh. Check the bot logs and its Manage Channels / message permissions.'; + return sendReply(interaction, `Ticket #${ticket.id} priority is now **${formatPriority(priority, config.priorityLevels)}**. ${presentation}`); } if (name === 'ticket-category') { const categoryId = interaction.options.getString('category', true); From 3c2ffd7f755b0e48e87ce2a59d372bded055f80d Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:25:50 -0400 Subject: [PATCH 57/59] Test automatic claims correctly remove tickets from queue status --- tests/ticket-lifecycle.test.js | 44 ++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 tests/ticket-lifecycle.test.js diff --git a/tests/ticket-lifecycle.test.js b/tests/ticket-lifecycle.test.js new file mode 100644 index 0000000..bba40d0 --- /dev/null +++ b/tests/ticket-lifecycle.test.js @@ -0,0 +1,44 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { markActivity } from '../src/services/tickets.js'; + +test('auto-claiming a queued ticket removes it from waiting state', async () => { + const ticket = { + id: 42, + guild_id: 'guild-id', + owner_id: 'owner-id', + category_id: 'general', + status: 'queued', + claimed_by: null, + first_response_at: null + }; + let savedPatch = null; + const events = []; + const db = { + updateTicket(id, patch) { + assert.equal(id, ticket.id); + savedPatch = patch; + return { ...ticket, ...patch }; + }, + logStaffEvent(event) { events.push(event); } + }; + const config = { + permissions: { staffRoleIds: ['staff-role'], adminRoleIds: [] }, + ticketing: { + categories: [{ id: 'general', supportRoleIds: [] }], + claims: { autoClaimOnFirstResponse: true } + } + }; + + await markActivity({ + ticket, + author: { id: 'staff-id', roles: ['staff-role'] }, + db, + config + }); + + assert.equal(savedPatch.status, 'open'); + assert.equal(savedPatch.claimed_by, 'staff-id'); + assert.equal(events.filter((event) => event.action === 'response').length, 1); + assert.equal(events.filter((event) => event.action === 'claim').length, 1); +}); From 475541174e0259f85bba6c0f540ce46dde5f560c Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:25:58 -0400 Subject: [PATCH 58/59] Document priority sorting scope across Discord categories --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d66b40c..352d01d 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ Once online, run `/ticket-panel` in the channel where users should open tickets. | `features.suggestions` | Enable the suggestion workflow | | `features.reviews` | Let users rate their support experience | -Category IDs must be letters, digits, underscores, or hyphens (max 40 chars). Each category can have a `parentCategoryId`, `supportRoleIds`, `requiredRoleIds`, and up to three `questions`. Each category can also set `channelPrefix` to override the global prefix; for example, set `channelPrefix` to `general-` to create channels such as `general-12-someone`. To enable the optional queue embed, set `ticketing.queue.enabled` and `ticketing.queue.display.enabled` to `true`, choose `type: "embed"`, and set a text `channelId`. The bot creates the message on first use, stores its message ID in SQLite, then edits that same message after restarts and at `refreshIntervalSeconds`. Higher `priorityLevels[].rank` values appear first; tickets with equal priority stay FIFO, and closed ticket channels are placed below active tickets. +Category IDs must be letters, digits, underscores, or hyphens (max 40 chars). Each category can have a `parentCategoryId`, `supportRoleIds`, `requiredRoleIds`, and up to three `questions`. Each category can also set `channelPrefix` to override the global prefix; for example, set `channelPrefix` to `general-` to create channels such as `general-12-someone`. To enable the optional queue embed, set `ticketing.queue.enabled` and `ticketing.queue.display.enabled` to `true`, choose `type: "embed"`, and set a text `channelId`. The bot creates the message on first use, stores its message ID in SQLite, then edits that same message after restarts and at `refreshIntervalSeconds`. Higher `priorityLevels[].rank` values appear first; tickets with equal priority stay FIFO, and closed ticket channels are placed below active tickets. Discord channel positions are sorted within each parent category, because channels under separate Discord categories cannot be globally interleaved. ## Commands From 9b851e2b9499bdc2503f5463e9ea7e0e4d43de4e Mon Sep 17 00:00:00 2001 From: THEMPGUYActions Date: Mon, 19 Oct 2026 15:27:59 -0400 Subject: [PATCH 59/59] Refresh priority queue immediately after ticket state changes --- src/services/tickets.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/services/tickets.js b/src/services/tickets.js index a3a1d4c..0f68af5 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -230,6 +230,7 @@ export async function closeTicket({ ticket, channel, member, reason = 'No reason const current = db.getTicketById(ticket.id); db.updateTicket(ticket.id, { status: 'closed', closed_at: Date.now(), closed_by: memberId(member), close_reason: truncate(reason, 900), last_activity_at: Date.now() }); db.logStaffEvent({ guildId: ticket.guild_id, ticketId: ticket.id, staffId: memberId(member), action: 'close' }); + await syncTicketPresentation({ guild, db, config }); const hasLogDestination = Boolean(category?.logsChannelId || config.channels?.ticketLogsId); if (config.ticketing.transcripts?.saveLocalCopy || !hasLogDestination) { @@ -287,7 +288,6 @@ export async function closeTicket({ ticket, channel, member, reason = 'No reason }).catch(() => {}); } } - await syncTicketPresentation({ guild, db, config }); return { ticket: db.getTicketById(ticket.id), transcript, summary }; } @@ -335,13 +335,13 @@ export async function setPriority({ ticket, channel, member, priority, db, confi if (!isStaff(member, config, category)) throw new Error('Only support staff can change priority.'); const configured = config.priorityLevels ?? []; if (!configured.some((item) => item.id === priority)) throw new Error('That priority is not configured.'); - const updated = db.updateTicket(ticket.id, { priority, last_activity_at: Date.now() }); - await updateOpeningTicketPriority(channel, ticket, priority, config, db); + db.updateTicket(ticket.id, { priority, last_activity_at: Date.now() }); + const presentationSynced = await syncTicketPresentation({ guild: channel.guild, db, config }); + const openingEmbedUpdated = await updateOpeningTicketPriority(channel, ticket, priority, config, db); await channel.send(`Ticket #${ticket.id} priority changed to **${formatPriority(priority, configured)}** by <@${memberId(member)}>.`).catch((error) => { console.warn(`[tickets] Unable to post priority change for ticket #${ticket.id}: ${error.message}`); }); - const presentationSynced = await syncTicketPresentation({ guild: channel.guild, db, config }); - return { ticket: db.getTicketById(ticket.id), presentationSynced }; + return { ticket: db.getTicketById(ticket.id), presentationSynced: presentationSynced && openingEmbedUpdated }; } export async function setCategory({ ticket, channel, member, categoryId, db, config }) {