diff --git a/README.md b/README.md index 88c4ed4..352d01d 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,9 +78,14 @@ 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.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 | @@ -87,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, 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 diff --git a/config/settings.example.json b/config/settings.example.json index 0c5c3c4..03d5c1f 100644 --- a/config/settings.example.json +++ b/config/settings.example.json @@ -7,12 +7,21 @@ "defaultColor": "#6D5AE6" }, "ticketing": { + "channelPrefix": "ticket-", "maxOpenPerUser": 3, "creationCooldownSeconds": 20, "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, @@ -47,6 +56,7 @@ "categories": [ { "id": "general", + "channelPrefix": "", "name": "General Support", "description": "Questions and general help", "emoji": "🎫", @@ -60,6 +70,7 @@ }, { "id": "technical", + "channelPrefix": "", "name": "Technical Support", "description": "Report a technical problem", "emoji": "🛠️", @@ -74,6 +85,7 @@ }, { "id": "billing", + "channelPrefix": "", "name": "Billing and Purchases", "description": "Questions about purchases or payments", "emoji": "🧾", diff --git a/src/bot.js b/src/bot.js index 89d3569..1ed9558 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); @@ -32,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); } @@ -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); 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.'), diff --git a/src/config.js b/src/config.js index 6646e11..c793449 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,37 @@ 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 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.'); @@ -28,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)) { @@ -35,6 +82,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) { diff --git a/src/db/database.js b/src/db/database.js index 575eba3..9c4cf93 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 = []) => { @@ -37,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); @@ -107,6 +109,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, @@ -131,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) { @@ -145,6 +157,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); @@ -165,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(', '); @@ -174,7 +191,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 +205,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 +286,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) { diff --git a/src/handlers/interactions.js b/src/handlers/interactions.js index f0d4930..15ef6ba 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.'; @@ -137,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 **${priority}**.`); + 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); diff --git a/src/services/queue-display.js b/src/services/queue-display.js new file mode 100644 index 0000000..bad8817 --- /dev/null +++ b/src/services/queue-display.js @@ -0,0 +1,114 @@ +import { EmbedBuilder } from 'discord.js'; +import { formatPriority } from '../utils/priority.js'; + +function isUnknownMessage(error) { + return Number(error?.code ?? error?.rawError?.code) === 10008; +} + +export function buildQueueEmbed({ guild, queued, config, display }) { + const maxTickets = Math.min(25, Math.max(1, Number(display.maxTickets ?? 15))); + 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; + 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)) + .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. + */ +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".'); + + 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) { + 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; +} diff --git a/src/services/ticket-ordering.js b/src/services/ticket-ordering.js new file mode 100644 index 0000000..fe1715e --- /dev/null +++ b/src/services/ticket-ordering.js @@ -0,0 +1,77 @@ +import { compareTicketsByPriority } 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 = 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) => { + 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; +} + +async function sortTicketChannelsByPriorityOnce({ 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; +} + +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; +} diff --git a/src/services/ticket-presentation.js b/src/services/ticket-presentation.js new file mode 100644 index 0000000..17341e3 --- /dev/null +++ b/src/services/ticket-presentation.js @@ -0,0 +1,36 @@ +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())); + 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 successful; +} + +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; +} diff --git a/src/services/tickets.js b/src/services/tickets.js index fdfeb1b..0f68af5 100644 --- a/src/services/tickets.js +++ b/src/services/tickets.js @@ -9,12 +9,52 @@ 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 { buildTicketChannelName, getConfiguredChannelPrefix } from '../utils/ticket-channel-name.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 ticketChannelName(config, category, ticketId, username) { + return buildTicketChannelName(getConfiguredChannelPrefix(config, category), username, ticketId); +} + +async function updateOpeningTicketPriority(channel, ticket, priority, config, db) { + try { + 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 #${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 === `#${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 } + : { 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 #${ticket.id}: ${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,7 +80,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 channelName = `ticket-${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] }, @@ -65,6 +105,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)}`); @@ -75,7 +116,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( @@ -83,7 +124,9 @@ 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) { if (savedTicket) db.deleteTicket(savedTicket.id); @@ -130,7 +173,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.'); @@ -143,7 +187,10 @@ 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); } @@ -159,7 +206,10 @@ 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 }); } export async function closeTicket({ ticket, channel, member, reason = 'No reason provided.', db, config, guild }) { @@ -180,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) { @@ -246,12 +297,16 @@ 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'; + 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 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); } @@ -271,6 +326,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; } @@ -280,8 +336,12 @@ 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.'); 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 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}`); + }); + return { ticket: db.getTicketById(ticket.id), presentationSynced: presentationSynced && openingEmbedUpdated }; } export async function setCategory({ ticket, channel, member, categoryId, db, config }) { @@ -300,7 +360,14 @@ 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() }); - await channel.send(`Ticket category changed to **${next.name}** by <@${memberId(member)}>.`); + 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)}>.`).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); } @@ -328,39 +395,51 @@ 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 }) { - const queue = db.queueList(guild.id).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) { - 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) { @@ -392,6 +471,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}>`; } diff --git a/src/utils/priority.js b/src/utils/priority.js new file mode 100644 index 0000000..add2d82 --- /dev/null +++ b/src/utils/priority.js @@ -0,0 +1,33 @@ +export function getPriorityLevel(priorityId, priorityLevels = []) { + return priorityLevels.find((level) => level.id === priorityId) ?? null; +} + +export function getPriorityRank(priorityId, priorityLevels = []) { + const index = priorityLevels.findIndex((level) => level.id === priorityId); + 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; +} + +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)); +} diff --git a/src/utils/settings-migration.js b/src/utils/settings-migration.js new file mode 100644 index 0000000..31ad175 --- /dev/null +++ b/src/utils/settings-migration.js @@ -0,0 +1,43 @@ +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 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)) { + 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; + } + + 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; + } + } + } + + return changed; +} diff --git a/src/utils/ticket-channel-name.js b/src/utils/ticket-channel-name.js new file mode 100644 index 0000000..096a90d --- /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) || '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)); + return [safePrefix.slice(0, prefixBudget), suffix].filter(Boolean).join('-').slice(0, 90) || 'ticket'; +} 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]); +}); diff --git a/tests/priority.test.js b/tests/priority.test.js new file mode 100644 index 0000000..25ad406 --- /dev/null +++ b/tests/priority.test.js @@ -0,0 +1,121 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { compareTicketsByPriority, formatPriority, getPriorityRank, sortTicketsByPriority } from '../src/utils/priority.js'; +import { buildPriorityPositionUpdates, sortTicketChannelsByPriority } from '../src/services/ticket-ordering.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'); +}); + +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 } + ] + ); +}); + +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 } + ] + ); +}); + +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); +}); diff --git a/tests/queue-display.test.js b/tests/queue-display.test.js new file mode 100644 index 0000000..2c57c9f --- /dev/null +++ b/tests/queue-display.test.js @@ -0,0 +1,190 @@ +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/); +}); + +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'); +}); diff --git a/tests/settings-migration.test.js b/tests/settings-migration.test.js new file mode 100644 index 0000000..341f748 --- /dev/null +++ b/tests/settings-migration.test.js @@ -0,0 +1,82 @@ +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); +}); + +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' }); +}); 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'); +}); 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); +});