All files / services supportTickets.ts

100% Statements 386/386
100% Branches 91/91
100% Functions 13/13
100% Lines 386/386

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 38724x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 15x 5x 20x 20x 15x 15x 15x 15x 15x 15x 15x 15x 14x 15x 2x 2x 2x 15x 20x 20x 18x 20x 20x 4x 14x 20x 20x 20x 20x 20x 20x 20x 20x 1x 1x 1x 1x 1x 1x 1x 20x 20x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 20x 20x 1x 1x 1x 20x 20x 3x 3x 3x 20x 20x 12x 12x 12x 12x 12x 12x 20x 1x 20x 11x 11x 11x 11x 11x 11x 8x 11x 11x 20x 1x 1x 1x 1x 1x 1x 1x 20x 20x 6x 6x 6x 6x 6x 6x 6x 20x 20x 12x 12x 12x 20x 1x 1x 17x 17x 17x 17x 17x 17x 17x 17x 1x 1x 17x 17x 17x 17x 16x 15x 15x 17x 17x 1x 1x 9x 9x 9x 9x 9x 9x 6x 3x 9x 9x 9x 9x 9x 8x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 9x 9x 9x 9x 9x 9x 2x 2x 9x 9x 7x 7x 7x 7x 9x 1x 1x 9x 9x 6x 9x 4x 1x 1x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 2x 2x 2x 2x 2x 2x 9x 9x 1x 1x 1x 1x 1x 9x 1x 8x 8x 8x 8x 8x 8x 8x 7x 7x 8x 8x 1x 1x 1x 1x 8x 1x 3x 3x 3x 3x 3x 1x 2x 2x 2x 2x 2x 1x 15x 15x 15x 15x 15x 15x 15x 3x 3x 15x 15x 6x 6x 15x 1x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 1x 1x 15x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 8x 1x 1x 1x  
import {
  convexBotClient,
  type DiscordSupportTicketId,
  type DiscordSupportTicketOpenInput,
  type DiscordSupportTicketOpenResult,
} from "@/services/convexBotClient"
import {
  fetchDiscordGuildRuntimeConfig,
  type DiscordGuildRuntimeConfig,
  type DiscordGuildRuntimeConfigResult,
} from "@/services/guildRuntimeConfig"
import {
  reportDiscordRuntimeError,
  type DiscordRuntimeErrorReporter,
} from "@/services/runtimeErrorReporter"
import { botLogError } from "@/utils/botLog"
import {
  ApplicationIntegrationType,
  ChannelType,
  MessageFlags,
  type ChatInputCommandInteraction,
  type ForumChannel,
  type Guild,
  type GuildBasedChannel,
  type MessageCreateOptions,
} from "discord.js"
 
type SupportTicketOpener = (
  input: DiscordSupportTicketOpenInput
) => Promise<DiscordSupportTicketOpenResult | null>
 
type RuntimeConfigFetcher = (
  discordGuildId: string
) => Promise<DiscordGuildRuntimeConfigResult>
 
type SupportTicketReadyResult = Exclude<
  DiscordSupportTicketOpenResult,
  { status: "guildSupportUnavailable" }
>
 
type GuildSupportTicketResult = SupportTicketReadyResult & {
  scope: "guild"
}
 
type GuildSupportNotifier = (
  interaction: ChatInputCommandInteraction,
  result: GuildSupportTicketResult,
  saveRoutingThread: SupportRoutingThreadSaver
) => Promise<boolean>
 
type SupportRoutingThreadSaver = (
  ticketId: DiscordSupportTicketId,
  threadId: string
) => Promise<void>
 
type SupportTicketOptions = {
  fetchConfig?: RuntimeConfigFetcher
  openTicket?: SupportTicketOpener
  notifyGuildSupport?: GuildSupportNotifier
  saveRoutingThread?: SupportRoutingThreadSaver
  logError?: typeof botLogError
  reportRuntimeError?: DiscordRuntimeErrorReporter
}
 
type SendableGuildChannel = GuildBasedChannel & {
  send(message: MessageCreateOptions): Promise<unknown>
}
 
export async function handleHelpCommand(
  interaction: ChatInputCommandInteraction,
  options: SupportTicketOptions = {}
): Promise<void> {
  const logError = options.logError ?? botLogError
  const reportRuntimeError =
    options.reportRuntimeError ?? reportDiscordRuntimeError
  const discordGuildId =
    interaction.guildId && !isUserInstallInteraction(interaction)
      ? interaction.guildId
      : undefined
 
  if (discordGuildId) {
    const configResult = await fetchGuildSupportConfig(
      discordGuildId,
      options.fetchConfig ?? fetchDiscordGuildRuntimeConfig,
      logError
    )
 
    if (
      configResult?.status !== "ready" ||
      !isGuildSupportReady(configResult.config)
    ) {
      await replyPrivately(interaction, guildSupportUnavailableContent)
      return
    }
  }
 
  const input: DiscordSupportTicketOpenInput = {
    requesterDiscordUserId: interaction.user.id,
    ...(discordGuildId ? { discordGuildId } : {}),
    ...(interaction.options.getString("message")?.trim()
      ? { message: interaction.options.getString("message", true) }
      : {}),
  }
  let result: DiscordSupportTicketOpenResult | null
 
  try {
    result = await (
      options.openTicket ?? convexBotClient.openOrResumeSupportTicket
    )(input)
  } catch (error) {
    result = null
    logError("Discord support ticket open failed.", error, {
      commandName: interaction.commandName,
      discordGuildId,
      discordUserId: interaction.user.id,
    })
  }
 
  if (!result) {
    await reportSupportRuntimeError({
      error: new Error("Convex support ticket open returned no result."),
      interaction,
      logError,
      reportRuntimeError,
    })
    await replyPrivately(
      interaction,
      "Cleo support is temporarily unavailable. Please try again shortly."
    )
    return
  }
 
  if (result.status === "guildSupportUnavailable") {
    await replyPrivately(interaction, guildSupportUnavailableContent)
    return
  }
 
  if (result.scope === "jcn") {
    await replyPrivately(interaction, formatRequesterConfirmation(result))
    return
  }
 
  const guildResult: GuildSupportTicketResult = {
    ...result,
    scope: "guild",
  }
  let notified = false
 
  try {
    if (guildResult.status === "resumed" && !guildResult.submittedMessage) {
      notified = true
    } else {
      notified = await (
        options.notifyGuildSupport ?? notifyConfiguredGuildSupport
      )(
        interaction,
        guildResult,
        options.saveRoutingThread ??
          convexBotClient.setSupportTicketRoutingThread
      )
    }
  } catch (error) {
    logError("Discord guild support notification failed.", error, {
      commandName: interaction.commandName,
      discordGuildId,
      discordUserId: interaction.user.id,
      discordChannelId: guildResult.route?.targetId,
    })
  }
 
  if (!notified) {
    await reportSupportRuntimeError({
      error: new Error("Configured guild support destination was unavailable."),
      interaction,
      logError,
      reportRuntimeError,
    })
  }
 
  await replyPrivately(
    interaction,
    formatRequesterConfirmation(guildResult, !notified)
  )
}
 
export function isUserInstallInteraction(
  interaction: Pick<ChatInputCommandInteraction, "authorizingIntegrationOwners">
): boolean {
  return (
    interaction.authorizingIntegrationOwners[
      ApplicationIntegrationType.UserInstall
    ] !== undefined
  )
}
 
export function isGuildSupportReady(
  config: DiscordGuildRuntimeConfig
): boolean {
  return Boolean(
    config.supportEnabled &&
    config.supportTargetId &&
    config.supportTargetType &&
    config.supportStaffRoleIds?.length
  )
}
 
export function formatSupportStaffMessage(
  result: GuildSupportTicketResult,
  requesterDiscordUserId: string
): MessageCreateOptions {
  const isNew = result.status === "opened"
  const roleMentions =
    isNew && result.route
      ? result.route.staffRoleIds.map((roleId) => `<@&${roleId}>`).join(" ")
      : ""
  const lines = [
    roleMentions,
    `**${isNew ? "New" : "Updated"} Cleo support request**`,
    `Requester: <@${requesterDiscordUserId}>`,
    ...(result.submittedMessage
      ? ["", result.submittedMessage]
      : ["", "_No message was submitted with `/help`._"]),
  ].filter((line, index) => line.length > 0 || index > 0)
 
  return {
    content: lines.join("\n"),
    allowedMentions: {
      parse: [],
      roles: isNew ? (result.route?.staffRoleIds ?? []) : [],
      users: [],
    },
  }
}
 
async function notifyConfiguredGuildSupport(
  interaction: ChatInputCommandInteraction,
  result: GuildSupportTicketResult,
  saveRoutingThread: SupportRoutingThreadSaver
): Promise<boolean> {
  if (!result.route || !interaction.guild) {
    return false
  }
 
  const channel = await resolveGuildChannel(
    interaction.guild,
    result.route.targetId
  )
 
  if (!channel) {
    return false
  }
 
  const message = formatSupportStaffMessage(result, interaction.user.id)
 
  if (result.route.targetType === "forum") {
    if (channel.type !== ChannelType.GuildForum) {
      return false
    }
 
    if (result.route.threadId) {
      const existingThread = await resolveGuildChannel(
        interaction.guild,
        result.route.threadId
      )
 
      if (existingThread && isSendableGuildChannel(existingThread)) {
        await existingThread.send(message)
        return true
      }
    }
 
    const thread = await (channel as ForumChannel).threads.create({
      name: `Support ยท ${sanitizeThreadName(interaction.user.username)}`,
      message,
    })
    await saveRoutingThread(result.ticketId, thread.id)
    return true
  }
 
  if (!isSendableGuildChannel(channel)) {
    return false
  }
 
  await channel.send(message)
  return true
}
 
async function resolveGuildChannel(
  guild: Guild,
  channelId: string
): Promise<GuildBasedChannel | null> {
  const cached = guild.channels.cache.get(channelId)
 
  if (cached) {
    return cached
  }
 
  try {
    return await guild.channels.fetch(channelId)
  } catch {
    return null
  }
}
 
function isSendableGuildChannel(
  channel: GuildBasedChannel
): channel is SendableGuildChannel {
  return channel.isTextBased() && channel.isSendable()
}
 
function sanitizeThreadName(value: string): string {
  const normalized = value.replaceAll(/[\r\n]/g, " ").trim()
 
  return (normalized || "Discord user").slice(0, 80)
}
 
function formatRequesterConfirmation(
  result: SupportTicketReadyResult,
  notificationDelayed = false
): string {
  const action = result.status === "opened" ? "opened" : "resumed"
 
  if (result.scope === "jcn") {
    return `Your JCN support request has been ${action}. JCN staff can review it privately in Cleo.`
  }
 
  return notificationDelayed
    ? `Your server support request has been ${action} and saved. The configured Discord notification could not be delivered, but server managers can still review it in the Cleo dashboard.`
    : `Your server support request has been ${action} and routed privately to this server's configured support team.`
}
 
async function fetchGuildSupportConfig(
  discordGuildId: string,
  fetchConfig: RuntimeConfigFetcher,
  logError: typeof botLogError
): Promise<DiscordGuildRuntimeConfigResult | null> {
  try {
    return await fetchConfig(discordGuildId)
  } catch (error) {
    logError("Discord support runtime config fetch failed.", error, {
      discordGuildId,
    })
    return null
  }
}
 
async function replyPrivately(
  interaction: ChatInputCommandInteraction,
  content: string
): Promise<void> {
  await interaction.reply({
    content,
    flags: MessageFlags.Ephemeral,
  })
}
 
async function reportSupportRuntimeError(args: {
  error: unknown
  interaction: ChatInputCommandInteraction
  logError: typeof botLogError
  reportRuntimeError: DiscordRuntimeErrorReporter
}): Promise<void> {
  try {
    await args.reportRuntimeError({
      severity: "error",
      serviceArea: "command",
      message: "Discord support ticket routing failed.",
      error: args.error,
      discordGuildId: args.interaction.guildId ?? undefined,
      commandName: args.interaction.commandName,
      operation: "openOrRouteSupportTicket",
      fingerprint: `support:openOrRoute:${args.interaction.guildId ?? "jcn"}`,
      metadata: {
        requesterDiscordUserId: args.interaction.user.id,
      },
    })
  } catch (reportError) {
    args.logError("Discord support runtime error report failed.", reportError, {
      commandName: args.interaction.commandName,
      discordGuildId: args.interaction.guildId ?? undefined,
    })
  }
}
 
const guildSupportUnavailableContent =
  "This server has not configured Cleo support yet. Ask a server admin to configure Support in the Cleo dashboard. For Cleo product help, run `/help` in a DM with Cleo."