Skip to content

Self-hosted, plugin-based server management.

7.2 KB
Raw Blame
import type { AuthenticatedRequest } from "../../../types/index.js";
import express, { type Request, type Response } from "express";
import { databaseLogger } from "../../utils/logger.js";
import { AuthManager } from "../../utils/auth-manager.js";
import {
  createCurrentUiPreferenceRepository,
  createCurrentUserRepository,
} from "../repositories/factory.js";
import {
  defaultUiPreferences,
  sanitizeOnboarding,
  sanitizeUiPreferences,
  type UiPreferences,
} from "../../../types/ui-preferences.js";
import { LEGACY_SEEN, mergeSeen } from "../../../types/onboarding.js";

const router = express.Router();
const authManager = AuthManager.getInstance();
const authenticateJWT = authManager.createAuthMiddleware();

/** Accounts younger than this are treated as new and get onboarding. */
const NEW_ACCOUNT_WINDOW_MS = 24 * 60 * 60 * 1000;

/**
 * Existing users must never be ambushed by onboarding. A user who never
 * finished it and registered more than a day ago predates this feature, so
 * they count as having seen every core step, and the client silently marks
 * the plugin steps they have now as seen too (baselinePending).
 */
export function withOnboardingBackfill(
  preferences: UiPreferences,
  registeredAt: string | null | undefined,
): UiPreferences {
  const registeredMs = registeredAt ? Date.parse(registeredAt) : Number.NaN;
  const isNewAccount =
    Number.isFinite(registeredMs) &&
    Date.now() - registeredMs < NEW_ACCOUNT_WINDOW_MS;

  const { onboarding } = preferences;
  if (
    isNewAccount ||
    onboarding.completedAt ||
    Object.keys(onboarding.seen).length > 0
  ) {
    return preferences;
  }

  return {
    ...preferences,
    onboarding: {
      ...onboarding,
      seen: { ...LEGACY_SEEN },
      baselinePending: true,
    },
  };
}

/**
 * @openapi
 * /ui-preferences:
 *   get:
 *     summary: Get the UI complexity preferences for the current user
 *     description: Returns the current user's interface preset (simple, balanced, advanced or custom), their per-area overrides, and their onboarding state (which onboarding steps they have seen, by version). A first-time GET returns defaults without writing a row; a row is only created once the user actually changes something via PUT. Users who registered more than a day ago and never finished onboarding are returned as having seen every core step, so they are never shown the first-run flow.
 *     tags:
 *       - UI Preferences
 *     responses:
 *       200:
 *         description: The current user's UI preferences.
 */
router.get("/", authenticateJWT, async (req: Request, res: Response) => {
  const userId = (req as AuthenticatedRequest).userId;
  try {
    const existing =
      await createCurrentUiPreferenceRepository().findByUserId(userId);

    const stored = existing
      ? sanitizeUiPreferences(JSON.parse(existing.data))
      : defaultUiPreferences();
    if (stored.onboarding.completedAt) {
      return res.json({ preferences: stored });
    }

    const user = await createCurrentUserRepository().findById(userId);
    return res.json({
      preferences: withOnboardingBackfill(stored, user?.registeredAt),
    });
  } catch (e) {
    databaseLogger.error("Failed to get UI preferences", e, {
      operation: "get_ui_preferences",
      userId,
    });
    return res.status(500).json({ error: "Failed to get UI preferences" });
  }
});

/**
 * @openapi
 * /ui-preferences:
 *   put:
 *     summary: Update the UI complexity preferences for the current user
 *     description: Persists the current user's interface preset, per-area overrides and onboarding state as a single JSON document. Overrides are merged two levels deep, so a request only has to send the keys it changes. A null at a key clears that single override; a null at an area clears every override for that area; a null at overrides clears all of them. Onboarding seen versions are merged per step and never go down, so two open tabs cannot undo each other.
 *     tags:
 *       - UI Preferences
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *     responses:
 *       200:
 *         description: Preferences updated successfully.
 *       400:
 *         description: Invalid preferences payload.
 */
router.put("/", authenticateJWT, async (req: Request, res: Response) => {
  const userId = (req as AuthenticatedRequest).userId;

  if (!req.body || typeof req.body !== "object") {
    return res.status(400).json({ error: "Invalid preferences payload" });
  }

  try {
    const repository = createCurrentUiPreferenceRepository();
    const existing = await repository.findByUserId(userId);
    const stored = existing
      ? sanitizeUiPreferences(JSON.parse(existing.data))
      : defaultUiPreferences();
    const base = stored.onboarding.completedAt
      ? stored
      : withOnboardingBackfill(
          stored,
          (await createCurrentUserRepository().findById(userId))?.registeredAt,
        );

    const body = req.body as Record<string, unknown>;

    // Two levels of merging, with null meaning "clear this". A plain spread
    // could not express clearing an override, which the settings UI needs to
    // hand a knob back to the preset.
    const mergedOverrides: Record<string, Record<string, unknown>> = {
      ...(base.overrides as Record<string, Record<string, unknown>>),
    };

    if (body.overrides === null) {
      for (const area of Object.keys(mergedOverrides)) {
        delete mergedOverrides[area];
      }
    } else if (body.overrides && typeof body.overrides === "object") {
      for (const [area, patch] of Object.entries(
        body.overrides as Record<string, unknown>,
      )) {
        if (patch === null) {
          delete mergedOverrides[area];
          continue;
        }
        if (!patch || typeof patch !== "object") continue;

        const next = { ...(mergedOverrides[area] ?? {}) };
        for (const [key, value] of Object.entries(
          patch as Record<string, unknown>,
        )) {
          if (value === null) delete next[key];
          else next[key] = value;
        }
        mergedOverrides[area] = next;
      }
    }

    const merged = sanitizeUiPreferences({
      ...base,
      ...body,
      // Must come after the body spread, or a raw overrides payload would
      // clobber the merge above.
      overrides: mergedOverrides,
      onboarding: mergeOnboarding(base, body.onboarding),
    });

    await repository.upsert(userId, JSON.stringify(merged));

    return res.json({ success: true, preferences: merged });
  } catch (e) {
    databaseLogger.error("Failed to update UI preferences", e, {
      operation: "update_ui_preferences",
      userId,
    });
    return res.status(500).json({ error: "Failed to update UI preferences" });
  }
});

function mergeOnboarding(base: UiPreferences, patch: unknown) {
  if (!patch || typeof patch !== "object") return base.onboarding;
  const incoming = sanitizeOnboarding({
    ...base.onboarding,
    ...(patch as Record<string, unknown>),
    seen: (patch as Record<string, unknown>).seen ?? {},
  });
  return {
    ...incoming,
    seen: mergeSeen(base.onboarding.seen, incoming.seen),
    completedAt: incoming.completedAt ?? base.onboarding.completedAt,
  };
}

export default router;