all repos — stealth-developers @ 0034b53eccf9ab0f19cc43c837b39e1a6d05021e

apps/bot/src/commands/tickets/command.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
import { randomUUID } from "node:crypto";

import { ChannelType, type TextChannel } from "discord.js";
import { Subcommand } from "@sapphire/plugin-subcommands";
import { ApplyOptions } from "@sapphire/decorators";
import { container, Result } from "@sapphire/framework";

import db, { eq, tickets } from "@stealth-developers/db";
import config from "@stealth-developers/config";
import { getCategory, PublicError } from "@/lib";
import { upsertUser } from "$/db";

@ApplyOptions<Subcommand.Options>({
	description: "ticket-related commands",
})
export class TicketCommand extends Subcommand {
	public constructor(context: Subcommand.LoaderContext, options: Subcommand.Options) {
		super(context, {
			...options,
			name: "ticket",
			subcommands: [
				{ name: "new", chatInputRun: "createTicket" },
				{ name: "for", chatInputRun: "createTicketFor" },
				{
					name: "actions",
					type: "group",
					entries: [
						{ name: "open", chatInputRun: "openTicket" },
						{ name: "close", chatInputRun: "closeTicket" },
						{ name: "add", chatInputRun: "addToTicket" },
						{ name: "claim", chatInputRun: "claimTicket" },
						{ name: "unclaim", chatInputRun: "unclaimTicket" },
						{ name: "delete", chatInputRun: "deleteTicket" },
					],
				},
				{
					name: "view",
					type: "group",
					entries: [
						{ name: "info", chatInputRun: "viewTicketInfo" },
						{ name: "transcript", chatInputRun: "viewTicketTranscript" },
						{ name: "list", chatInputRun: "listTickets" },
						{ name: "export", chatInputRun: "exportTickets" },
					],
				},
			],
		});
	}

	public override registerApplicationCommands(registry: Subcommand.Registry) {
		registry.registerChatInputCommand((builder) =>
			builder
				.setName("ticket")
				.setDescription("root ticket command")
				.addSubcommand((command) => command.setName("new").setDescription("Open a new ticket"))
				.addSubcommand((command) =>
					command
						.setName("for")
						.setDescription("Open a ticket for a user")
						.addUserOption((option) =>
							option
								.setName("user")
								.setDescription("The user to open the ticket for")
								.setRequired(true),
						),
				)
				.addSubcommandGroup((group) =>
					group
						.setName("action")
						.setDescription("ticket actions")
						.addSubcommand((command) =>
							command.setName("open").setDescription("Reopen the ticket in the current channel"),
						)
						.addSubcommand((command) =>
							command
								.setName("close")
								.setDescription("Close the ticket in the current channel")
								.addStringOption((option) =>
									option
										.setName("reason")
										.setDescription("Public reason for closing the ticket")
										.setRequired(true),
								)
								.addStringOption((option) =>
									option
										.setName("private")
										.setDescription(
											"Private reason for closing the ticket, only visible to moderators",
										)
										.setRequired(false),
								)
								.addBooleanOption((option) =>
									option.setName("delete-channel").setDescription("Delete the channel immediately"),
								),
						),
				),
		);
	}

	private async doCreateTicket(interaction: Subcommand.ChatInputCommandInteraction) {
		const isOnBehalf = interaction.options.getSubcommand(true) === "for";
		const publicId = randomUUID();

		if (!interaction.member) {
			return interaction.reply({
				content: "Failed to create ticket: Member not found",
				flags: ["Ephemeral"],
			});
		}

		const creator = await upsertUser(interaction.member);
		if (!creator)
			return interaction.reply({
				content: "Failed to create ticket: User not found",
				flags: ["Ephemeral"],
			});

		const subject = isOnBehalf ? interaction.options.getUser("user") : interaction.user;
		const subjectUser = subject ? await upsertUser(subject) : creator;
		if (!subjectUser)
			return interaction.reply({
				content: "Failed to create ticket: Subject not found",
				flags: ["Ephemeral"],
			});

		if (isOnBehalf && !creator.moderator)
			return interaction.reply({
				content: "You don't have permission to create a ticket for another user.",
				flags: ["Ephemeral"],
			});

		const ticketCategory = await getCategory(config.discord.server.ticket_category);
		let createdChannel: TextChannel | undefined = undefined;

		const txResult = await Result.fromAsync(async () => {
			return await db.transaction(async (tx) => {
				const [ticket] = await tx
					.insert(tickets)
					.values({
						anonymousId: publicId,
						status: "open",
						openedAt: new Date(),
						openedBy: creator.id,
						subject: subjectUser.id,
					})
					.returning();

				if (!ticket) throw new PublicError("failed to add ticket to database.");

				const ticketNumber = ticket.id;
				const paddedTicketNumber = String(ticketNumber).padStart(4, "0");

				const channel = await interaction.guild?.channels.create({
					name: `ticket-${paddedTicketNumber}`,
					type: ChannelType.GuildText,
					parent: ticketCategory,
				});

				if (!channel) throw new PublicError("failed to create Discord channel.");
				createdChannel = channel;

				await tx.update(tickets).set({ channelId: channel.id }).where(eq(tickets.id, ticket.id));
				await channel.send({ content: `Hi! Thanks for submitting a report.` });

				return channel.id;
			});
		});

		if (txResult.isErr()) {
			if (createdChannel) await Result.fromAsync(() => createdChannel?.delete());

			const error = txResult.unwrapErr();
			const message =
				error instanceof PublicError
					? `Failed to create ticket: ${error.message}`
					: "There was an error creating the ticket.";

			if (error instanceof Error) this.container.logger.error(error.message, error.stack);

			return interaction.reply({
				content: message,
				flags: ["Ephemeral"],
			});
		}

		const channelId = txResult.unwrap();
		interaction.reply({
			content: `Ticket created! See <#${channelId}>`,
			flags: ["Ephemeral"],
		});
	}

	public async createTicket(interaction: Subcommand.ChatInputCommandInteraction) {
		await this.doCreateTicket(interaction);
	}
	public async createTicketFor(interaction: Subcommand.ChatInputCommandInteraction) {
		await this.doCreateTicket(interaction);
	}

	public async openTicket(interaction: Subcommand.ChatInputCommandInteraction) {
		interaction.reply({ content: "Ticket opened!" });
	}

	public async closeTicket(interaction: Subcommand.ChatInputCommandInteraction) {
		interaction.reply({ content: "Ticket closed!" });
	}
}

container.stores.loadPiece({
	piece: TicketCommand,
	name: "ticket",
	store: "commands",
});