Skip to content

Your favorite shift management application!

10.9 KB
Raw Blame
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { withCalendarDay } from "@/lib/date-utils";
import {
  calendars,
  shifts,
  shiftPresets,
  calendarNotes,
  calendarPermissionBundles,
} from "@/lib/db/schema";
import { eq, sql } from "drizzle-orm";
import { getSessionUser } from "@/lib/auth/sessions";
import {
  canViewCalendar,
  canDeleteCalendar,
  getCalendarAccess,
} from "@/lib/auth/permissions";
import {
  assertBundleWithinCallerCapabilities,
  handleBundleServiceError,
  resolveGuestEligibleBundle,
} from "@/lib/auth/permission-bundles-service";
import {
  calendarViewSettingsEqual,
  sanitizeCalendarViewSettings,
} from "@/lib/view-settings";
import {
  logUserAction,
  type CalendarUpdatedMetadata,
  type CalendarDeletedMetadata,
  type CalendarGuestBundleChangedMetadata,
} from "@/lib/audit-log";

// GET single calendar
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const user = await getSessionUser(request.headers);

    const [calendar] = await db
      .select()
      .from(calendars)
      .where(eq(calendars.id, id));

    if (!calendar) {
      return NextResponse.json(
        { error: "Calendar not found" },
        { status: 404 }
      );
    }

    // Check read permission (works for both authenticated users and guests)
    const hasAccess = await canViewCalendar(user?.id, id);
    if (!hasAccess) {
      return NextResponse.json(
        { error: "Insufficient permissions" },
        { status: 403 }
      );
    }

    const calendarShifts = await db
      .select()
      .from(shifts)
      .where(eq(shifts.calendarId, id))
      .orderBy(shifts.date);

    return NextResponse.json({ ...calendar, shifts: calendarShifts.map(withCalendarDay) });
  } catch (error) {
    console.error("Failed to fetch calendar:", error);
    return NextResponse.json(
      { error: "Failed to fetch calendar" },
      { status: 500 }
    );
  }
}

// PATCH update calendar (requires admin permission)
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const user = await getSessionUser(request.headers);
    const body = await request.json();
    const { name, color, guestBundleId, viewSettings, signupsEnabled, splitShiftsEnabled } = body;

    if (
      viewSettings !== undefined &&
      viewSettings !== null &&
      (typeof viewSettings !== "object" || Array.isArray(viewSettings))
    ) {
      return NextResponse.json(
        { error: "viewSettings must be an object or null" },
        { status: 400 }
      );
    }

    // Fetch current calendar
    const [existingCalendar] = await db
      .select()
      .from(calendars)
      .where(eq(calendars.id, id));

    if (!existingCalendar) {
      return NextResponse.json(
        { error: "Calendar not found" },
        { status: 404 }
      );
    }

    // guestBundleId is gated separately from the rest of the calendar's
    // settings — a bundle can hold manageCalendarSettings without
    // manageGuestAccess, or vice versa.
    const wantsGuestChange = guestBundleId !== undefined;
    const wantsGeneralChange =
      name !== undefined ||
      color !== undefined ||
      viewSettings !== undefined ||
      typeof signupsEnabled === "boolean" ||
      typeof splitShiftsEnabled === "boolean";

    const access = await getCalendarAccess(user?.id, id);
    const deny = () =>
      NextResponse.json(
        { error: "Insufficient permissions. Admin access required." },
        { status: 403 }
      );
    if (
      (wantsGeneralChange || !wantsGuestChange) &&
      !access?.can("manageCalendarSettings")
    ) {
      return deny();
    }
    if (wantsGuestChange && !access?.can("manageGuestAccess")) {
      return deny();
    }

    const updateData: Partial<typeof calendars.$inferInsert> = {};
    const changes: string[] = [];
    let guestBundleChanged = false;
    let oldGuestBundleId: string | null = null;
    let newGuestBundleId: string | null = null;
    let viewSettingsChange: CalendarUpdatedMetadata["viewSettings"];

    if (name && name !== existingCalendar.name) {
      updateData.name = name;
      changes.push("name");
    }
    if (color && color !== existingCalendar.color) {
      updateData.color = color;
      changes.push("color");
    }
    if (wantsGuestChange) {
      if (guestBundleId === null) {
        if (existingCalendar.guestBundleId !== null) {
          updateData.guestBundleId = null;
          changes.push("guestBundleId");
          guestBundleChanged = true;
          oldGuestBundleId = existingCalendar.guestBundleId;
          newGuestBundleId = null;
        }
      } else if (typeof guestBundleId === "string") {
        const bundle = await resolveGuestEligibleBundle(
          id,
          guestBundleId,
          "Bundle contains capabilities that cannot be granted to guests"
        );
        if (bundle instanceof NextResponse) return bundle;
        // A non-owner manageGuestAccess holder may only assign a bundle
        // whose capabilities are a subset of their own — closes the
        // self-escalation path a fixed cap used to guard against pre-PR.
        assertBundleWithinCallerCapabilities(access!, bundle.capabilities);
        if (guestBundleId !== existingCalendar.guestBundleId) {
          updateData.guestBundleId = guestBundleId;
          changes.push("guestBundleId");
          guestBundleChanged = true;
          oldGuestBundleId = existingCalendar.guestBundleId;
          newGuestBundleId = guestBundleId;
        }
      } else {
        return NextResponse.json(
          { error: "Invalid guestBundleId" },
          { status: 400 }
        );
      }
    }
    if (
      typeof signupsEnabled === "boolean" &&
      signupsEnabled !== existingCalendar.signupsEnabled
    ) {
      updateData.signupsEnabled = signupsEnabled;
      changes.push("signupsEnabled");
    }
    if (
      typeof splitShiftsEnabled === "boolean" &&
      splitShiftsEnabled !== existingCalendar.splitShiftsEnabled
    ) {
      updateData.splitShiftsEnabled = splitShiftsEnabled;
      changes.push("splitShiftsEnabled");
    }
    if (viewSettings === null && existingCalendar.viewSettings !== null) {
      updateData.viewSettings = null;
      changes.push("viewSettings");
      viewSettingsChange = "disabled";
    } else if (viewSettings) {
      const next = sanitizeCalendarViewSettings({
        ...(existingCalendar.viewSettings ?? {}),
        ...viewSettings,
      });
      if (
        !existingCalendar.viewSettings ||
        !calendarViewSettingsEqual(existingCalendar.viewSettings, next)
      ) {
        updateData.viewSettings = next;
        changes.push("viewSettings");
        viewSettingsChange = existingCalendar.viewSettings
          ? "updated"
          : "enabled";
      }
    }

    if (changes.length === 0) {
      return NextResponse.json(existingCalendar);
    }

    const [calendar] = await db
      .update(calendars)
      .set(updateData)
      .where(eq(calendars.id, id))
      .returning();

    // Log calendar update event if there were actual changes
    if (user && changes.length > 0) {
      await logUserAction<CalendarUpdatedMetadata>({
        action: "calendar.updated",
        userId: user.id,
        resourceType: "calendar",
        resourceId: calendar.id,
        metadata: {
          calendarName: calendar.name,
          changes,
          ...(viewSettingsChange && { viewSettings: viewSettingsChange }),
        },
        request,
      });

      // Log separate event for guest bundle changes
      if (guestBundleChanged) {
        const [oldBundle, newBundle] = await Promise.all([
          oldGuestBundleId
            ? db.query.calendarPermissionBundles.findFirst({
                where: eq(calendarPermissionBundles.id, oldGuestBundleId),
                columns: { name: true },
              })
            : null,
          newGuestBundleId
            ? db.query.calendarPermissionBundles.findFirst({
                where: eq(calendarPermissionBundles.id, newGuestBundleId),
                columns: { name: true },
              })
            : null,
        ]);
        await logUserAction<CalendarGuestBundleChangedMetadata>({
          action: "calendar.guest_permission.changed",
          userId: user.id,
          resourceType: "calendar",
          resourceId: calendar.id,
          metadata: {
            calendarName: calendar.name,
            oldBundleId: oldGuestBundleId,
            oldBundleName: oldBundle?.name ?? null,
            newBundleId: newGuestBundleId,
            newBundleName: newBundle?.name ?? null,
          },
          request,
        });
      }
    }

    return NextResponse.json(calendar);
  } catch (error) {
    return handleBundleServiceError(error, "Failed to update calendar");
  }
}

// DELETE calendar (requires owner permission)
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const user = await getSessionUser(request.headers);

    // Fetch calendar
    const [calendar] = await db
      .select()
      .from(calendars)
      .where(eq(calendars.id, id));

    if (!calendar) {
      return NextResponse.json(
        { error: "Calendar not found" },
        { status: 404 }
      );
    }

    // Check owner permission (works for both authenticated users and guests)
    const hasAccess = await canDeleteCalendar(user?.id, id);
    if (!hasAccess) {
      return NextResponse.json(
        { error: "Insufficient permissions. Owner access required." },
        { status: 403 }
      );
    }

    // Count related records before deletion
    const [{ shiftsCount, presetsCount, notesCount }] = await db
      .select({
        shiftsCount: sql<number>`(SELECT COUNT(*) FROM ${shifts} WHERE ${shifts.calendarId} = ${calendar.id})`,
        presetsCount: sql<number>`(SELECT COUNT(*) FROM ${shiftPresets} WHERE ${shiftPresets.calendarId} = ${calendar.id})`,
        notesCount: sql<number>`(SELECT COUNT(*) FROM ${calendarNotes} WHERE ${calendarNotes.calendarId} = ${calendar.id})`,
      })
      .from(calendars)
      .where(eq(calendars.id, id));

    // Delete calendar (cascade will delete related records)
    await db.delete(calendars).where(eq(calendars.id, id));

    // Log calendar deletion event
    if (user) {
      await logUserAction<CalendarDeletedMetadata>({
        action: "calendar.deleted",
        userId: user.id,
        resourceType: "calendar",
        resourceId: calendar.id,
        metadata: {
          calendarName: calendar.name,
          shiftsDeleted: shiftsCount,
          presetsDeleted: presetsCount,
          notesDeleted: notesCount,
        },
        request,
      });
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Failed to delete calendar:", error);
    return NextResponse.json(
      { error: "Failed to delete calendar" },
      { status: 500 }
    );
  }
}