all repos — stealth-developers @ fcf415d87df5c195a36df6bb1201baee5cb662bc

apps/bot/src/feats/tickets/actions.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
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
import { randomUUID } from "node:crypto";
import {
	TextChannel,
	ChannelType,
	type Guild,
	type Channel,
	ContainerBuilder,
	TextDisplayBuilder,
	ActionRowBuilder,
	DiscordAPIError,
	Message,
} from "discord.js";
import { Result } from "@sapphire/framework";
import { ButtonBuilder } from "discord.js";

import db, {
	addTicketComment,
	desc,
	editTicket,
	eq,
	getGuildByDiscordId,
	getTicketByChannelId,
	tickets,
	type Actor,
	type TicketWithRelations,
} from "@stealth-developers/db";

import { upsertUser, getCategory, PublicError, logger } from "@/lib";
import { hasAccessToTicket } from "@/lib/tickets";
import { client } from "@/client";
import type { AnyUser, MessageSendPayload } from "@/types";

import { TicketButtonPresets } from "./buttons";
import { TicketModalPresets } from "./modals";
import { getGuildActor } from "../guild-actor";
import type { TicketContext } from "./types";

type CreateTicketArgs =
	| undefined
	| {
			for: AnyUser;
			reason?: string;
	  };

const text = (content: string) => new TextDisplayBuilder().setContent(content);

export async function createTicket(
	opener: AnyUser,
	guild: Guild,
	args?: CreateTicketArgs,
): Promise<{ channelId: string; publicId: string }> {
	const isOnBehalf = !!args?.for;
	const publicId = randomUUID();

	const dbGuild = await getGuildByDiscordId(guild.id);
	if (!dbGuild) throw new PublicError("Failed to create ticket: Guild not found in database");

	const creator = await upsertUser(opener, guild);
	if (!creator) throw new PublicError("Failed to create ticket: Creator user not found");

	const subject = isOnBehalf ? args?.for : opener;
	const subjectUser = subject ? await upsertUser(subject, guild) : creator;
	if (!subjectUser) throw new PublicError("Failed to create ticket: Subject user not found");

	if (isOnBehalf && !creator.moderator)
		throw new PublicError("You don't have permission to create a ticket for another user.");

	if (!dbGuild.ticketCategory)
		throw new PublicError(
			"Ticket category is not set up in this guild. Please contact an administrator.",
		);
	const ticketCategory = await getCategory(dbGuild.ticketCategory);
	let createdChannel: TextChannel | undefined = undefined;

	const canDm = await canDmUser(subject);

	const txResult = await Result.fromAsync(async () => {
		return await db.transaction(async (tx) => {
			const [maxTicket] = await tx
				.select({ localId: tickets.localId })
				.from(tickets)
				.where(eq(tickets.guildId, creator.guildId))
				.orderBy(desc(tickets.localId))
				.limit(1);

			const localId = (maxTicket?.localId ?? 0) + 1;

			const [ticket] = await tx
				.insert(tickets)
				.values({
					id: publicId,
					guildId: creator.guildId,
					localId: localId,
					status: "provisioning",
					openedAt: new Date(),
					openedBy: creator.id,
					subject: subjectUser.id,
				})
				.returning();

			if (!ticket) throw new PublicError("Failed to add ticket to database, please try again.");

			const channel = await guild.channels.create({
				name: channelName(localId, ticket.status),
				type: ChannelType.GuildText,
				parent: ticketCategory,
			});

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

			const greeting = dbGuild.ticketGreeting;
			const components = [];

			if (greeting)
				components.push(
					new ContainerBuilder()
						.setAccentColor(0x3a9027)
						.addTextDisplayComponents(
							new TextDisplayBuilder({
								content: greeting.replaceAll("{user}", `<@${subjectUser.discordId}>`),
							}),
						)
						.addActionRowComponents(
							new ActionRowBuilder<ButtonBuilder>().addComponents(
								TicketButtonPresets.claimTicketButton(publicId),
								TicketButtonPresets.closeTicketButton(publicId),
							),
						),
				);

			if (!canDm)
				components.push(
					new ContainerBuilder()
						.setAccentColor(0xdf8e1d)
						.addTextDisplayComponents(
							new TextDisplayBuilder().setContent("## I can't DM you!"),
							new TextDisplayBuilder().setContent(
								[
									"You won't receive a notification once your ticket has been handled.",
									`To check the outcome, you can use the \`/ticket view\` command with the ID \`${ticket.localId}\``,
									"or, see all of your tickets with `/ticket manage list`.",
								].join(" "),
							),
						),
				);

			components.push(
				new ContainerBuilder()
					.setAccentColor(0x3a9027)
					.addTextDisplayComponents(
						new TextDisplayBuilder({
							content: [
								"# Uploading Videos\n",
								"You can either upload your video directly to this channel, or",
								"you can use the button below to upload it directly to us, which",
								"allows you to upload videos up to 2GB in size.",
							].join(" "),
						}),
					)
					.addActionRowComponents(
						new ActionRowBuilder<ButtonBuilder>().addComponents(
							TicketButtonPresets.uploadLink(publicId),
						),
					),
			);

			await channel.send({
				components,
				flags: ["IsComponentsV2"],
			});

			await tx
				.update(tickets)
				.set({ channelId: channel.id, status: "open" })
				.where(eq(tickets.id, ticket.id));

			await channel.edit({
				name: channelName(localId, "open"),
			});

			return channel;
		});
	});

	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) logger.error(error.stack, error.message);

		throw new PublicError(message);
	}

	const channel = txResult.unwrap();
	return { channelId: channel.id, publicId };
}

export async function triggerCloseTicket(user: AnyUser, guild: Guild, channelId: string) {
	const dbGuild = await getGuildByDiscordId(guild.id);
	if (!dbGuild) throw new PublicError("Failed to create ticket: Guild not found in database");

	const dbUser = await upsertUser(user, guild);
	if (!dbUser) throw new PublicError("Failed to create ticket: User not found in database");

	const ticket = await getTicketByChannelId(channelId);
	if (!ticket) throw new PublicError("Failed to close ticket: Ticket not found in database");

	return TicketModalPresets.close(ticket.id, Boolean(dbUser.moderator));
}

/**
 * @param ticket the ticket to get the container for
 * @param limitedDetails whether to exclude comments & other internal details
 */
export function getTicketContainer(ticket: TicketWithRelations, limitedDetails = false) {
	const container = new ContainerBuilder();
	container.addTextDisplayComponents(text(`# Ticket #${ticket.localId} - ${ticket.status}`));

	let closedBySubject = true;
	if (ticket.status !== "open" && ticket.closedByActor && ticket.subjectActor) {
		closedBySubject = ticket.subjectActor.id === ticket.closedByActor.id;

		container.addTextDisplayComponents(
			text(`Closed by ${closedBySubject ? "the subject" : `<@${ticket.closedByActor.discordId}>`}`),
		);

		container.addTextDisplayComponents(text(["**Reason**", `> ${ticket.closeReason}`].join("\n")));

		if (!limitedDetails && ticket.privateReason)
			container.addTextDisplayComponents(
				text(["**Private Reason**", `> ${ticket.privateReason}`].join("\n")),
			);
	}

	const hasAttachments = ticket.attachments.length > 0;
	if (hasAttachments)
		container.addTextDisplayComponents(text(`**Attachments:** ${ticket.attachments.length}`));
	else container.addTextDisplayComponents(text("**Attachments:** no attachments"));

	container.addTextDisplayComponents(text(`-# ${ticket.id}`));

	const actionRow = new ActionRowBuilder<ButtonBuilder>();
	if (limitedDetails) actionRow.addComponents(TicketButtonPresets.thankButton(ticket.id));
	if (!limitedDetails)
		actionRow.addComponents(
			TicketButtonPresets.viewCommentsButton(ticket.id, ticket.comments.length),
		);
	actionRow.addComponents(TicketButtonPresets.transcriptsLink(ticket.id));

	container.addActionRowComponents(actionRow);
	return container;
}

export function getCommentContainer(ticketId: number, comments: TicketWithRelations["comments"]) {
	const formatTime = (date: Date) => `<t:${Math.floor(date.getTime() / 1000)}>`;

	const container = new ContainerBuilder();
	container.addTextDisplayComponents(
		new TextDisplayBuilder().setContent(`## Comments on #${String(ticketId).padStart(4, "0")}`),
	);

	if (!comments || comments.length === 0) {
		container.addTextDisplayComponents(new TextDisplayBuilder().setContent("No comments found"));
		return container;
	}

	const recentComments = comments.slice(-10);

	recentComments.forEach((comment) => {
		const authorMention = comment.actor?.discordId
			? `<@${comment.actor.discordId}>`
			: "Unknown User";

		const quotedContent = (comment.content || "")
			.split("\n")
			.map((line) => `> ${line}`)
			.join("\n");

		const commentString = `**${authorMention}** (${formatTime(comment.createdAt)})\n${quotedContent}`;

		container.addTextDisplayComponents(new TextDisplayBuilder().setContent(commentString));
	});

	return container;
}

/**
 *
 * @param user
 * @param ticketId
 * @param reasons
 * @param cleanup whether to delete the ticket channel immediately after closing
 * @returns
 */
export async function closeTicket(
	user: Actor,
	ticketId: string,
	reasons: { public: string; private?: string | null },
	cleanup: boolean = false,
) {
	const result = await editTicket(ticketId, {
		closedAt: new Date(),
		closeReason: reasons.public,
		privateReason: reasons.private,
		closedBy: user.id,
		status: "closed",
	});

	if (!result) throw new PublicError("Failed to close ticket: Ticket not found in database");

	const dbGuild = result.guild;
	if (!dbGuild) throw new PublicError("Failed to close ticket: Guild not found in database");

	const guild = await client.guilds.fetch(dbGuild.discordId);
	if (!guild) throw new PublicError("Failed to close ticket: Guild not found in Discord");

	if (!result.channelId)
		throw new PublicError("Failed to close ticket: Channel not found in database");

	const dbSubject = result.subjectActor;
	if (!dbSubject || !dbSubject.discordId)
		throw new PublicError("Failed to close ticket: Subject not found in database");

	const channel = await guild.channels.fetch(result.channelId);
	if (!channel || !channel.isTextBased())
		throw new PublicError("Failed to close ticket: Channel not found in database");

	if (cleanup) {
		await channel.delete();
	} else {
		channel.edit({
			name: channelName(result.localId, result.status),
		});

		const actionRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
			TicketButtonPresets.reopenTicketButton(ticketId),
			TicketButtonPresets.cleanTicketButton(ticketId),
		);

		messageChannel(channel, {
			content: `This ticket has been closed by <@${user.discordId}>.`,
			components: [actionRow],
			flags: ["SuppressNotifications"],
		});
	}

	const botActor = await getGuildActor(guild);
	if (!botActor) throw new PublicError("Failed to close ticket: Bot actor not found in database");

	const subject = await client.users.fetch(dbSubject.discordId);

	const container = getTicketContainer(result, true);

	const messageRes = await Result.fromAsync(
		messageUser(subject, {
			components: [container],
			flags: ["IsComponentsV2"],
		}),
	);

	if (messageRes.isErr()) {
		await addTicketComment({
			actorId: botActor.id,
			ticketId: result.id,
			content: `User has DMs closed, a notification was not sent.`,
		});
	}

	const logChannel = dbGuild.ticketLogChannel;
	if (!logChannel) {
		await addTicketComment({
			actorId: botActor.id,
			ticketId: result.id,
			content: `No log channel was found, a notification was not sent.`,
		});
	} else {
		const container = getTicketContainer(result, false);
		const commentContainer = getCommentContainer(result.localId, result.comments);

		const message = await Result.fromAsync(
			messageChannel(logChannel, {
				components: [container, commentContainer],
				flags: ["SuppressNotifications", "IsComponentsV2"],
				allowedMentions: { parse: [] },
			}),
		);

		if (message.isErr()) {
			await addTicketComment({
				actorId: botActor.id,
				ticketId: result.id,
				content: `Failed to send log message: ${message.unwrapErr()}`,
			});
		}
	}

	return result;
}

export async function reopenTicket(ctx: TicketContext) {
	const { actor, guild, ticket, ticketChannel } = ctx;
	if (ticket.status !== "closed") throw new PublicError("This ticket is not closed.");

	const canAccess = hasAccessToTicket(actor, guild, ticket, { requireModerator: true });
	if (!canAccess) throw new PublicError("You don't have permission to reopen this ticket.");

	const newTicket = await editTicket(ticket.id, {
		status: "open",
		closedAt: null,
		closedBy: null,

		claimedBy: actor.id,
		claimedAt: new Date(),
		lastClaimantActivityAt: new Date(),
	});

	if (ticketChannel) {
		const actionRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
			TicketButtonPresets.claimTicketButton(ticket.id),
			TicketButtonPresets.closeTicketButton(ticket.id),
		);

		messageChannel(ticketChannel, {
			content: `<@${actor.discordId}> reopened this ticket.`,
			flags: ["SuppressNotifications"],
			components: [actionRow],
		});

		if (ticketChannel.type === ChannelType.GuildText) {
			ticketChannel.edit({
				name: channelName(ticket.localId, "claimed", actor.displayName || actor.username!),
			});
		}
	}

	return newTicket;
}

export async function claimTicket(ctx: TicketContext) {
	const { ticket, actor, ticketChannel, guild } = ctx;
	if (ticket.status !== "open") throw new Error("Ticket is not open");

	const canAccess = hasAccessToTicket(actor, guild, ticket, { requireModerator: true });
	if (!canAccess) throw new PublicError("You don't have permission to reopen this ticket.");

	const lastClaimerActive = ticket.lastClaimantActivityAt
		? new Date(ticket.lastClaimantActivityAt)
		: null;

	// if the last claimer was active in the last 15 minutes, don't allow claiming
	if (lastClaimerActive && lastClaimerActive.getTime() > Date.now() - 1000 * 60 * 15) {
		const timeAgo = Math.floor(lastClaimerActive.getTime() / 1000);
		throw new PublicError(
			`This ticket was claimed by <@${ticket.claimedByActor?.discordId}> <t:${timeAgo}:R>.`,
		);
	}

	const newTicket = await editTicket(ticket.id, {
		claimedAt: new Date(),
		claimedBy: actor.id,
		lastClaimantActivityAt: new Date(),
	});

	if (ticketChannel) {
		const actionRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
			TicketButtonPresets.unclaimTicketButton(ticket.id),
		);

		messageChannel(ticketChannel, {
			content: `<@${actor.discordId}> has claimed this ticket, they will be with you shortly.`,
			flags: ["SuppressNotifications"],
			components: [actionRow],
		});

		if (ticketChannel.type === ChannelType.GuildText) {
			ticketChannel.edit({
				name: channelName(ticket.localId, "claimed", actor.displayName || actor.username!),
			});
		}
	}

	return newTicket;
}

export async function addComment(ctx: TicketContext, comment: string) {
	const { actor, guild, ticket } = ctx;

	const canAccess = hasAccessToTicket(actor, guild, ticket, { requireModerator: true });
	if (!canAccess)
		throw new PublicError("You don't have permission to add a comment to this ticket.");

	const dbComment = await addTicketComment({
		ticketId: ticket.id,
		actorId: actor.id,
		content: comment,
	});

	if (!dbComment) throw new PublicError("Failed to add comment to ticket.");
	return dbComment;
}

export async function unclaimTicket(ctx: TicketContext) {
	const { ticket, actor, ticketChannel, guild } = ctx;
	if (ticket.status !== "open") throw new Error("Ticket is not open");

	const canAccess = hasAccessToTicket(actor, guild, ticket, { requireModerator: true });
	if (!canAccess) throw new PublicError("You don't have permission to reopen this ticket.");

	if (ticket.claimedBy !== actor.id) throw new PublicError("You have not claimed this ticket.");

	const newTicket = await editTicket(ticket.id, {
		claimedAt: null,
		claimedBy: null,
		lastClaimantActivityAt: null,
	});

	if (ticketChannel) {
		const actionRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
			TicketButtonPresets.claimTicketButton(ticket.id),
		);
		messageChannel(ticketChannel, {
			content: `<@${actor.discordId}> unclaimed this ticket, someone else will be with you shortly.`,
			flags: ["SuppressNotifications"],
			components: [actionRow],
		});

		if (ticketChannel.type === ChannelType.GuildText) {
			ticketChannel.edit({
				name: channelName(ticket.localId, "open"),
			});
		}
	}

	return newTicket;
}

export async function cleanTicket(ctx: TicketContext) {
	const { ticket, actor, ticketChannel, guild } = ctx;
	if (ticket.status !== "closed")
		throw new Error("Tickets must be closed before they can be cleaned up.");

	const canAccess = hasAccessToTicket(actor, guild, ticket, { requireModerator: true });
	if (!canAccess) throw new PublicError("You don't have permission to clean up this ticket.");
	if (!ticketChannel) throw new PublicError("Ticket channel not found.");

	await editTicket(ticket.id, {
		channelId: null,
	});

	return await ticketChannel.delete("Ticket channel cleaned up");
}

export async function canDmUser(user: AnyUser): Promise<boolean> {
	if (!("send" in user)) return false;

	return user
		.send({
			content: "Hi! I'm just checking if your DMs are open.",
			flags: ["SuppressNotifications"],
		})
		.then(() => true)
		.catch(() => false);
}

export function channelName(localId: number, status: string, claimedBy?: string) {
	const initNumber = localId.toString().padStart(4, "0");

	// discord errors if we try to create channels with certain phrases in them
	const bad = ["1488", "1919"];
	if (bad.includes(initNumber)) return `${status}-filtered`;

	if (claimedBy) {
		const firstLetters = claimedBy.slice(0, 3);
		return `${firstLetters}-${status}-${initNumber}`;
	}

	return `${status}-ticket-${localId}`;
}

export async function messageUser(user: AnyUser, message: MessageSendPayload) {
	if (!("send" in user))
		throw new PublicError("Failed to message user: User is not a Discord user");

	const result = await Result.fromAsync(user.send(message));
	if (result.isErr()) {
		const error = result.unwrapErr();

		if (error instanceof DiscordAPIError && [50007, 50278].includes(error.code as number))
			throw new PublicError("Failed to message user: User has DMs disabled");
		throw error;
	}

	return result.unwrap();
}

export async function messageChannel(channelIn: string | Channel, message: MessageSendPayload) {
	const channel =
		typeof channelIn === "string" ? await client.channels.fetch(channelIn) : channelIn;
	if (!channel) throw new PublicError("Failed to message channel: Channel not found");

	if (!("send" in channel))
		throw new PublicError("Failed to message channel: Channel is not a text channel");

	const result = await Result.fromAsync<Message<boolean>>(channel.send(message));
	if (result.isErr()) {
		const error = result.unwrapErr();
		logger.warn({ error }, "Failed to message channel");

		if (error instanceof DiscordAPIError && [50007, 50278].includes(error.code as number))
			throw new PublicError("Failed to message channel: Channel is not a text channel");

		throw error;
	}

	return result.unwrap();
}