all repos — stealth-developers @ 2139da3743617ff966f14c44322f461fef88192c

apps/bot/src/feats/tickets/actions/comments.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
import { type TicketWithRelations, addTicketComment } from "@stealth-developers/db";
import { ContainerBuilder, TextDisplayBuilder } from "discord.js";

import { PublicError } from "@/lib";

import type { TicketContext } from "../types";

import { hasAccessToTicket } from "../lib";

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 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;
}