all repos — stealth-developers @ d06e74e90dd3c88a7b74708880d1c73ec5d7eff2

src/interactions/commands/tickets/gdpr.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
import { db, tickets } from "@/database";
import { getTicketByNumericId } from "@/database/queries";
import { hasManagerPermissions } from "@/utils/discord/permissions";
import { loggers } from "@/utils/logging";
import { generateTranscript } from "@/utils/tickets/transcripts";
import {
	ActionRowBuilder,
	ButtonBuilder,
	type ButtonInteraction,
	ButtonStyle,
	type ChatInputCommandInteraction,
	type Client,
	ContainerBuilder,
	type GuildMember,
	SeparatorBuilder,
	TextDisplayBuilder,
} from "discord.js";
import { eq } from "drizzle-orm";
import { PAGINATION_SIZE, getTicketContainer } from "./_shared";

const logger = loggers.interactions.child({ name: "ticket/gdpr" });

async function buildListContainerForUser(userId: string, page = 1) {
	const ticketsRes = await db
		.select()
		.from(tickets)
		.where(eq(tickets.authorId, userId));

	if (!ticketsRes || ticketsRes.length === 0) {
		const empty = new ContainerBuilder()
			.setAccentColor(0xff5a00)
			.addTextDisplayComponents(
				new TextDisplayBuilder().setContent(
					"## Your Tickets\n\nYou have no tickets.",
				),
			);
		return { container: empty, totalPages: 0, page: 1, total: 0 };
	}

	const sortedTickets = ticketsRes.sort((a, b) => {
		const dateA = a.closedAt ?? a.createdAt;
		const dateB = b.closedAt ?? b.createdAt;
		return dateB.getTime() - dateA.getTime();
	});

	const total = sortedTickets.length;
	const totalPages = Math.max(1, Math.ceil(total / PAGINATION_SIZE));
	const currentPage = Math.min(Math.max(1, page), totalPages);

	const paged = sortedTickets.slice(
		(currentPage - 1) * PAGINATION_SIZE,
		currentPage * PAGINATION_SIZE,
	);

	const tsExact = (d: string | Date) => {
		const date = new Date(d);
		return `<t:${Math.floor(date.getTime() / 1000)}:f>`;
	};
	const tsRelative = (d: string | Date) => {
		const date = new Date(d);
		return `<t:${Math.floor(date.getTime() / 1000)}:R>`;
	};

	const ticketLines = paged.map((t) => {
		let id = `**#${t.anonymousId}**`;
		if (t.closedAt) id = `~~**${id}**~~ (closed)`;

		const created = `${tsExact(t.createdAt)} (${tsRelative(t.createdAt)})`;
		const closed = t.closedAt
			? `\n  * opened ${tsExact(t.closedAt)} (${tsRelative(t.closedAt)})`
			: "";
		return `- ${id}\n  * created ${created}${closed}`;
	});

	const header = `## Your Tickets - ${total} total\n`;

	const container = new ContainerBuilder()
		.setAccentColor(0xff5a00)
		.addTextDisplayComponents(
			new TextDisplayBuilder().setContent(`${header}${ticketLines.join("\n")}`),
		)
		.addSeparatorComponents(
			new SeparatorBuilder().setDivider(false).setSpacing(1),
		);

	const controls = new ActionRowBuilder<ButtonBuilder>().addComponents(
		new ButtonBuilder()
			.setDisabled(true)
			.setLabel(`Page ${currentPage} of ${totalPages}`)
			.setStyle(ButtonStyle.Secondary)
			.setCustomId("ticket:list:page_info"),
		new ButtonBuilder()
			.setCustomId(`ticket:list:page:${Math.max(1, currentPage - 1)}`)
			.setLabel("Prev")
			.setStyle(ButtonStyle.Primary)
			.setDisabled(currentPage <= 1),
		new ButtonBuilder()
			.setCustomId(`ticket:list:page:${Math.min(totalPages, currentPage + 1)}`)
			.setLabel("Next")
			.setStyle(ButtonStyle.Primary)
			.setDisabled(currentPage >= totalPages),
	);

	const nextPage = Math.min(currentPage + 1, totalPages);
	const prevPage = Math.max(currentPage - 1, 1);
	if (nextPage !== prevPage) container.addActionRowComponents(controls);

	return { container, totalPages, page: currentPage, total };
}

export async function handleListPagination(
	_client: Client,
	interaction: ButtonInteraction,
) {
	const parts = interaction.customId.split(":");
	const pagePart = parts[3];
	const page = pagePart ? Number.parseInt(pagePart, 10) : 1;

	if (Number.isNaN(page) || page < 1) {
		try {
			await interaction.reply({
				content: "Invalid page.",
				flags: ["Ephemeral"],
			});
		} catch {}
		return;
	}

	const { container } = await buildListContainerForUser(
		interaction.user.id,
		page,
	);

	try {
		await interaction.update({ components: [container] });
	} catch (err) {
		try {
			await interaction.reply({
				content: "Could not update page, try /ticket list again.",
				flags: ["Ephemeral"],
			});
		} catch {}
		logger.error(err, "failed to update ticket list pagination");
	}
}

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

	const { container } = await buildListContainerForUser(interaction.user.id, 1);

	await interaction.reply({
		components: [container],
		flags: ["IsComponentsV2", "Ephemeral"],
	});
}

export async function handleViewTicket(
	_client: Client,
	interaction: ChatInputCommandInteraction,
) {
	await interaction.deferReply();
	if (!interaction.guild) {
		await interaction.editReply({
			content: "❌ This command can only be used in a server.",
		});
		return;
	}

	const ticketId = interaction.options.getInteger("ticket_id", true);

	const { data: ticket, exists } = await getTicketByNumericId(
		interaction.guild.id,
		ticketId,
	);
	if (!exists || !ticket) {
		await interaction.editReply({
			content: `❌ Ticket with ID ${ticketId} not found.`,
		});
		return;
	}

	const isStaff = await hasManagerPermissions(
		interaction.member as GuildMember,
	);
	const isAuthor = ticket.authorId === interaction.user.id;

	if (!isStaff && !isAuthor) {
		await interaction.editReply({
			content: "❌ You don't have permission to view this ticket.",
		});
		return;
	}

	const { container, files } = await getTicketContainer(
		ticket,
		"view",
		!isStaff,
	);

	await interaction.editReply({
		components: [container],
		files: files,
		flags: ["IsComponentsV2"],
	});
}

export async function handleExport(
	_client: Client,
	interaction: ChatInputCommandInteraction,
) {
	const _tickets = await db
		.select()
		.from(tickets)
		.where(eq(tickets.authorId, interaction.user.id));

	const transcripts = await Promise.all(
		_tickets.map(async (ticket) => {
			const [transcriptText] = await generateTranscript(ticket);
			return transcriptText;
		}),
	);

	const combined = transcripts.join("\n\n\n\n");
	await interaction.reply({
		content: "Here is your exported ticket data:",
		files: [
			{
				attachment: Buffer.from(combined, "utf-8"),
				name: `tickets-export-${interaction.user.id}.txt`,
			},
		],
		flags: ["Ephemeral"],
	});
}