projects/backend/convex/setupCheck.ts

import { v } from "convex/values"
import { internalMutation, mutation, query, type QueryCtx } from "./_generated/server.js"
import { internal } from "./_generated/api.js"
import type { DashboardOverview, DashboardSetupCheck } from "../dashboard-contracts.js"
import {
    SetupReadyRequest,
    SetupRecordRequest,
    SetupStatusRequest,
    type DashboardOverviewSection,
    type DashboardOverviewState,
    type SetupProblem,
    type SetupReadyResult,
    type SetupRecordResult,
    type SetupStatus,
} from "@neonflux/contracts/setup"
import { serviceMutation, serviceQuery } from "./serviceGuard.ts"
import { dashboardSession } from "./dashboard.ts"
import { readRolesSettings } from "./rolesStore.ts"
import { defaultRolesSettings } from "./rolesDomain.ts"
import { config as moderationConfig, readSettings as readModeration } from "./moderationStore.ts"
import { defaultGreetings } from "./greetingsDomain.ts"
import { defaultTickets } from "./ticketDomain.ts"
import { defaultLevelingSettings } from "./levelingDomain.ts"
import { readRolePicker } from "./rolePickerStore.ts"
import { readTemporaryRoleSettings } from "./temporaryRolesStore.ts"
import { readOnboarding } from "./onboardingStore.ts"
import { readLfgSettings } from "./lfg.ts"
import { readShowcaseSettings } from "./showcases.ts"
import { readProfileSettings } from "./profiles.ts"
import { youtubeSubscriptions } from "./youtubeStore.ts"
import { twitchSubscriptions } from "./twitchStore.ts"
import { feedSubscriptions } from "./feedStore.ts"
import { readReminderSettings } from "./remindersStore.ts"
import { readGiveawaySettings } from "./giveawaysStore.ts"
import { boardView } from "./boardsStore.ts"
import { counterView } from "./countersStore.ts"
import { decode } from "./validation.ts"
import { ringWork } from "./workSignal.ts"
import { publicAlerts, readAlerts } from "./alerts.ts"
import { readAntiNuke } from "./antiNuke.ts"
import { readLockdown } from "./lockdownStore.ts"
import { publicJailSettings, readJailSettings } from "./jailStore.ts"
import { publicRights, readRights } from "./rightsStore.ts"
import { alertActions, type AlertAction } from "@neonflux/contracts/alerts"
import { alertKinds } from "./alertsDomain.ts"
import { metadataTypes } from "./metadataLogsDomain.ts"

/** How long the bot has to answer a dashboard permission check */
export const SETUP_CHECK_MS = 60000
/** A new check waits this long after the previous one, so the refresh button cannot keep the bot reading Fluxer */
export const SETUP_CHECK_INTERVAL_MS = 10000

// Setup progress. A feature is on when it is enabled and has what it needs to act, needs setup when it is enabled without that, and off otherwise
const state = (enabled: boolean, ready = true): DashboardOverviewState => (!enabled ? "off" : ready ? "on" : "setup")
export async function readSetupSections(ctx: QueryCtx, serverId: string): Promise<DashboardOverview["sections"]> {
    const exists = (row: unknown) => row !== null
    const responses = await ctx.db
        .query("responseSettings")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()
    const definition = async (kind: "custom" | "auto") =>
        exists(
            await ctx.db
                .query("responseDefinitions")
                .withIndex("by_server_kind_name", (q) => q.eq("serverId", serverId).eq("kind", kind))
                .first(),
        )
    const moderation = moderationConfig(await readModeration(ctx, serverId))
    const cleanup = await ctx.db
        .query("cleanupSettings")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()
    const logs = await ctx.db
        .query("metadataLogSettings")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()
    const roles = (await readRolesSettings(ctx, serverId))?.config ?? defaultRolesSettings()
    // A rules panel with a role or a published message holds back role grants, events and birthdays even while verification is off,
    // so it counts as needing setup until members can accept it
    const rules = await ctx.db
        .query("rolePanels")
        .withIndex("by_server_kind", (q) => q.eq("serverId", serverId).eq("kind", "verification"))
        .unique()
    const rulesGate = Boolean(rules && (rules.published || rules.mappings.length)),
        rulesOpen = Boolean(roles.verificationEnabled && rules?.enabled && rules.published?.revision === rules.revision)
    const picker = await readRolePicker(ctx, serverId),
        onboarding = await readOnboarding(ctx, serverId)
    // Temporary roles have no switch. They are on while a grant or a role default exists
    const temporary =
        exists(
            await ctx.db
                .query("temporaryRoleGrants")
                .withIndex("by_server_end", (q) => q.eq("serverId", serverId))
                .first(),
        ) || (await readTemporaryRoleSettings(ctx, serverId)).roles.length > 0
    const publishing = await ctx.db
        .query("publishingSettings")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()
    const greetings =
        (
            await ctx.db
                .query("greetingSettings")
                .withIndex("by_server", (q) => q.eq("serverId", serverId))
                .unique()
        )?.config ?? defaultGreetings()
    const schedules = await ctx.db
        .query("scheduleSettings")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()
    const tickets =
        (
            await ctx.db
                .query("ticketSettings")
                .withIndex("by_server", (q) => q.eq("serverId", serverId))
                .unique()
        )?.config ?? defaultTickets()
    const leveling =
        (
            await ctx.db
                .query("levelingSettings")
                .withIndex("by_server", (q) => q.eq("serverId", serverId))
                .unique()
        )?.config ?? defaultLevelingSettings()
    const milestones = await ctx.db
        .query("milestoneSettings")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()
    const milestoneRoutes = await ctx.db
        .query("milestoneRoutes")
        .withIndex("by_kind", (q) => q.eq("serverId", serverId))
        .take(2)
    const suggestions = await ctx.db
        .query("suggestionSettings")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()
    const events = await ctx.db
        .query("eventSettings")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()
    const analytics = await ctx.db
        .query("analyticsSettings")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()
    const alerts = publicAlerts(await readAlerts(ctx, serverId))
    const helpDesk = await ctx.db
        .query("helpDeskSettings")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()
    const lfg = await readLfgSettings(ctx, serverId)
    const showcases = await readShowcaseSettings(ctx, serverId),
        profiles = await readProfileSettings(ctx, serverId),
        youtube = await youtubeSubscriptions(ctx, serverId),
        twitch = await twitchSubscriptions(ctx, serverId),
        feeds = await feedSubscriptions(ctx, serverId),
        boards = await boardView(ctx, serverId),
        counters = await counterView(ctx, serverId)
    const lockdown = await readLockdown(ctx, serverId)
    const jail = publicJailSettings(await readJailSettings(ctx, serverId)),
        rights = publicRights(await readRights(ctx, serverId))
    const routed = (routes: Array<{ enabled: boolean; channelId?: string }>) =>
        routes.some((route) => route.enabled && route.channelId)
    const securityRouted = Boolean(
        logs?.enabled &&
        (routed(logs.routes.filter((route) => route.category === "security")) ||
            routed(
                logs.eventRoutes.filter((route) =>
                    (metadataTypes.security as readonly string[]).includes(route.eventType),
                ),
            )),
    )
    return [
        { id: "custom", state: state(responses?.customEnabled ?? true, await definition("custom")) },
        { id: "auto", state: state(responses?.autoEnabled ?? true, await definition("auto")) },
        {
            id: "moderation",
            state: state(moderation.manualModerationEnabled || moderation.automodEnabled || moderation.securityEnabled),
        },
        {
            id: "cleanup",
            state: state(
                cleanup?.enabled ?? false,
                exists(
                    await ctx.db
                        .query("cleanupPolicies")
                        .withIndex("by_due", (q) => q.eq("serverId", serverId).eq("enabled", true))
                        .first(),
                ),
            ),
        },
        {
            id: "logs",
            state: state(logs?.enabled ?? false, Boolean(logs && (routed(logs.routes) || routed(logs.eventRoutes)))),
        },
        {
            id: "reaction",
            state: state(
                roles.panelsEnabled,
                exists(
                    await ctx.db
                        .query("rolePanels")
                        .withIndex("by_server_kind", (q) => q.eq("serverId", serverId).eq("kind", "reaction"))
                        .first(),
                ),
            ),
        },
        {
            id: "autorole",
            state: state(roles.autoroleEnabled, roles.autoroleIds.length > 0 || (roles.reservations ?? []).length > 0),
        },
        { id: "verification", state: state(roles.verificationEnabled || rulesGate, rulesOpen) },
        { id: "rolepicker", state: state(picker.enabled, picker.menus.length > 0) },
        { id: "temproles", state: state(temporary) },
        // The checklist acts once it has a step members finish through a feature
        {
            id: "onboarding",
            state: state(
                onboarding.enabled,
                onboarding.steps.some((step) => step.type !== "link"),
            ),
        },
        { id: "publishing", state: state(publishing?.enabled ?? true) },
        { id: "greetings", state: state(Object.values(greetings.routes).some((route) => route.enabled)) },
        { id: "schedules", state: state(schedules?.enabled ?? false, (schedules?.definitions ?? 0) > 0) },
        {
            id: "tickets",
            state: state(
                tickets.enabled,
                exists(
                    await ctx.db
                        .query("ticketCategories")
                        .withIndex("by_name", (q) => q.eq("serverId", serverId))
                        .first(),
                ),
            ),
        },
        { id: "leveling", state: state(leveling.enabled) },
        {
            id: "milestones",
            state: state(
                milestones?.enabled ?? false,
                milestoneRoutes.some((route) => route.configured && route.enabled),
            ),
        },
        { id: "suggestions", state: state(suggestions?.enabled ?? false, Boolean(suggestions?.channelId)) },
        { id: "events", state: state(events?.enabled ?? false) },
        {
            id: "voice",
            state: state(
                exists(
                    await ctx.db
                        .query("voiceGenerators")
                        .withIndex("by_channel", (q) => q.eq("serverId", serverId))
                        .first(),
                ),
            ),
        },
        { id: "analytics", state: state(analytics?.enabled ?? true) },
        {
            id: "sticky",
            state: state(
                exists(
                    await ctx.db
                        .query("stickyMessages")
                        .withIndex("by_channel", (q) => q.eq("serverId", serverId))
                        .first(),
                ),
            ),
        },
        {
            id: "sidebar",
            state: state(
                exists(
                    await ctx.db
                        .query("sidebarLinks")
                        .withIndex("by_server", (q) => q.eq("serverId", serverId))
                        .first(),
                ),
            ),
        },
        // Alerts reach staff through metadata logs, so they need the module on and the security category or one of its events routed
        {
            id: "alerts",
            state: state(
                alertKinds.some((kind) => alerts[kind]),
                securityRouted,
            ),
        },
        {
            id: "helpdesk",
            state: state(
                !!helpDesk &&
                    (helpDesk.forumIds.length > 0 || helpDesk.guardChannelId !== null || helpDesk.autoArchive),
            ),
        },
        // Groups need their channel and a voice generator for their rooms
        { id: "lfg", state: state(lfg.enabled, Boolean(lfg.channelId && lfg.generatorChannelId)) },
        { id: "showcase", state: state(showcases.enabled, showcases.channelId !== null) },
        { id: "profile", state: state(profiles.enabled) },
        // YouTube alerts are on while a server follows a channel, and need setup when NeonFlux turned every followed channel off
        {
            id: "youtube",
            state: state(
                youtube.length > 0,
                youtube.some((row) => row.enabled),
            ),
        },
        // A lockdown is on from its start until every channel it holds was restored
        {
            id: "lockdown",
            state: state(!!lockdown && lockdown.state !== "ended"),
        },
        // Its incidents need somewhere to reach staff: The staff log, or the metadata log's security category
        {
            id: "antinuke",
            state: state(
                (await readAntiNuke(ctx, serverId))?.enabled ?? false,
                moderation.logChannelId !== null || securityRouted,
            ),
        },
        // Jail needs its role and channel, which a setup makes. Rights need a role that holds one
        { id: "jail", state: state(jail.enabled, !!jail.roleId && !!jail.channelId) },
        { id: "rights", state: state(rights.enabled, rights.grants.length > 0) },
        // Twitch alerts are on while a server follows a channel, and need setup when NeonFlux turned every followed channel off
        {
            id: "twitch",
            state: state(
                twitch.length > 0,
                twitch.some((row) => row.enabled),
            ),
        },
        // Feeds are on while a server follows an account, and need setup when NeonFlux turned every followed account off
        {
            id: "feeds",
            state: state(
                feeds.length > 0,
                feeds.some((row) => row.enabled),
            ),
        },
        // Boards are on while a server has one, and need setup when NeonFlux stopped every board
        {
            id: "boards",
            state: state(
                boards.enabled && boards.boards.length > 0,
                boards.boards.some((row) => !row.problem),
            ),
        },
        // Reminders and giveaways need no setup, so they are on while their switches are
        { id: "reminders", state: state((await readReminderSettings(ctx, serverId)).enabled) },
        { id: "giveaways", state: state((await readGiveawaySettings(ctx, serverId)).enabled) },
        // Counters are on while a server has one, and need setup when NeonFlux turned every counter off
        {
            id: "counters",
            state: state(
                counters.enabled && counters.counters.length > 0,
                counters.counters.some((row) => row.enabled),
            ),
        },
    ]
}

/**
 * The roles each feature assigns, so the bot can check that its own role ranks above them. Every configured role is listed, since each
 * feature's own limit bounds its list. Temporary roles also list the roles of their grants, one grant read for each role
 */
async function managedRoles(ctx: QueryCtx, serverId: string): Promise<SetupStatus["managedRoles"]> {
    const roles = (await readRolesSettings(ctx, serverId))?.config ?? defaultRolesSettings()
    const panels = await ctx.db
        .query("rolePanels")
        .withIndex("by_server_name", (q) => q.eq("serverId", serverId))
        .take(100)
    const picker = await readRolePicker(ctx, serverId)
    const leveling = (
            await ctx.db
                .query("levelingSettings")
                .withIndex("by_server", (q) => q.eq("serverId", serverId))
                .unique()
        )?.config,
        onboarding = await readOnboarding(ctx, serverId)
    // A server has at most 250 roles. A deleted role keeps its grants until they end, so the walk stops after 1,000 roles, one read each
    const grantRoles: string[] = []
    for (let after: string | undefined; grantRoles.length < 1000;) {
        const next = await ctx.db
            .query("temporaryRoleGrants")
            .withIndex("by_server_role", (q) =>
                after === undefined ? q.eq("serverId", serverId) : q.eq("serverId", serverId).gt("roleId", after),
            )
            .first()
        if (!next) break
        grantRoles.push(next.roleId)
        after = next.roleId
    }
    const panelRoles = (kind: "reaction" | "verification") =>
        panels
            .filter((panel) => panel.kind === kind)
            .flatMap((panel) => panel.mappings.map((mapping) => mapping.roleId))
    const list = (feature: DashboardOverviewSection, roleIds: string[]) => ({
        feature,
        roleIds: [...new Set(roleIds)],
    })
    return [
        list("autorole", [
            ...roles.autoroleIds,
            ...(roles.reservations ?? []).flatMap((reservation) => reservation.roleIds),
        ]),
        list("reaction", panelRoles("reaction")),
        list("verification", panelRoles("verification")),
        list(
            "rolepicker",
            picker.menus.flatMap((menu) => menu.roleIds),
        ),
        list("temproles", [
            ...(await readTemporaryRoleSettings(ctx, serverId)).roles.map((role) => role.roleId),
            ...grantRoles,
        ]),
        list("leveling", leveling?.mappings.map((mapping) => mapping.roleId) ?? []),
        list("onboarding", onboarding.completionRoleId ? [onboarding.completionRoleId] : []),
    ].filter((entry) => entry.roleIds.length > 0)
}

const readCheck = (ctx: Pick<QueryCtx, "db">, serverId: string) =>
    ctx.db
        .query("dashboardSetupJobs")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()

/** What !setup, !health and the dashboard check read */
export const status = serviceQuery({
    args: { request: v.any() },
    handler: async (ctx, { request }): Promise<SetupStatus> => {
        const { serverId } = decode(SetupStatusRequest, request)
        const events = await ctx.db
                .query("eventSettings")
                .withIndex("by_server", (q) => q.eq("serverId", serverId))
                .unique(),
            alerts = publicAlerts(await readAlerts(ctx, serverId))
        const actions = (Object.keys(alertActions) as AlertAction[]).filter(
            (action) => alerts[action] && alerts[alertActions[action].alert],
        )
        const rightsNow = publicRights(await readRights(ctx, serverId))
        return {
            sections: await readSetupSections(ctx, serverId),
            managedRoles: await managedRoles(ctx, serverId),
            staffRoleIds: moderationConfig(await readModeration(ctx, serverId)).staffRoleIds,
            ...(rightsNow.enabled ? { rights: rightsNow } : {}),
            threadFeatures: events?.threads ? ["events"] : [],
            ...(actions.length ? { alertActions: actions } : {}),
        }
    },
})
/** Whether the website waits for a permission check from the bot */
export const ready = serviceQuery({
    args: { request: v.any() },
    handler: async (ctx, { request }): Promise<SetupReadyResult> => {
        const row = await readCheck(ctx, decode(SetupReadyRequest, request).serverId)
        return { queued: row?.state === "queued" && row.expiresAt > Date.now() }
    },
})

/** The bot's answer to a waiting check. A late answer is dropped, since the website already reports that the bot did not answer */
export const record = serviceMutation({
    args: { request: v.any() },
    handler: async (ctx, { request }): Promise<SetupRecordResult> => {
        const { serverId, problems } = decode(SetupRecordRequest, request, "Invalid permission check"),
            row = await readCheck(ctx, serverId),
            now = Date.now()
        if (row?.state !== "queued" || row.expiresAt <= now) return { recorded: false }
        await ctx.db.patch(row._id, { state: "done", checkedAt: now, problems })
        return { recorded: true }
    },
})

const viewArgs = { sessionToken: v.string(), serverId: v.string() }
export const view = query({
    args: viewArgs,
    handler: async (ctx, { sessionToken, serverId }): Promise<DashboardSetupCheck | null> => {
        await dashboardSession(ctx, sessionToken, serverId)
        const row = await readCheck(ctx, serverId)
        return row
            ? {
                  serverId,
                  state: row.state,
                  requestedAt: row.createdAt,
                  ...(row.checkedAt !== undefined ? { checkedAt: row.checkedAt } : {}),
                  problems: row.problems as SetupProblem[],
              }
            : null
    },
})
/** Ask the bot for a fresh check. The bot reads Fluxer with its own token, never the manager's sign-in */
export const request = mutation({
    args: viewArgs,
    handler: async (ctx, { sessionToken, serverId }) => {
        await dashboardSession(ctx, sessionToken, serverId)
        const row = await readCheck(ctx, serverId),
            now = Date.now()
        if (row && ((row.state === "queued" && row.expiresAt > now) || row.createdAt > now - SETUP_CHECK_INTERVAL_MS))
            return null
        const next = { state: "queued" as const, createdAt: now, expiresAt: now + SETUP_CHECK_MS }
        if (row) await ctx.db.patch(row._id, next)
        else await ctx.db.insert("dashboardSetupJobs", { serverId, ...next, problems: [] })
        await ctx.scheduler.runAt(next.expiresAt, internal.setupCheck.expire, { serverId })
        await ringWork(ctx)
        return null
    },
})
export const expire = internalMutation({
    args: { serverId: v.string() },
    handler: async (ctx, { serverId }) => {
        const row = await readCheck(ctx, serverId)
        if (row?.state === "queued" && row.expiresAt <= Date.now()) await ctx.db.patch(row._id, { state: "failed" })
    },
})