Skip to content

Your favorite shift management application!

11.4 KB
Raw Blame
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { shiftPresets, shifts, calendars } from "@/lib/db/schema";
import { and, eq } from "drizzle-orm";
import { getSessionUser } from "@/lib/auth/sessions";
import { hasCapability, hasOwnedCapability } from "@/lib/auth/permissions";
import { trimOrNull } from "@/lib/utils";
import { replacePresetSegments, replaceShiftSegments, withPresetSegments } from "@/lib/shift-time-ranges";
import { normalizeTimeRanges, toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
import {
  getCalendarCustomFields,
  withPresetCustomFields,
  resolveCustomFieldValues,
  replacePresetCustomFieldValues,
  type CustomFieldValueRow,
} from "@/lib/shift-custom-fields";

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

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

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

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

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

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

    return NextResponse.json(preset);
  } catch (error) {
    console.error("Failed to fetch preset:", error);
    return NextResponse.json(
      { error: "Failed to fetch preset" },
      { status: 500 }
    );
  }
}

// PATCH update a preset
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await request.json();
    const {
      title,
      startTime,
      endTime,
      color,
      notes,
      groupName,
      isSecondary,
      isAllDay,
      hideFromStats,
      defaultSignupCapacity,
      segments: requestedSegments,
      customFields,
      archived,
    } = body;

    // groupName: undefined leaves it unchanged, null explicitly clears it,
    // strings are trimmed (empty -> cleared), anything else is invalid input.
    let normalizedGroupName: string | null | undefined;
    if (groupName === undefined || groupName === null) {
      normalizedGroupName = groupName;
    } else if (typeof groupName === "string") {
      normalizedGroupName = trimOrNull(groupName);
    } else {
      return NextResponse.json({ error: "Invalid groupName" }, { status: 400 });
    }

    const user = await getSessionUser(request.headers);

    // Fetch preset to get calendar ID
    const [existingPreset] = await db
      .select()
      .from(shiftPresets)
      .where(eq(shiftPresets.id, id));

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

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

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

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

    // An archive toggle is a request of its own and carries no other fields:
    // the generic update below rewrites every shift stamped from this preset,
    // which archiving must never do.
    if (archived !== undefined) {
      if (typeof archived !== "boolean") {
        return NextResponse.json({ error: "Invalid archived" }, { status: 400 });
      }
      const [toggled] = await db
        .update(shiftPresets)
        .set({ archivedAt: archived ? new Date() : null, updatedAt: new Date() })
        .where(eq(shiftPresets.id, id))
        .returning();
      const [withSegs] = await withPresetSegments([toggled]);
      const [result] = await withPresetCustomFields(
        [withSegs],
        await getCalendarCustomFields(existingPreset.calendarId)
      );
      return NextResponse.json(result);
    }

    const nextIsAllDay = isAllDay !== undefined ? isAllDay : existingPreset.isAllDay;
    // Mirrors the shift PUT handler: segments (and the normalized primary range) are only
    // ever written when split shifts is enabled, otherwise a round-tripped `segments: []`
    // from a client that can no longer see the stored rows would wipe them — including via
    // the cascade below, which would silently wipe every stamped child shift too.
    let nextStartTime = startTime;
    let nextEndTime = endTime;
    let nextSegments: TimeRange[] | undefined;
    if (requestedSegments !== undefined) {
      const rawSegments: TimeRange[] = Array.isArray(requestedSegments) ? requestedSegments : [];
      if (!nextIsAllDay) {
        if (rawSegments.length > 0 && !calendar.splitShiftsEnabled) {
          return NextResponse.json(
            { error: "Split shifts are not enabled for this calendar" },
            { status: 400 }
          );
        }
        const allRanges = toTimeRanges({
          startTime: startTime ?? existingPreset.startTime,
          endTime: endTime ?? existingPreset.endTime,
          segments: rawSegments,
        });
        const validationError = validateTimeRanges(allRanges);
        if (validationError) {
          return NextResponse.json({ error: validationError }, { status: 400 });
        }
        if (calendar.splitShiftsEnabled) {
          // Persisted primary is always the chronologically earliest range.
          const normalized = normalizeTimeRanges(allRanges);
          nextStartTime = normalized.startTime;
          nextEndTime = normalized.endTime;
          nextSegments = normalized.segments;
        }
      } else if (calendar.splitShiftsEnabled) {
        nextSegments = [];
      }
    }

    const customFieldDefinitions = await getCalendarCustomFields(existingPreset.calendarId);
    // null means "not mentioned in the request" — leave existing values untouched;
    // an empty object still resolves to [] and clears them.
    let customFieldValuesToPersist: CustomFieldValueRow[] | null = null;
    if (customFields !== undefined) {
      const resolved = resolveCustomFieldValues(customFieldDefinitions, customFields);
      if ("error" in resolved) {
        return NextResponse.json({ error: resolved.error }, { status: 400 });
      }
      customFieldValuesToPersist = resolved.values;
    }

    const updatedPreset = db.transaction((tx) => {
      const updated = tx
        .update(shiftPresets)
        .set({
          title,
          startTime: isAllDay ? "00:00" : nextStartTime,
          endTime: isAllDay ? "23:59" : nextEndTime,
          color,
          notes: notes || null,
          groupName: normalizedGroupName,
          isSecondary: isSecondary !== undefined ? isSecondary : undefined,
          isAllDay: isAllDay !== undefined ? isAllDay : undefined,
          hideFromStats: hideFromStats !== undefined ? hideFromStats : undefined,
          defaultSignupCapacity:
            defaultSignupCapacity !== undefined
              ? defaultSignupCapacity
              : undefined,
          updatedAt: new Date(),
        })
        .where(eq(shiftPresets.id, id))
        .returning()
        .get();

      if (nextSegments !== undefined) {
        replacePresetSegments(tx, id, nextSegments);
      }

      if (customFieldValuesToPersist !== null) {
        replacePresetCustomFieldValues(tx, id, customFieldValuesToPersist);
      }

      // Cascade to every shift created from this preset — title/time/color/
      // notes/isAllDay are already cascaded unconditionally below; segments
      // must follow the same rule so a preset's split-shift edit doesn't
      // silently stop propagating to shifts already created from it.
      const childShifts = tx
        .select({ id: shifts.id })
        .from(shifts)
        .where(
          and(
            eq(shifts.presetId, id),
            eq(shifts.calendarId, existingPreset.calendarId)
          )
        )
        .all();

      tx.update(shifts)
        .set({
          title,
          startTime: isAllDay ? "00:00" : nextStartTime,
          endTime: isAllDay ? "23:59" : nextEndTime,
          color,
          notes: notes || null,
          isAllDay: isAllDay !== undefined ? isAllDay : undefined,
          updatedAt: new Date(),
        })
        .where(
          and(
            eq(shifts.presetId, id),
            eq(shifts.calendarId, existingPreset.calendarId)
          )
        )
        .run();

      if (nextSegments !== undefined) {
        for (const child of childShifts) {
          replaceShiftSegments(tx, child.id, nextSegments);
        }
      }

      return updated;
    });

    const [withSegments] = await withPresetSegments([updatedPreset]);
    const [withCustomFields] = await withPresetCustomFields([withSegments], customFieldDefinitions);
    return NextResponse.json(withCustomFields);
  } catch (error) {
    console.error("Error updating preset:", error);
    return NextResponse.json(
      { error: "Failed to update preset" },
      { status: 500 }
    );
  }
}

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

    // Fetch preset to get calendar ID
    const [preset] = await db
      .select()
      .from(shiftPresets)
      .where(eq(shiftPresets.id, id));

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

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

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

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

    // Delete all shifts that were created from this preset
    await db
      .delete(shifts)
      .where(
        and(eq(shifts.presetId, id), eq(shifts.calendarId, preset.calendarId))
      );

    // Delete the preset
    await db.delete(shiftPresets).where(eq(shiftPresets.id, id));

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