all repos — stealth-developers @ 01d2e9fd4ff1d1ff4d424b2b2a5e0719a1cf763a

src/interactions/commands/bug/report.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
import config from "@/config.ts";
import {
	ActionRowBuilder,
	ButtonBuilder,
	type ButtonInteraction,
	ButtonStyle,
	ChannelType,
	type ChatInputCommandInteraction,
	type Client,
	EmbedBuilder,
	type GuildMember,
	ModalBuilder,
	type ModalSubmitInteraction,
	StringSelectMenuBuilder,
	type StringSelectMenuInteraction,
	StringSelectMenuOptionBuilder,
	TextInputBuilder,
	TextInputStyle,
} from "discord.js";
import {
	BugModel,
	GuildModel,
	getNextBugId,
} from "../../../database/schemas.ts";
import { createUserIfNotExists } from "../../../utils/exists.ts";
import { Logger } from "../../../utils/logging.ts";
import { hasManagerPermissions } from "../../../utils/permissions.ts";
import { PROJECT_MAP, getProjectName, updateBugEmbed } from "./shared.ts";

const logger = new Logger("bug-report");

export function getProjectChoices() {
	return Object.entries(PROJECT_MAP).map(([key, project]) => ({
		name: project.displayName,
		value: key,
	}));
}

export async function execute(
	_client: Client,
	interaction: ChatInputCommandInteraction,
) {
	const project = interaction.options.getString("project", true);

	const modal = new ModalBuilder()
		.setCustomId(`bug:${project}`)
		.setTitle(`report bug - ${getProjectName(project)}`);

	const titleInput = new TextInputBuilder()
		.setCustomId("title")
		.setLabel("bug title")
		.setStyle(TextInputStyle.Short)
		.setPlaceholder("short description of the bug")
		.setRequired(true)
		.setMaxLength(100);

	const descriptionInput = new TextInputBuilder()
		.setCustomId("description")
		.setLabel("bug description")
		.setStyle(TextInputStyle.Paragraph)
		.setPlaceholder("detailed description of the bug and steps to reproduce")
		.setRequired(true)
		.setMaxLength(1000);

	const firstRow = new ActionRowBuilder<TextInputBuilder>().addComponents(
		titleInput,
	);
	const secondRow = new ActionRowBuilder<TextInputBuilder>().addComponents(
		descriptionInput,
	);

	modal.addComponents(firstRow, secondRow);
	await interaction.showModal(modal);
}

export async function modalExecute(
	client: Client,
	interaction: ModalSubmitInteraction,
) {
	if (!interaction.guild) {
		await interaction.reply({
			content: "❌ this command can only be used in a server.",
			flags: ["Ephemeral"],
		});
		return;
	}

	const customIdParts = interaction.customId.split(":");
	const title = interaction.fields.getTextInputValue("title");
	const description = interaction.fields.getTextInputValue("description");

	// handle edit case
	if (customIdParts[1] === "edit") {
		const bugId = Number.parseInt(customIdParts[2]);

		try {
			const bug = await BugModel.findOne({ bug_id: bugId });
			if (!bug) {
				await interaction.reply({
					content: "❌ bug not found.",
					flags: ["Ephemeral"],
				});
				return;
			}

			bug.title = title;
			bug.description = description;
			await bug.save();

			if (bug.message_id && interaction.guild) {
				const guild = await GuildModel.findOne({
					guild_id: interaction.guild.id,
				});
				if (guild?.bug_channel) {
					await updateBugEmbed(client, bug, bug.message_id, guild.bug_channel);
				}
			}

			await interaction.reply({
				content: `✅ bug #${bug.bug_id} updated!`,
				flags: ["Ephemeral"],
			});
		} catch (error) {
			logger.error("failed to update bug:", error);
			await interaction.reply({
				content: "❌ failed to update bug. please try again later.",
				flags: ["Ephemeral"],
			});
		}
		return;
	}

	const project = customIdParts[1];

	try {
		await createUserIfNotExists(interaction.user.id, interaction.guild.id);

		const bugId = await getNextBugId();

		const bug = new BugModel({
			bug_id: bugId,
			user_id: interaction.user.id,
			project,
			title,
			description,
			status: "open",
			sent: false,
		});

		await bug.save();
		logger.info(`bug report created: ${bug._id}`);

		// send to bug channel if configured
		const guild = await GuildModel.findOne({
			guild_id: interaction.guild.id,
		});
		let msgUrl = "";

		if (guild?.bug_channel) {
			try {
				const channel = await client.channels.fetch(guild.bug_channel);
				if (channel?.type !== ChannelType.GuildText) {
					await interaction.reply({
						content: "❌ the bug channel is misconfigured",
					});
				}

				if (channel?.isTextBased() && "send" in channel) {
					const projectInfo = PROJECT_MAP[project as keyof typeof PROJECT_MAP];

					const embed = new EmbedBuilder()
						.setAuthor({
							name: interaction.user.displayName,
							url: `https://discord.com/users/${interaction.user.id}`,
							iconURL: interaction.user?.avatarURL() || undefined,
						})
						.setTitle(title)
						.setColor(0xff6b6b)
						.setDescription(description)
						.setFooter({ text: `${projectInfo.name} • bug #${bugId}` })
						.setTimestamp();

					if (projectInfo.iconURL) embed.setThumbnail(projectInfo.iconURL);

					const trelloUrlParts = [
						"https://trello.com/addCard?name=",
						encodeURIComponent(title),
						"&url=",
						encodeURIComponent(
							interaction.message?.url || "https://example.com",
						),
						"&idBoard=",
						config.data?.trelloBoardId || "",
					];

					const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
						new ButtonBuilder()
							.setCustomId(`bug:close:${bugId}`)
							.setLabel("close")
							.setStyle(ButtonStyle.Secondary)
							.setEmoji("🔒"),
						new ButtonBuilder()
							.setCustomId(`bug:edit:${bugId}`)
							.setLabel("edit")
							.setStyle(ButtonStyle.Primary),
						new ButtonBuilder()
							.setCustomId(`bug:delete:${bugId}`)
							.setLabel("delete")
							.setStyle(ButtonStyle.Danger),
						new ButtonBuilder()
							.setStyle(ButtonStyle.Link)
							.setLabel("add to trello")
							.setURL(trelloUrlParts.join("")),
						new ButtonBuilder()
							.setCustomId("bug:new")
							.setLabel("new bug")
							.setStyle(ButtonStyle.Success),
					);

					const message = await channel.send({
						embeds: [embed],
						components: [buttons],
					});

					try {
						const thread = await message.startThread({
							name: `#${bugId}: ${title.substring(0, 50)}${title.length > 50 ? "..." : ""}`,
							reason: `bug report thread for bug #${bugId}`,
						});

						await thread.members.add(interaction.user.id);
						await thread.send({
							content:
								`thread created for bug #${bugId} affecting ${projectInfo.displayName}.
							use this space to discuss the bug report, provide additional
							details, or ask questions.`
									.replace(/\s+/g, " ")
									.trim(),
						});

						bug.thread_id = thread.id;
						await bug.save();
					} catch (error) {}

					msgUrl = message.url;

					bug.message_id = message.id;
					bug.sent = true;
					await bug.save();

					logger.info(
						`sent bug report ${bug._id} to channel ${guild.bug_channel}`,
					);
				}
			} catch (error) {
				logger.error(`failed to send bug report to channel: ${error}`);
			}
		}

		await interaction.reply({
			content: `✅ bug report submitted! ${msgUrl}`,
			flags: ["Ephemeral"],
		});
	} catch (error) {
		logger.error("failed to create bug report:", error);
		await interaction.reply({
			content: "❌ failed to submit bug report. please try again later.",
			flags: ["Ephemeral"],
		});
	}
}

export async function buttonExecute(
	client: Client,
	interaction: ButtonInteraction,
) {
	const [, action, bugId] = interaction.customId.split(":");

	if (action === "new") {
		const options = Object.entries(PROJECT_MAP).map(([key, project]) =>
			new StringSelectMenuOptionBuilder()
				.setLabel(project.displayName)
				.setValue(key),
		);

		const selectMenu = new StringSelectMenuBuilder()
			.setCustomId("bug:project-select")
			.setPlaceholder("select a project")
			.addOptions(...options);

		const row = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
			selectMenu,
		);

		await interaction.reply({
			content: "select a project to report a bug for:",
			components: [row],
			flags: ["Ephemeral"],
		});
		return;
	}

	const member = interaction.member as GuildMember;
	const isManager = await hasManagerPermissions(member);

	const bug = await BugModel.findOne({ bug_id: Number.parseInt(bugId) });
	if (!bug) {
		await interaction.reply({
			content: "❌ bug not found.",
			flags: ["Ephemeral"],
		});
		return;
	}

	const isAuthor = bug.user_id === interaction.user.id;

	if (!isManager && !isAuthor) {
		await interaction.reply({
			content: "❌ you don't have permission to do this.",
			flags: ["Ephemeral"],
		});
		return;
	}

	switch (action) {
		case "close": {
			const newStatus = bug.status === "closed" ? "open" : "closed";
			bug.status = newStatus;
			await bug.save();

			if (bug.message_id && interaction.guild) {
				const guild = await GuildModel.findOne({
					guild_id: interaction.guild.id,
				});
				if (guild?.bug_channel) {
					await updateBugEmbed(client, bug, bug.message_id, guild.bug_channel);
				}
			}

			await interaction.reply({
				content: `✅ bug #${bug.bug_id} ${newStatus === "closed" ? "closed" : "reopened"}.`,
				flags: ["Ephemeral"],
			});
			break;
		}

		case "edit": {
			if (bug.status === "closed") {
				await interaction.reply({
					content: "❌ cannot edit a closed bug.",
					flags: ["Ephemeral"],
				});
				return;
			}

			const modal = new ModalBuilder()
				.setCustomId(`bug:edit:${bug.bug_id}`)
				.setTitle(`edit bug #${bug.bug_id}`);

			const titleInput = new TextInputBuilder()
				.setCustomId("title")
				.setLabel("bug title")
				.setStyle(TextInputStyle.Short)
				.setPlaceholder("short description of the bug")
				.setRequired(true)
				.setMaxLength(100)
				.setValue(bug.title);

			const descriptionInput = new TextInputBuilder()
				.setCustomId("description")
				.setLabel("bug description")
				.setStyle(TextInputStyle.Paragraph)
				.setPlaceholder(
					"detailed description of the bug and steps to reproduce",
				)
				.setRequired(true)
				.setMaxLength(1000)
				.setValue(bug.description);

			const firstRow = new ActionRowBuilder<TextInputBuilder>().addComponents(
				titleInput,
			);
			const secondRow = new ActionRowBuilder<TextInputBuilder>().addComponents(
				descriptionInput,
			);

			modal.addComponents(firstRow, secondRow);
			await interaction.showModal(modal);
			break;
		}

		case "delete": {
			bug.deleteOne();

			if (bug.message_id && interaction.guild) {
				const guild = await GuildModel.findOne({
					guild_id: interaction.guild.id,
				});
				if (guild?.bug_channel) {
					try {
						const channel = await client.channels.fetch(guild.bug_channel);
						if (channel?.isTextBased() && "messages" in channel) {
							const message = await channel.messages.fetch(bug.message_id);
							await message.delete();
						}
					} catch (error) {
						logger.error("failed to delete bug message:", error);
					}
				}
			}

			await interaction.reply({
				content: `✅ bug #${bug.bug_id} deleted.`,
				flags: ["Ephemeral"],
			});
			break;
		}
	}
}

export async function selectMenuExecute(
	_client: Client,
	interaction: StringSelectMenuInteraction,
) {
	if (interaction.customId !== "bug:project-select") return;

	const project = interaction.values[0];
	const modal = new ModalBuilder()
		.setCustomId(`bug:${project}`)
		.setTitle(`report bug - ${getProjectName(project)}`);

	const titleInput = new TextInputBuilder()
		.setCustomId("title")
		.setLabel("bug title")
		.setStyle(TextInputStyle.Short)
		.setPlaceholder("short description of the bug")
		.setRequired(true)
		.setMaxLength(100);

	const descriptionInput = new TextInputBuilder()
		.setCustomId("description")
		.setLabel("bug description")
		.setStyle(TextInputStyle.Paragraph)
		.setPlaceholder("detailed description of the bug and steps to reproduce")
		.setRequired(true)
		.setMaxLength(1000);

	const firstRow = new ActionRowBuilder<TextInputBuilder>().addComponents(
		titleInput,
	);
	const secondRow = new ActionRowBuilder<TextInputBuilder>().addComponents(
		descriptionInput,
	);

	modal.addComponents(firstRow, secondRow);
	await interaction.showModal(modal);
}

export const reportCommand = {
	execute,
	modalExecute,
	buttonExecute,
	selectMenuExecute,
	getProjectChoices,
};