Skip to content

Your favorite shift management application!

feat: support split shifts with multiple time ranges (#208)

panteL6101766b2172
diff --git a/app/api/calendars/[id]/route.ts b/app/api/calendars/[id]/route.ts
index 5c3c8ad..438602d 100644
--- a/app/api/calendars/[id]/route.ts
+++ b/app/api/calendars/[id]/route.ts
@@ -85,7 +85,7 @@ export async function PATCH(
const { id } = await params;
const user = await getSessionUser(request.headers);
const body = await request.json();
- const { name, color, guestBundleId, viewSettings, signupsEnabled } = body;
+ const { name, color, guestBundleId, viewSettings, signupsEnabled, splitShiftsEnabled } = body;
if (
viewSettings !== undefined &&
@@ -119,7 +119,8 @@ export async function PATCH(
name !== undefined ||
color !== undefined ||
viewSettings !== undefined ||
- typeof signupsEnabled === "boolean";
+ typeof signupsEnabled === "boolean" ||
+ typeof splitShiftsEnabled === "boolean";
const access = await getCalendarAccess(user?.id, id);
const deny = () =>
@@ -193,6 +194,13 @@ export async function PATCH(
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");
diff --git a/app/api/calendars/route.ts b/app/api/calendars/route.ts
index da6eb71..7adb202 100644
--- a/app/api/calendars/route.ts
+++ b/app/api/calendars/route.ts
@@ -50,6 +50,7 @@ export async function GET(request: Request) {
ownerId: calendars.ownerId,
guestBundleId: calendars.guestBundleId,
signupsEnabled: calendars.signupsEnabled,
+ splitShiftsEnabled: calendars.splitShiftsEnabled,
viewSettings: calendars.viewSettings,
createdAt: calendars.createdAt,
updatedAt: calendars.updatedAt,
diff --git a/app/api/export/ics/route.ts b/app/api/export/ics/route.ts
index bd32d30..68d7875 100644
--- a/app/api/export/ics/route.ts
+++ b/app/api/export/ics/route.ts
@@ -7,6 +7,7 @@ import { getSessionUser } from "@/lib/auth/sessions";
import { hasCapability } from "@/lib/auth/permissions";
import { getServerTimezone, formatDateToLocal } from "@/lib/date-utils";
import { rateLimit } from "@/lib/rate-limiter";
+import { toTimeRanges } from "@/lib/time-ranges";
export async function POST(request: NextRequest) {
try {
@@ -55,14 +56,24 @@ export async function POST(request: NextRequest) {
}
// Get all shifts for accessible calendars
- const allShifts = await db.query.shifts.findMany({
+ let allShifts = await db.query.shifts.findMany({
where: inArray(
shifts.calendarId,
accessibleCalendars.map((c) => c.id)
),
orderBy: (shifts, { asc }) => [asc(shifts.date)],
+ with: { segments: true },
});
+ // A calendar that has since turned split shifts off must fall back to
+ // showing only its shifts' primary ranges, without deleting the stored segments.
+ const splitShiftsEnabledIds = new Set(
+ accessibleCalendars.filter((c) => c.splitShiftsEnabled).map((c) => c.id)
+ );
+ allShifts = allShifts.map((shift) =>
+ splitShiftsEnabledIds.has(shift.calendarId) ? shift : { ...shift, segments: [] }
+ );
+
// Create calendar name lookup
const calendarMap = new Map(accessibleCalendars.map((c) => [c.id, c.name]));
@@ -91,73 +102,58 @@ export async function POST(request: NextRequest) {
// Add shifts as events
for (const shift of allShifts) {
- const vevent = new ICAL.Component("vevent");
- const event = new ICAL.Event(vevent);
-
- // Set event ID
- event.uid = shift.id;
-
- // Set title with calendar prefix only for multi-calendar exports
+ const shiftDate = shift.date as Date;
const calendarName = calendarMap.get(shift.calendarId);
- event.summary = isMultiCalendar
+ const summary = isMultiCalendar
? `[${calendarName}] ${shift.title}`
: shift.title;
- // Set description (notes)
- if (shift.notes) {
- event.description = shift.notes;
- }
+ const ranges = shift.isAllDay ? [null] : toTimeRanges(shift);
- // Set times
- const shiftDate = shift.date as Date;
+ ranges.forEach((range, index) => {
+ const vevent = new ICAL.Component("vevent");
+ const event = new ICAL.Event(vevent);
- if (shift.isAllDay) {
- // All-day event (DTEND is exclusive per RFC 5545)
- const dateStr = formatDateToLocal(shiftDate);
-
- const startTime = ICAL.Time.fromDateString(dateStr);
- event.startDate = startTime;
-
- // DTEND must be the day after DTSTART for single-day all-day events
- const endDate = new Date(shiftDate);
- endDate.setDate(endDate.getDate() + 1);
- const endYear = endDate.getFullYear();
- const endMonth = String(endDate.getMonth() + 1).padStart(2, "0");
- const endDay = String(endDate.getDate()).padStart(2, "0");
- const endDateStr = `${endYear}-${endMonth}-${endDay}`;
-
- event.endDate = ICAL.Time.fromDateString(endDateStr);
- } else {
- // Timed event
- const [startHour, startMinute] = shift.startTime.split(":").map(Number);
- const [endHour, endMinute] = shift.endTime.split(":").map(Number);
-
- // Create date objects in server timezone
- const startDateTime = new Date(shiftDate);
- startDateTime.setHours(startHour, startMinute, 0, 0);
-
- const endDateTime = new Date(shiftDate);
- endDateTime.setHours(endHour, endMinute, 0, 0);
-
- // Handle shifts that end after midnight
- if (endDateTime <= startDateTime) {
- endDateTime.setDate(endDateTime.getDate() + 1);
+ event.uid = index === 0 ? shift.id : `${shift.id}-seg-${index}`;
+ event.summary = summary;
+ if (shift.notes) {
+ event.description = shift.notes;
}
- // Convert to UTC for iCalendar standard compliance
- const startIcalTime = ICAL.Time.fromJSDate(startDateTime, true);
- const endIcalTime = ICAL.Time.fromJSDate(endDateTime, true);
-
- event.startDate = startIcalTime;
- event.endDate = endIcalTime;
- }
+ if (!range) {
+ // All-day event (DTEND is exclusive per RFC 5545)
+ const dateStr = formatDateToLocal(shiftDate);
+ event.startDate = ICAL.Time.fromDateString(dateStr);
+
+ const endDate = new Date(shiftDate);
+ endDate.setDate(endDate.getDate() + 1);
+ const endYear = endDate.getFullYear();
+ const endMonth = String(endDate.getMonth() + 1).padStart(2, "0");
+ const endDay = String(endDate.getDate()).padStart(2, "0");
+ event.endDate = ICAL.Time.fromDateString(`${endYear}-${endMonth}-${endDay}`);
+ } else {
+ const [startHour, startMinute] = range.startTime.split(":").map(Number);
+ const [endHour, endMinute] = range.endTime.split(":").map(Number);
+
+ const startDateTime = new Date(shiftDate);
+ startDateTime.setHours(startHour, startMinute, 0, 0);
+
+ const endDateTime = new Date(shiftDate);
+ endDateTime.setHours(endHour, endMinute, 0, 0);
+
+ if (endDateTime <= startDateTime) {
+ endDateTime.setDate(endDateTime.getDate() + 1);
+ }
+
+ event.startDate = ICAL.Time.fromJSDate(startDateTime, true);
+ event.endDate = ICAL.Time.fromJSDate(endDateTime, true);
+ }
- // Set color (using X-APPLE-CALENDAR-COLOR for Apple Calendar compatibility)
- vevent.addPropertyWithValue("color", shift.color);
- vevent.addPropertyWithValue("x-apple-calendar-color", shift.color);
+ vevent.addPropertyWithValue("color", shift.color);
+ vevent.addPropertyWithValue("x-apple-calendar-color", shift.color);
- // Add event to calendar
- cal.addSubcomponent(vevent);
+ cal.addSubcomponent(vevent);
+ });
}
// Generate ICS content
diff --git a/app/api/export/pdf/route.ts b/app/api/export/pdf/route.ts
index 51f9cf0..b534db5 100644
--- a/app/api/export/pdf/route.ts
+++ b/app/api/export/pdf/route.ts
@@ -7,6 +7,7 @@ import { getSessionUser } from "@/lib/auth/sessions";
import { hasCapability } from "@/lib/auth/permissions";
import { rateLimit } from "@/lib/rate-limiter";
import { formatDateToLocal } from "@/lib/date-utils";
+import { formatTimeRange } from "@/lib/shift-display";
export async function POST(request: NextRequest) {
try {
@@ -66,8 +67,18 @@ export async function POST(request: NextRequest) {
accessibleCalendars.map((c) => c.id)
),
orderBy: (shifts, { asc }) => [asc(shifts.date)],
+ with: { segments: true },
});
+ // A calendar that has since turned split shifts off must fall back to
+ // showing only its shifts' primary ranges, without deleting the stored segments.
+ const splitShiftsEnabledIds = new Set(
+ accessibleCalendars.filter((c) => c.splitShiftsEnabled).map((c) => c.id)
+ );
+ allShifts = allShifts.map((shift) =>
+ splitShiftsEnabledIds.has(shift.calendarId) ? shift : { ...shift, segments: [] }
+ );
+
// Filter by month or year if provided
if (month) {
const [filterYear, filterMonth] = month.split("-").map(Number);
@@ -231,32 +242,35 @@ export async function POST(request: NextRequest) {
doc.setFont("helvetica", "bold");
doc.text(dateStr, margin + 6, yPosition);
- // Time
+ // Time — a split shift's joined range (e.g. "06:00 – 10:00, 15:00 – 21:00")
+ // can be wider than the fixed column, so later columns shift right to
+ // clear it instead of overlapping; short strings keep the original offsets.
+ const columnGap = 3;
doc.setFont("helvetica", "normal");
- const timeStr = shift.isAllDay
- ? "—" // Em dash for all-day shifts
- : `${shift.startTime} - ${shift.endTime}`;
+ const timeStr = shift.isAllDay ? "—" : formatTimeRange(shift);
doc.text(timeStr, margin + 35, yPosition);
+ const timeTextEnd = margin + 35 + doc.getTextWidth(timeStr);
// Calendar name (only for multi-calendar exports)
+ let titleX: number;
if (isMultiCalendar) {
doc.setFont("helvetica", "italic");
doc.setFontSize(9);
- doc.text(
- `[${calendarInfo?.name || "Unknown"}]`,
- margin + 70,
- yPosition
+ const calendarLabel = `[${calendarInfo?.name || "Unknown"}]`;
+ const calendarX = Math.max(margin + 70, timeTextEnd + columnGap);
+ doc.text(calendarLabel, calendarX, yPosition);
+ titleX = Math.max(
+ margin + 105,
+ calendarX + doc.getTextWidth(calendarLabel) + columnGap
);
+ } else {
+ titleX = Math.max(margin + 70, timeTextEnd + columnGap);
}
// Shift title
doc.setFont("helvetica", "bold");
doc.setFontSize(10);
- doc.text(
- shift.title,
- isMultiCalendar ? margin + 105 : margin + 70,
- yPosition
- );
+ doc.text(shift.title, titleX, yPosition);
yPosition += 5;
diff --git a/app/api/presets/[id]/route.ts b/app/api/presets/[id]/route.ts
index 24ea855..8a3ac37 100644
--- a/app/api/presets/[id]/route.ts
+++ b/app/api/presets/[id]/route.ts
@@ -5,6 +5,8 @@ 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";
// GET single preset
export async function GET(
@@ -79,6 +81,7 @@ export async function PATCH(
isAllDay,
hideFromStats,
defaultSignupCapacity,
+ segments: requestedSegments,
} = body;
// groupName: undefined leaves it unchanged, null explicitly clears it,
@@ -132,47 +135,115 @@ export async function PATCH(
);
}
- const [updatedPreset] = await db
- .update(shiftPresets)
- .set({
- title,
- startTime: isAllDay ? "00:00" : startTime,
- endTime: isAllDay ? "23:59" : endTime,
- 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();
-
- // Update all shifts that were created from this preset
- await db
- .update(shifts)
- .set({
- title,
- startTime: isAllDay ? "00:00" : startTime,
- endTime: isAllDay ? "23:59" : endTime,
- color,
- notes: notes || null,
- isAllDay: isAllDay !== undefined ? isAllDay : undefined,
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(shifts.presetId, id),
- eq(shifts.calendarId, existingPreset.calendarId)
+ 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 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);
+ }
+
+ // 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;
+ });
- return NextResponse.json(updatedPreset);
+ const [withSegments] = await withPresetSegments([updatedPreset]);
+ return NextResponse.json(withSegments);
} catch (error) {
console.error("Error updating preset:", error);
return NextResponse.json(
diff --git a/app/api/presets/route.ts b/app/api/presets/route.ts
index 7ec5add..d8fc1fe 100644
--- a/app/api/presets/route.ts
+++ b/app/api/presets/route.ts
@@ -5,6 +5,8 @@ import { eq, asc } from "drizzle-orm";
import { getSessionUser } from "@/lib/auth/sessions";
import { hasCapability } from "@/lib/auth/permissions";
import { trimOrNull } from "@/lib/utils";
+import { replacePresetSegments, withPresetSegments } from "@/lib/shift-time-ranges";
+import { normalizeTimeRanges, toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
// GET all presets for a calendar
export async function GET(request: NextRequest) {
@@ -48,7 +50,9 @@ export async function GET(request: NextRequest) {
.from(shiftPresets)
.where(eq(shiftPresets.calendarId, calendarId))
.orderBy(asc(shiftPresets.order));
- return NextResponse.json(presets);
+ return NextResponse.json(
+ calendar.splitShiftsEnabled ? await withPresetSegments(presets) : presets
+ );
} catch (error) {
console.error("Error fetching presets:", error);
return NextResponse.json(
@@ -74,6 +78,7 @@ export async function POST(request: NextRequest) {
isAllDay,
hideFromStats,
defaultSignupCapacity,
+ segments: requestedSegments,
} = body;
if (!calendarId || !title) {
@@ -118,29 +123,59 @@ export async function POST(request: NextRequest) {
? Math.max(...existingPresets.map((p) => p.order || 0))
: -1;
- const [preset] = await db
- .insert(shiftPresets)
- .values({
- calendarId,
- title,
- startTime: isAllDay ? "00:00" : startTime,
- endTime: isAllDay ? "23:59" : endTime,
- color: color || "#3b82f6",
- notes: notes || null,
- groupName: groupName ? trimOrNull(groupName) : null,
- isSecondary: isSecondary || false,
- isAllDay: isAllDay || false,
- hideFromStats: hideFromStats || false,
- defaultSignupCapacity:
- typeof defaultSignupCapacity === "number"
- ? defaultSignupCapacity
- : null,
- order: maxOrder + 1,
- createdBy: user?.id ?? null,
- })
- .returning();
-
- return NextResponse.json(preset);
+ const rawSegments: TimeRange[] = isAllDay || !Array.isArray(requestedSegments)
+ ? []
+ : requestedSegments;
+ if (rawSegments.length > 0 && !calendar.splitShiftsEnabled) {
+ return NextResponse.json(
+ { error: "Split shifts are not enabled for this calendar" },
+ { status: 400 }
+ );
+ }
+ let effectiveStartTime = startTime;
+ let effectiveEndTime = endTime;
+ let segmentsToPersist = rawSegments;
+ if (!isAllDay) {
+ const allRanges = toTimeRanges({ startTime, endTime, segments: rawSegments });
+ const validationError = validateTimeRanges(allRanges);
+ if (validationError) {
+ return NextResponse.json({ error: validationError }, { status: 400 });
+ }
+ // Persisted primary is always the chronologically earliest range.
+ const normalized = normalizeTimeRanges(allRanges);
+ effectiveStartTime = normalized.startTime;
+ effectiveEndTime = normalized.endTime;
+ segmentsToPersist = normalized.segments;
+ }
+
+ const preset = db.transaction((tx) => {
+ const inserted = tx
+ .insert(shiftPresets)
+ .values({
+ calendarId,
+ title,
+ startTime: isAllDay ? "00:00" : effectiveStartTime,
+ endTime: isAllDay ? "23:59" : effectiveEndTime,
+ color: color || "#3b82f6",
+ notes: notes || null,
+ groupName: groupName ? trimOrNull(groupName) : null,
+ isSecondary: isSecondary || false,
+ isAllDay: isAllDay || false,
+ hideFromStats: hideFromStats || false,
+ defaultSignupCapacity:
+ typeof defaultSignupCapacity === "number"
+ ? defaultSignupCapacity
+ : null,
+ order: maxOrder + 1,
+ createdBy: user?.id ?? null,
+ })
+ .returning()
+ .get();
+ replacePresetSegments(tx, inserted.id, segmentsToPersist);
+ return inserted;
+ });
+
+ return NextResponse.json({ ...preset, segments: segmentsToPersist });
} catch (error) {
console.error("Error creating preset:", error);
return NextResponse.json(
diff --git a/app/api/shifts/[id]/route.ts b/app/api/shifts/[id]/route.ts
index e2882b2..5c545d3 100644
--- a/app/api/shifts/[id]/route.ts
+++ b/app/api/shifts/[id]/route.ts
@@ -5,6 +5,8 @@ import { and, eq } from "drizzle-orm";
import { getSessionUser } from "@/lib/auth/sessions";
import { hasCapability, hasOwnedCapability } from "@/lib/auth/permissions";
import { parseLocalDate } from "@/lib/date-utils";
+import { replaceShiftSegments, withShiftSegments } from "@/lib/shift-time-ranges";
+import { normalizeTimeRanges, toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
// GET single shift
export async function GET(
@@ -34,6 +36,7 @@ export async function GET(
id: calendars.id,
name: calendars.name,
color: calendars.color,
+ splitShiftsEnabled: calendars.splitShiftsEnabled,
},
})
.from(shifts)
@@ -57,7 +60,11 @@ export async function GET(
);
}
- return NextResponse.json(result[0]);
+ if (!result[0].calendar?.splitShiftsEnabled) {
+ return NextResponse.json(result[0]);
+ }
+ const [withSegments] = await withShiftSegments([result[0]]);
+ return NextResponse.json(withSegments);
} catch (error) {
console.error("Failed to fetch shift:", error);
return NextResponse.json(
@@ -190,30 +197,80 @@ export async function PUT(
}
}
+ let nextStartTime = body.startTime ?? existingShift.startTime;
+ let nextEndTime = body.endTime ?? existingShift.endTime;
+ const nextIsAllDay = body.isAllDay ?? existingShift.isAllDay;
+
+ // Segments are only ever written when the calendar has split shifts enabled — otherwise
+ // a client that can no longer see stored segments (GET omits them while the flag is off)
+ // would round-trip `segments: []` on any unrelated edit and wipe the real stored rows.
+ let nextSegments: TimeRange[] | undefined;
+ if (body.segments !== undefined) {
+ const rawSegments: TimeRange[] = Array.isArray(body.segments) ? body.segments : [];
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, existingShift.calendarId));
+ 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: nextStartTime,
+ endTime: nextEndTime,
+ 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 = [];
+ }
+ }
+
// Update the shift
- const [updatedShift] = await db
- .update(shifts)
- .set({
- date,
- startTime: body.startTime ?? existingShift.startTime,
- endTime: body.endTime ?? existingShift.endTime,
- title: body.title ?? existingShift.title,
- color: body.color ?? existingShift.color,
- notes: body.notes ?? existingShift.notes,
- isAllDay: body.isAllDay ?? existingShift.isAllDay,
- presetId: body.presetId ?? existingShift.presetId,
- signupCapacity:
- typeof body.signupCapacity === "number"
- ? body.signupCapacity
- : body.signupCapacity === null
- ? null
- : existingShift.signupCapacity,
- updatedAt: new Date(),
- })
- .where(eq(shifts.id, id))
- .returning();
+ const updatedShift = db.transaction((tx) => {
+ const updated = tx
+ .update(shifts)
+ .set({
+ date,
+ startTime: nextStartTime,
+ endTime: nextEndTime,
+ title: body.title ?? existingShift.title,
+ color: body.color ?? existingShift.color,
+ notes: body.notes ?? existingShift.notes,
+ isAllDay: nextIsAllDay,
+ presetId: body.presetId ?? existingShift.presetId,
+ signupCapacity:
+ typeof body.signupCapacity === "number"
+ ? body.signupCapacity
+ : body.signupCapacity === null
+ ? null
+ : existingShift.signupCapacity,
+ updatedAt: new Date(),
+ })
+ .where(eq(shifts.id, id))
+ .returning()
+ .get();
+ if (nextSegments !== undefined) {
+ replaceShiftSegments(tx, id, nextSegments);
+ }
+ return updated;
+ });
- return NextResponse.json(updatedShift);
+ const [withSegments] = await withShiftSegments([updatedShift]);
+ return NextResponse.json(withSegments);
} catch (error) {
console.error("Failed to update shift:", error);
return NextResponse.json(
diff --git a/app/api/shifts/route.ts b/app/api/shifts/route.ts
index 0f36986..ea5ab48 100644
--- a/app/api/shifts/route.ts
+++ b/app/api/shifts/route.ts
@@ -7,6 +7,8 @@ import { hasCapability, getCalendarAccess } from "@/lib/auth/permissions";
import { addShiftSignup, withSignups } from "@/lib/shift-signups";
import { parseLocalDate } from "@/lib/date-utils";
import type { CalendarMember } from "@/lib/types";
+import { withShiftSegments, replaceShiftSegments, withPresetSegments } from "@/lib/shift-time-ranges";
+import { normalizeTimeRanges, toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
// GET shifts for a calendar (with optional date filter)
export async function GET(request: Request) {
@@ -98,7 +100,10 @@ export async function GET(request: Request) {
or(isNull(shifts.externalSyncId), eq(externalSyncs.isHidden, false))
)
);
- return NextResponse.json(await withSignups(result));
+ const withSigs = await withSignups(result);
+ return NextResponse.json(
+ calendar.splitShiftsEnabled ? await withShiftSegments(withSigs) : withSigs
+ );
}
const result = await query.where(
@@ -108,7 +113,10 @@ export async function GET(request: Request) {
or(isNull(shifts.externalSyncId), eq(externalSyncs.isHidden, false))
)
);
- return NextResponse.json(await withSignups(result));
+ const withSigs = await withSignups(result);
+ return NextResponse.json(
+ calendar.splitShiftsEnabled ? await withShiftSegments(withSigs) : withSigs
+ );
} catch (error) {
console.error("Failed to fetch shifts:", error);
return NextResponse.json(
@@ -135,6 +143,7 @@ export async function POST(request: Request) {
isSecondary,
signupCapacity,
signupUserIds,
+ segments: requestedSegments,
} = body;
if (!calendarId || !date || !title) {
@@ -194,6 +203,7 @@ export async function POST(request: Request) {
notes: string | null;
isAllDay: boolean;
};
+ let segmentsToPersist: TimeRange[] = [];
if (access.can("createShift")) {
if (presetId) {
const [preset] = await db
@@ -220,6 +230,28 @@ export async function POST(request: Request) {
notes: notes || null,
isAllDay: isAllDay || false,
};
+
+ if (!isAllDay) {
+ const rawSegments: TimeRange[] = Array.isArray(requestedSegments)
+ ? requestedSegments
+ : [];
+ if (rawSegments.length > 0 && !calendar.splitShiftsEnabled) {
+ return NextResponse.json(
+ { error: "Split shifts are not enabled for this calendar" },
+ { status: 400 }
+ );
+ }
+ const allRanges = toTimeRanges({ ...insertValues, segments: rawSegments });
+ const validationError = validateTimeRanges(allRanges);
+ if (validationError) {
+ return NextResponse.json({ error: validationError }, { status: 400 });
+ }
+ // Persisted primary is always the chronologically earliest range.
+ const normalized = normalizeTimeRanges(allRanges);
+ insertValues.startTime = normalized.startTime;
+ insertValues.endTime = normalized.endTime;
+ segmentsToPersist = normalized.segments;
+ }
} else {
if (!presetId) {
return NextResponse.json(
@@ -250,23 +282,32 @@ export async function POST(request: Request) {
notes: preset.notes,
isAllDay: preset.isAllDay,
};
+ if (!preset.isAllDay && calendar.splitShiftsEnabled) {
+ const [presetWithSegments] = await withPresetSegments([preset]);
+ segmentsToPersist = presetWithSegments.segments;
+ }
}
- const [shift] = await db
- .insert(shifts)
- .values({
- calendarId,
- presetId: presetId || null,
- date: parsedDate,
- ...insertValues,
- isSecondary: isSecondary || false,
- signupCapacity:
- typeof signupCapacity === "number" ? signupCapacity : null,
- createdBy: user?.id ?? null,
- createdAt: new Date(),
- updatedAt: new Date(),
- })
- .returning();
+ const shift = db.transaction((tx) => {
+ const inserted = tx
+ .insert(shifts)
+ .values({
+ calendarId,
+ presetId: presetId || null,
+ date: parsedDate,
+ ...insertValues,
+ isSecondary: isSecondary || false,
+ signupCapacity:
+ typeof signupCapacity === "number" ? signupCapacity : null,
+ createdBy: user?.id ?? null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .returning()
+ .get();
+ replaceShiftSegments(tx, inserted.id, segmentsToPersist);
+ return inserted;
+ });
// Best-effort: a shift the caller picked people for still gets created
// even if one of those signups is no longer valid by the time we get here.
@@ -291,7 +332,7 @@ export async function POST(request: Request) {
}
return NextResponse.json(
- { ...shift, calendar, signups },
+ { ...shift, calendar, signups, segments: segmentsToPersist },
{ status: 201 }
);
} catch (error) {
diff --git a/app/api/shifts/stats/route.ts b/app/api/shifts/stats/route.ts
index c3705c4..c3de06f 100644
--- a/app/api/shifts/stats/route.ts
+++ b/app/api/shifts/stats/route.ts
@@ -9,11 +9,9 @@ import {
import { eq, and, gte, lte, or, isNull } from "drizzle-orm";
import { getSessionUser } from "@/lib/auth/sessions";
import { hasCapability } from "@/lib/auth/permissions";
-import {
- calculateShiftDuration,
- formatDateToLocal,
- parseLocalDate,
-} from "@/lib/date-utils";
+import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";
+import { withShiftSegments } from "@/lib/shift-time-ranges";
+import { toTimeRanges, sumRangeDurations } from "@/lib/time-ranges";
import {
startOfWeek,
endOfWeek,
@@ -125,6 +123,10 @@ export async function GET(request: Request) {
)
);
+ const resultWithSegments = calendar.splitShiftsEnabled
+ ? await withShiftSegments(result)
+ : result;
+
// Group by title and calculate stats
const statsMap = new Map<string, { count: number; totalMinutes: number }>();
const dailyStats = new Map<
@@ -135,15 +137,13 @@ export async function GET(request: Request) {
let maxDuration = 0;
let nonAllDayShiftCount = 0; // Track shifts with duration for accurate average
- result.forEach((shift) => {
+ resultWithSegments.forEach((shift) => {
const existing = statsMap.get(shift.title) || {
count: 0,
totalMinutes: 0,
};
existing.count++;
- const duration = shift.isAllDay
- ? 0
- : calculateShiftDuration(shift.startTime, shift.endTime);
+ const duration = shift.isAllDay ? 0 : sumRangeDurations(toTimeRanges(shift));
existing.totalMinutes += duration;
statsMap.set(shift.title, existing);
@@ -204,7 +204,7 @@ export async function GET(request: Request) {
0
);
- const totalShifts = result.length;
+ const totalShifts = resultWithSegments.length;
const avgMinutesPerShift =
nonAllDayShiftCount > 0 ? totalMinutes / nonAllDayShiftCount : 0;
diff --git a/components/calendar-permissions-panel.tsx b/components/calendar-permissions-panel.tsx
index 36d0252..7da7439 100644
--- a/components/calendar-permissions-panel.tsx
+++ b/components/calendar-permissions-panel.tsx
@@ -39,9 +39,12 @@ export function PermissionsPanel({ calendarId, onClose, onDirtyChange }: Permiss
useReportDirty(linkForm.dirty, onDirtyChange);
const [optimisticSignupsEnabled, setOptimisticSignupsEnabled] = useState<boolean | null>(null);
+ const [optimisticSplitShiftsEnabled, setOptimisticSplitShiftsEnabled] = useState<boolean | null>(null);
const [saving, setSaving] = useState(false);
const calendar = calendars.find((c) => c.id === calendarId);
const signupsEnabled = optimisticSignupsEnabled ?? calendar?.signupsEnabled ?? true;
+ const splitShiftsEnabled =
+ optimisticSplitShiftsEnabled ?? calendar?.splitShiftsEnabled ?? false;
const handleSignupsEnabledChange = async (value: boolean) => {
if (value === signupsEnabled) return;
@@ -57,6 +60,20 @@ export function PermissionsPanel({ calendarId, onClose, onDirtyChange }: Permiss
}
};
+ const handleSplitShiftsEnabledChange = async (value: boolean) => {
+ if (value === splitShiftsEnabled) return;
+ setOptimisticSplitShiftsEnabled(value);
+ setSaving(true);
+ try {
+ await updateCalendar(calendarId, { splitShiftsEnabled: value });
+ } catch {
+ // updateCalendar already reported the error and rolled back the cache.
+ } finally {
+ setSaving(false);
+ setOptimisticSplitShiftsEnabled(null);
+ }
+ };
+
// A freshly created link takes over the whole panel body, same as the old
// sharing sheet did — "Close" here resets the form, not the whole panel.
if (linkForm.created) {
@@ -114,6 +131,20 @@ export function PermissionsPanel({ calendarId, onClose, onDirtyChange }: Permiss
)}
<InfoNote icon={Info}>{t("permissionBundles.signupsCapabilityHint")}</InfoNote>
</section>
+ <section className="flex flex-col gap-3 border-t border-line pt-5">
+ <SectionLabel className="mb-0">{t("permissionBundles.groups.splitShifts")}</SectionLabel>
+ <ToggleRow
+ id="split-shifts-enabled"
+ title={t("sharingSheet.splitShiftsEnabledLabel")}
+ description={t("sharingSheet.splitShiftsEnabledDesc")}
+ checked={splitShiftsEnabled}
+ onCheckedChange={handleSplitShiftsEnabledChange}
+ disabled={saving || !canManageSettings}
+ />
+ {!canManageSettings && (
+ <InfoNote icon={Lock}>{t("permissionBundles.splitShiftsLocked")}</InfoNote>
+ )}
+ </section>
</>
)}
diff --git a/components/month-grid.tsx b/components/month-grid.tsx
index fa6b155..37a5ca0 100644
--- a/components/month-grid.tsx
+++ b/components/month-grid.tsx
@@ -13,6 +13,7 @@ import {
DayShiftLayout,
buildDayShiftLayout,
formatSignupCapacityLabel,
+ formatTimeRange,
shiftVars,
} from "@/lib/shift-display";
import { cn } from "@/lib/utils";
@@ -342,8 +343,12 @@ export function MonthGrid({
const chip =
"shift-chip flex min-w-0 shrink-0 gap-1.5 rounded-[6px] py-0.5 pr-[7px] dark:[--shift-tint:14%]";
const time = (shift: ShiftWithCalendar) => (
- <span className="shrink-0 font-mono text-[10.5px] leading-4 opacity-75">
- {shift.isAllDay ? t("calendarView.allDayShort") : shift.startTime.slice(0, 5)}
+ <span className="shrink-0 whitespace-nowrap font-mono text-[10.5px] leading-4 opacity-75">
+ {shift.isAllDay
+ ? t("calendarView.allDayShort")
+ : shift.segments?.length
+ ? formatTimeRange(shift)
+ : shift.startTime.slice(0, 5)}
</span>
);
diff --git a/components/preset-form.tsx b/components/preset-form.tsx
index c800bb5..eda7577 100644
--- a/components/preset-form.tsx
+++ b/components/preset-form.tsx
@@ -9,6 +9,10 @@ import { DEFAULT_COLOR } from "@/lib/constants";
import type { PresetFormData } from "@/hooks/usePresets";
import { useAuthFeatures } from "@/hooks/useAuthFeatures";
import { cn } from "@/lib/utils";
+import { suggestNextTimeRange, validateTimeRanges, toTimeRanges } from "@/lib/time-ranges";
+import type { TimeRange } from "@/lib/time-ranges";
+import { Button } from "@/components/ui/button";
+import { Plus, X } from "lucide-react";
export const EMPTY_PRESET_FORM: PresetFormData = {
title: "",
@@ -21,9 +25,10 @@ export const EMPTY_PRESET_FORM: PresetFormData = {
isAllDay: false,
hideFromStats: false,
defaultSignupCapacity: null,
+ segments: [],
};
-export function presetToFormData(preset: ShiftPreset): PresetFormData {
+export function presetToFormData(preset: ShiftPreset & { segments?: TimeRange[] }): PresetFormData {
return {
title: preset.title,
startTime: preset.startTime,
@@ -35,11 +40,17 @@ export function presetToFormData(preset: ShiftPreset): PresetFormData {
isAllDay: preset.isAllDay || false,
hideFromStats: preset.hideFromStats || false,
defaultSignupCapacity: preset.defaultSignupCapacity ?? null,
+ segments: preset.segments ?? [],
};
}
export function samePresetForm(a: PresetFormData, b: PresetFormData): boolean {
- return (Object.keys(a) as (keyof PresetFormData)[]).every((key) => a[key] === b[key]);
+ const { segments: segmentsA, ...restA } = a;
+ const { segments: segmentsB, ...restB } = b;
+ return (
+ (Object.keys(restA) as (keyof typeof restA)[]).every((key) => restA[key] === restB[key]) &&
+ JSON.stringify(segmentsA) === JSON.stringify(segmentsB)
+ );
}
@@ -54,6 +65,7 @@ interface PresetFormCardProps {
titleRef?: Ref<HTMLInputElement>;
/** Existing group names across this calendar's presets, offered as datalist suggestions. */
existingGroupNames?: string[];
+ splitShiftsEnabled?: boolean;
}
/** "Neue Vorlage" card; the same card edits an existing preset. */
@@ -67,6 +79,7 @@ export function PresetFormCard({
cardRef,
titleRef,
existingGroupNames = [],
+ splitShiftsEnabled,
}: PresetFormCardProps) {
const t = useTranslations();
const id = useId();
@@ -124,6 +137,74 @@ export function PresetFormCard({
</div>
)}
+ {!value.isAllDay && value.segments.length > 0 && (
+ <div className="flex flex-col gap-2">
+ {value.segments.map((segment, index) => (
+ <div key={index} className="grid grid-cols-[1fr_1fr_auto] items-end gap-2.5">
+ <Field label={t("presetSheet.start")}>
+ <Input
+ type="time"
+ value={segment.startTime}
+ onChange={(e) => {
+ const next = [...value.segments];
+ next[index] = { ...next[index], startTime: e.target.value };
+ onChange({ segments: next });
+ }}
+ className={cn(fieldClass, "font-mono")}
+ disabled={disabled}
+ />
+ </Field>
+ <Field label={t("presetSheet.end")}>
+ <Input
+ type="time"
+ value={segment.endTime}
+ onChange={(e) => {
+ const next = [...value.segments];
+ next[index] = { ...next[index], endTime: e.target.value };
+ onChange({ segments: next });
+ }}
+ className={cn(fieldClass, "font-mono")}
+ disabled={disabled}
+ />
+ </Field>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ aria-label={t("timeRanges.remove")}
+ disabled={disabled}
+ onClick={() => onChange({ segments: value.segments.filter((_, i) => i !== index) })}
+ >
+ <X className="size-4" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {!value.isAllDay && splitShiftsEnabled && !disabled && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="self-start"
+ onClick={() =>
+ onChange({
+ segments: [...value.segments, suggestNextTimeRange(toTimeRanges(value))],
+ })
+ }
+ >
+ <Plus className="size-4" />
+ {t("timeRanges.add")}
+ </Button>
+ )}
+
+ {!value.isAllDay &&
+ (() => {
+ const error = validateTimeRanges(toTimeRanges(value));
+ return error ? <p className="text-[13px] text-destructive">{t(`timeRanges.errors.${error}`)}</p> : null;
+ })()}
+
<ColorSwatches
value={value.color}
onChange={(color) => onChange({ color })}
diff --git a/components/preset-manage-sheet.tsx b/components/preset-manage-sheet.tsx
index 8bc5f8c..fcb6041 100644
--- a/components/preset-manage-sheet.tsx
+++ b/components/preset-manage-sheet.tsx
@@ -18,8 +18,10 @@ import { ShiftPreset } from "@/lib/db/schema";
import { groupPresetsByName } from "@/lib/shift-display";
import { usePresets, type PresetFormData } from "@/hooks/usePresets";
import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { useCalendars } from "@/hooks/useCalendars";
import { useReportDirty } from "@/hooks/useDirtyState";
import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
+import { validateTimeRanges, toTimeRanges } from "@/lib/time-ranges";
interface PresetsPanelProps {
calendarId: string;
@@ -52,6 +54,8 @@ export function PresetsPanel({
readOnly || (!permission.can("createPreset") && !permission.can("manageOwnPresets"));
const { presets, loading, createPreset, updatePreset, deletePreset, reorderPresets } =
usePresets(calendarId);
+ const { calendars } = useCalendars();
+ const splitShiftsEnabled = calendars.find((c) => c.id === calendarId)?.splitShiftsEnabled ?? false;
const formId = useId();
const formRef = useRef<HTMLFormElement>(null);
@@ -72,7 +76,11 @@ export function PresetsPanel({
// for editing, reachable only via an already-gated Edit button.
const formVisible = editingPreset ? canEditPreset(editingPreset) : canCreate;
const isDirty = formVisible && !samePresetForm(formData, baseline);
- const canSave = !isSaving && formData.title.trim() !== "" && (!editingPreset || isDirty);
+ const canSave =
+ !isSaving &&
+ formData.title.trim() !== "" &&
+ (!editingPreset || isDirty) &&
+ (formData.isAllDay || !validateTimeRanges(toTimeRanges(formData)));
useReportDirty(isDirty, onDirtyChange);
@@ -232,6 +240,7 @@ export function PresetsPanel({
cardRef={formRef}
titleRef={titleRef}
existingGroupNames={existingGroupNames}
+ splitShiftsEnabled={splitShiftsEnabled}
/>
)}
</PanelBody>
diff --git a/components/shift-form-fields.tsx b/components/shift-form-fields.tsx
index f3d65d4..8a2c9e6 100644
--- a/components/shift-form-fields.tsx
+++ b/components/shift-form-fields.tsx
@@ -1,6 +1,8 @@
import { useLocale, useTranslations } from "next-intl";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
+import { Button } from "@/components/ui/button";
+import { Plus, X } from "lucide-react";
import {
CheckRow,
ColorSwatches,
@@ -11,8 +13,8 @@ import {
import { ShiftFormData } from "@/components/shift-sheet";
import { useAutoFocusRef } from "@/hooks/useAutoFocus";
import { DEFAULT_COLOR } from "@/lib/constants";
-import { calculateShiftDuration } from "@/lib/date-utils";
import { formatHours } from "@/lib/shift-display";
+import { sumRangeDurations, suggestNextTimeRange, validateTimeRanges, toTimeRanges } from "@/lib/time-ranges";
import { cn } from "@/lib/utils";
interface ShiftFormFieldsProps {
@@ -24,6 +26,7 @@ interface ShiftFormFieldsProps {
onPresetNameChange: (value: string) => void;
isEditing: boolean;
readOnly?: boolean;
+ splitShiftsEnabled?: boolean;
}
const TIME_PATTERN = /^\d{2}:\d{2}$/;
@@ -37,6 +40,7 @@ export function ShiftFormFields({
onPresetNameChange,
isEditing,
readOnly = false,
+ splitShiftsEnabled = false,
}: ShiftFormFieldsProps) {
const t = useTranslations();
const locale = useLocale();
@@ -46,8 +50,10 @@ export function ShiftFormFields({
!formData.isAllDay &&
TIME_PATTERN.test(formData.startTime) &&
TIME_PATTERN.test(formData.endTime);
+ // formatHours takes minutes (see other call sites); sumRangeDurations already
+ // returns minutes, unlike the old calculateShiftDuration(...) call this replaced.
const duration = validTimes
- ? formatHours(calculateShiftDuration(formData.startTime, formData.endTime), locale)
+ ? formatHours(sumRangeDurations(toTimeRanges(formData)), locale)
: "–";
const timesDisabled = readOnly || formData.isAllDay;
@@ -99,6 +105,84 @@ export function ShiftFormFields({
</Field>
</div>
+ {!formData.isAllDay && (formData.segments?.length ?? 0) > 0 && (
+ <div className="flex flex-col gap-2">
+ {(formData.segments ?? []).map((segment, index) => (
+ <div key={index} className="flex items-end gap-2.5">
+ <Field label={t("shiftSheet.start")} className="flex-1">
+ <Input
+ type="time"
+ value={segment.startTime}
+ onChange={(e) => {
+ const next = [...(formData.segments ?? [])];
+ next[index] = { ...next[index], startTime: e.target.value };
+ onFormDataChange({ ...formData, segments: next });
+ }}
+ disabled={readOnly}
+ className={cn(inputClass, "font-mono")}
+ />
+ </Field>
+ <Field label={t("shiftSheet.end")} className="flex-1">
+ <Input
+ type="time"
+ value={segment.endTime}
+ onChange={(e) => {
+ const next = [...(formData.segments ?? [])];
+ next[index] = { ...next[index], endTime: e.target.value };
+ onFormDataChange({ ...formData, segments: next });
+ }}
+ disabled={readOnly}
+ className={cn(inputClass, "font-mono")}
+ />
+ </Field>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ className="mb-[1px] shrink-0"
+ aria-label={t("timeRanges.remove")}
+ disabled={readOnly}
+ onClick={() => {
+ const next = (formData.segments ?? []).filter((_, i) => i !== index);
+ onFormDataChange({ ...formData, segments: next });
+ }}
+ >
+ <X className="size-4" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {!formData.isAllDay && splitShiftsEnabled && !readOnly && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="self-start"
+ onClick={() =>
+ onFormDataChange({
+ ...formData,
+ segments: [
+ ...(formData.segments ?? []),
+ suggestNextTimeRange(toTimeRanges(formData)),
+ ],
+ })
+ }
+ >
+ <Plus className="size-4" />
+ {t("timeRanges.add")}
+ </Button>
+ )}
+
+ {!formData.isAllDay &&
+ (() => {
+ const error = validateTimeRanges(toTimeRanges(formData));
+ return error ? (
+ <p className="text-[13px] text-danger-body">{t(`timeRanges.errors.${error}`)}</p>
+ ) : null;
+ })()}
+
<CheckRow
id="allDay"
label={t("shiftSheet.allDay")}
diff --git a/components/shift-sheet.tsx b/components/shift-sheet.tsx
index 1b61449..a6c706a 100644
--- a/components/shift-sheet.tsx
+++ b/components/shift-sheet.tsx
@@ -10,8 +10,10 @@ import { ReadOnlyBanner } from "@/components/read-only-banner";
import { ShiftSignupList } from "@/components/shift-signup-list";
import { useShiftForm } from "@/hooks/useShiftForm";
import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { useCalendars } from "@/hooks/useCalendars";
import { formatDateToLocal, formatLongDate, parseLocalDate } from "@/lib/date-utils";
import { isTempId } from "@/lib/utils";
+import { validateTimeRanges, toTimeRanges, type TimeRange } from "@/lib/time-ranges";
interface ShiftSheetProps {
open: boolean;
@@ -34,6 +36,7 @@ export interface ShiftFormData {
presetId?: string;
isAllDay?: boolean;
signupCapacity?: number | null;
+ segments?: TimeRange[];
/** New shifts only: people to sign up immediately once the shift is created. */
signupUserIds?: string[];
}
@@ -49,6 +52,7 @@ function snapshot(data: ShiftFormData) {
color: data.color,
isAllDay: data.isAllDay || false,
signupCapacity: data.signupCapacity ?? null,
+ segments: data.segments ?? [],
});
}
@@ -65,6 +69,8 @@ export function ShiftSheet({
const t = useTranslations();
const locale = useLocale();
const permission = useCalendarPermission(calendarId);
+ const { calendars } = useCalendars();
+ const splitShiftsEnabled = calendars.find((c) => c.id === calendarId)?.splitShiftsEnabled ?? false;
const [isSaving, setIsSaving] = useState(false);
// Determine if sheet should be in read-only mode
@@ -113,6 +119,7 @@ export function ShiftSheet({
color: shift.color,
isAllDay: shift.isAllDay || false,
signupCapacity: shift.signupCapacity ?? null,
+ segments: shift.segments ?? [],
})
: null,
[shift]
@@ -143,6 +150,7 @@ export function ShiftSheet({
...formData,
startTime: formData.isAllDay ? "00:00" : formData.startTime,
endTime: formData.isAllDay ? "23:59" : formData.endTime,
+ segments: formData.isAllDay ? [] : formData.segments,
...(!shift ? { signupUserIds: pendingSignupUserIds } : {}),
};
@@ -190,7 +198,11 @@ export function ShiftSheet({
showCancelButton
onSave={handleSave}
isSaving={isSaving}
- saveDisabled={!formData.title.trim() || (shift && !hasChanges())}
+ saveDisabled={
+ !formData.title.trim() ||
+ (shift && !hasChanges()) ||
+ (!formData.isAllDay && !!validateTimeRanges(toTimeRanges(formData)))
+ }
saveLabel={shift ? undefined : t("shiftSheet.createAction")}
hasUnsavedChanges={!isReadOnly && hasChanges()}
>
@@ -215,6 +227,7 @@ export function ShiftSheet({
onPresetNameChange={setPresetName}
isEditing={!!shift}
readOnly={isReadOnly}
+ splitShiftsEnabled={splitShiftsEnabled}
/>
{/* Signups aren't gated by isReadOnly: a read-only member may still
diff --git a/docs/superpowers/plans/2026-09-15-split-shifts.md b/docs/superpowers/plans/2026-09-15-split-shifts.md
new file mode 100644
index 0000000..d72da1a
--- /dev/null
+++ b/docs/superpowers/plans/2026-09-15-split-shifts.md
@@ -0,0 +1,2203 @@
+# Split Shifts Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Let a shift (and a preset) have more than one time range on the same day — e.g. `06:00–10:00` and `15:00–21:00` in one duty — gated per calendar behind an owner/admin-controlled toggle, without changing behavior for the (majority) single-range case.
+
+**Architecture:** The primary time range stays on `shifts.startTime`/`endTime` and `shiftPresets.startTime`/`endTime` exactly as today. Two new child tables (`shiftTimeSegments`, `presetTimeSegments`) hold only the *additional* ranges, following the existing `shiftSignups` one-to-many-on-parent-id pattern. A new `calendars.splitShiftsEnabled` boolean (default `false`) gates the feature per calendar, modeled byte-for-byte on the existing `calendars.signupsEnabled` master switch.
+
+**Tech Stack:** Next.js 16 (App Router) API routes, Drizzle ORM / SQLite (better-sqlite3), React 19 client components, TanStack Query, next-intl.
+
+**Spec:** `docs/superpowers/specs/2026-09-15-split-shifts-design.md`
+
+## Global Constraints
+
+- No unit-test framework in this repo. Verification is `npx tsc --noEmit` (fast, run after almost every step) and the full `npm test` (lint + build + i18n) at task boundaries — see `CLAUDE.md`.
+- Never write raw `ALTER TABLE` SQL by hand — always edit `lib/db/schema.ts` then run `npm run db:generate` (creates the `.sql`, snapshot, and `_journal.json` entry together) followed by `npm run db:migrate`.
+- `messages/de.json` is the source of truth for i18n; add a key there first, then mirror the same key into `en.json`, `es.json`, `fr.json`, `it.json`, `cs.json` before running `npm run i18n`.
+- `startTime`/`endTime` on `shifts`/`shiftPresets` must keep meaning exactly what they mean today (the primary/first range) — every task must stay backward compatible for code that only reads those two fields.
+- Segments are validated (chronological, non-overlapping, same-day, no midnight wraparound) only when there is more than one range; a single range keeps 100% of its current behavior, including overnight shifts.
+- Follow existing code style: no comments unless they explain a non-obvious constraint; German UI strings mirror the tone of neighboring keys (see `sharingSheet.signupsEnabledLabel`/`Desc` for the reference tone).
+
+---
+
+### Task 1: Schema, migration, and shared types
+
+**Files:**
+- Modify: `lib/db/schema.ts`
+- Modify: `lib/types.ts`
+- Modify: `hooks/useCalendars.ts`
+- Create (generated): `drizzle/00XX_*.sql`, `drizzle/meta/00XX_snapshot.json`, updated `drizzle/meta/_journal.json`
+
+**Interfaces:**
+- Produces: `shiftTimeSegments` table (`id`, `shiftId`, `startTime`, `endTime`, `createdAt`), `presetTimeSegments` table (`id`, `presetId`, `startTime`, `endTime`, `createdAt`), `calendars.splitShiftsEnabled: boolean`, `shiftsRelations.segments` / `shiftPresetsRelations.segments` (Drizzle relations), `ShiftWithCalendar.segments?: { startTime: string; endTime: string }[]`, `CalendarWithCount.splitShiftsEnabled?: boolean`, `CalendarUpdateInput.splitShiftsEnabled?: boolean`.
+
+- [ ] **Step 1: Add the two child tables to the schema**
+
+In `lib/db/schema.ts`, add right after the `shiftPresets` table definition (before `calendarNotes`):
+
+```ts
+export const shiftTimeSegments = sqliteTable(
+ "shift_time_segments",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ shiftId: text("shift_id")
+ .notNull()
+ .references(() => shifts.id, { onDelete: "cascade" }),
+ startTime: text("start_time").notNull(),
+ endTime: text("end_time").notNull(),
+ createdAt: integer("created_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ },
+ (table) => [index("shift_time_segments_shiftId_idx").on(table.shiftId)]
+);
+
+export const presetTimeSegments = sqliteTable(
+ "preset_time_segments",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ presetId: text("preset_id")
+ .notNull()
+ .references(() => shiftPresets.id, { onDelete: "cascade" }),
+ startTime: text("start_time").notNull(),
+ endTime: text("end_time").notNull(),
+ createdAt: integer("created_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ },
+ (table) => [index("preset_time_segments_presetId_idx").on(table.presetId)]
+);
+```
+
+- [ ] **Step 2: Add `splitShiftsEnabled` to `calendars`**
+
+In the `calendars` table definition, right after the existing `signupsEnabled` field:
+
+```ts
+ // Master switch for split shifts (multiple time ranges per shift/preset)
+ // on this calendar. Owner/admin only; off hides extra ranges everywhere,
+ // same contract as signupsEnabled above.
+ splitShiftsEnabled: integer("split_shifts_enabled", { mode: "boolean" })
+ .notNull()
+ .default(false),
+```
+
+- [ ] **Step 3: Wire up relations**
+
+In `shiftsRelations`, add a `segments` relation next to `signups`:
+
+```ts
+export const shiftsRelations = relations(shifts, ({ one, many }) => ({
+ calendar: one(calendars, {
+ fields: [shifts.calendarId],
+ references: [calendars.id],
+ }),
+ preset: one(shiftPresets, {
+ fields: [shifts.presetId],
+ references: [shiftPresets.id],
+ }),
+ signups: many(shiftSignups),
+ segments: many(shiftTimeSegments),
+ creator: one(user, {
+ fields: [shifts.createdBy],
+ references: [user.id],
+ }),
+}));
+```
+
+In `shiftPresetsRelations`, add the equivalent (it currently only has `one`, so switch its factory to also destructure `many`):
+
+```ts
+export const shiftPresetsRelations = relations(shiftPresets, ({ one, many }) => ({
+ calendar: one(calendars, {
+ fields: [shiftPresets.calendarId],
+ references: [calendars.id],
+ }),
+ segments: many(presetTimeSegments),
+ creator: one(user, {
+ fields: [shiftPresets.createdBy],
+ references: [user.id],
+ }),
+}));
+```
+
+Add the two matching one-side relations, anywhere near the other `*Relations` exports:
+
+```ts
+export const shiftTimeSegmentsRelations = relations(shiftTimeSegments, ({ one }) => ({
+ shift: one(shifts, {
+ fields: [shiftTimeSegments.shiftId],
+ references: [shifts.id],
+ }),
+}));
+
+export const presetTimeSegmentsRelations = relations(presetTimeSegments, ({ one }) => ({
+ preset: one(shiftPresets, {
+ fields: [presetTimeSegments.presetId],
+ references: [shiftPresets.id],
+ }),
+}));
+```
+
+- [ ] **Step 4: Generate and apply the migration**
+
+Run:
+```bash
+npm run db:generate
+npm run db:migrate
+```
+Expected: a new `drizzle/00XX_<name>.sql` containing two `CREATE TABLE` statements and one `ALTER TABLE calendars ADD split_shifts_enabled ...` statement, plus an updated `drizzle/meta/_journal.json` with one new entry. `db:migrate` exits 0.
+
+- [ ] **Step 5: Type-check**
+
+Run: `npx tsc --noEmit`
+Expected: no new errors (the new tables/relations are additive).
+
+- [ ] **Step 6: Update `lib/types.ts`**
+
+Add a `TimeRange` re-export-friendly field to `ShiftWithCalendar` and `splitShiftsEnabled` to `CalendarWithCount`:
+
+```ts
+export interface CalendarWithCount {
+ id: string;
+ name: string;
+ color: string;
+ ownerId?: string | null;
+ guestBundleId?: string | null;
+ signupsEnabled?: boolean;
+ splitShiftsEnabled?: boolean;
+ /** The calendar's own view; null means everyone sees their personal view */
+ viewSettings?: CalendarViewSettings | null;
+ createdAt: Date | null;
+ updatedAt: Date | null;
+ _count?: number;
+ capabilities?: Capability[];
+ bundle?: CalendarBundleRef | null;
+ isSubscribed?: boolean;
+ subscriptionSource?: "guest" | "shared" | "token";
+ canSignUpSelf?: boolean;
+ canSignUpOthers?: boolean;
+}
+
+export interface ShiftWithCalendar {
+ id: string;
+ calendarId: string;
+ presetId?: string | null;
+ calendar?: {
+ id: string;
+ name: string;
+ color: string;
+ };
+ date: Date | null;
+ startTime: string;
+ endTime: string;
+ title: string;
+ color: string;
+ notes?: string | null;
+ isAllDay?: boolean;
+ syncedFromExternal?: boolean;
+ externalSyncId?: string | null;
+ signupCapacity?: number | null;
+ signups?: ShiftSignupUser[];
+ /** Additional time ranges beyond startTime/endTime (split shifts). Empty/undefined for a normal shift. */
+ segments?: { startTime: string; endTime: string }[];
+ createdBy?: string | null;
+ createdAt: Date | null;
+ updatedAt: Date | null;
+}
+```
+
+- [ ] **Step 7: Update `hooks/useCalendars.ts`**
+
+Add the field to `CalendarUpdateInput`:
+
+```ts
+export interface CalendarUpdateInput {
+ name?: string;
+ color?: string;
+ guestBundleId?: string | null;
+ viewSettings?: CalendarViewSettings | null;
+ signupsEnabled?: boolean;
+ splitShiftsEnabled?: boolean;
+}
+```
+
+- [ ] **Step 8: Type-check again**
+
+Run: `npx tsc --noEmit`
+Expected: clean.
+
+- [ ] **Step 9: Commit**
+
+```bash
+git add lib/db/schema.ts lib/types.ts hooks/useCalendars.ts drizzle
+git commit -m "feat(db): add split-shift time segments and calendar toggle"
+```
+
+---
+
+### Task 2: Client-safe time-range logic
+
+**Files:**
+- Create: `lib/time-ranges.ts`
+
+**Interfaces:**
+- Consumes: nothing project-specific (pure functions).
+- Produces: `TimeRange` type, `toTimeRanges(entity: { startTime: string; endTime: string; segments?: TimeRange[] }): TimeRange[]`, `validateTimeRanges(ranges: TimeRange[]): TimeRangeError | null`, `TimeRangeError` union, `sumRangeDurations(ranges: TimeRange[]): number`.
+
+- [ ] **Step 1: Write the module**
+
+```ts
+import { calculateShiftDuration } from "@/lib/date-utils";
+
+export interface TimeRange {
+ startTime: string;
+ endTime: string;
+}
+
+export type TimeRangeError = "invalid_format" | "overnight_segment" | "overlap";
+
+const TIME_PATTERN = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/;
+
+function toMinutes(time: string): number {
+ const [hours, minutes] = time.split(":").map(Number);
+ return hours * 60 + minutes;
+}
+
+/** Reassembles the primary range plus any extra segments into one ordered-by-input list. */
+export function toTimeRanges(entity: {
+ startTime: string;
+ endTime: string;
+ segments?: TimeRange[];
+}): TimeRange[] {
+ return [
+ { startTime: entity.startTime, endTime: entity.endTime },
+ ...(entity.segments ?? []),
+ ];
+}
+
+/**
+ * Validates a full list of ranges for a shift/preset. A single range is
+ * always valid here (including one that crosses midnight — unchanged
+ * existing behavior); chronological order, non-overlap and same-day-only
+ * are enforced only once there is more than one range.
+ */
+export function validateTimeRanges(ranges: TimeRange[]): TimeRangeError | null {
+ for (const range of ranges) {
+ if (!TIME_PATTERN.test(range.startTime) || !TIME_PATTERN.test(range.endTime)) {
+ return "invalid_format";
+ }
+ }
+
+ if (ranges.length <= 1) return null;
+
+ for (const range of ranges) {
+ if (toMinutes(range.endTime) <= toMinutes(range.startTime)) {
+ return "overnight_segment";
+ }
+ }
+
+ const sorted = [...ranges].sort((a, b) => toMinutes(a.startTime) - toMinutes(b.startTime));
+ for (let i = 1; i < sorted.length; i++) {
+ if (toMinutes(sorted[i].startTime) < toMinutes(sorted[i - 1].endTime)) {
+ return "overlap";
+ }
+ }
+
+ return null;
+}
+
+/** Total duration across all ranges, in minutes. */
+export function sumRangeDurations(ranges: TimeRange[]): number {
+ return ranges.reduce(
+ (total, range) => total + calculateShiftDuration(range.startTime, range.endTime),
+ 0
+ );
+}
+```
+
+- [ ] **Step 2: Type-check**
+
+Run: `npx tsc --noEmit`
+Expected: clean (this file has no callers yet, so it must compile standalone).
+
+- [ ] **Step 3: Sanity-check the validation logic with a throwaway script**
+
+Run:
+```bash
+npx tsx -e "
+import { validateTimeRanges } from './lib/time-ranges';
+console.log(validateTimeRanges([{ startTime: '06:00', endTime: '10:00' }])); // null
+console.log(validateTimeRanges([{ startTime: '22:00', endTime: '06:00' }])); // null (single range, overnight ok)
+console.log(validateTimeRanges([{ startTime: '06:00', endTime: '10:00' }, { startTime: '15:00', endTime: '21:00' }])); // null
+console.log(validateTimeRanges([{ startTime: '15:00', endTime: '21:00' }, { startTime: '06:00', endTime: '10:00' }])); // null (order-independent input)
+console.log(validateTimeRanges([{ startTime: '06:00', endTime: '10:00' }, { startTime: '09:00', endTime: '12:00' }])); // 'overlap'
+console.log(validateTimeRanges([{ startTime: '22:00', endTime: '06:00' }, { startTime: '08:00', endTime: '12:00' }])); // 'overnight_segment'
+"
+```
+Expected output, one value per line: `null`, `null`, `null`, `null`, `overlap`, `overnight_segment`. If any line differs, fix `validateTimeRanges` before continuing.
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add lib/time-ranges.ts
+git commit -m "feat: add client-safe time-range validation and duration helpers"
+```
+
+---
+
+### Task 3: Server-side segment persistence helpers
+
+**Files:**
+- Create: `lib/shift-time-ranges.ts`
+
+**Interfaces:**
+- Consumes: `TimeRange` from `lib/time-ranges.ts`; `db`, `shiftTimeSegments`, `presetTimeSegments` from `lib/db`/`lib/db/schema`.
+- Produces: `replaceShiftSegments(tx, shiftId, ranges)`, `replacePresetSegments(tx, presetId, ranges)`, `withShiftSegments<T extends {id: string}>(rows: T[])`, `withPresetSegments<T extends {id: string}>(rows: T[])`.
+
+- [ ] **Step 1: Write the module**
+
+```ts
+import { db } from "@/lib/db";
+import { shiftTimeSegments, presetTimeSegments } from "@/lib/db/schema";
+import { eq, inArray } from "drizzle-orm";
+import type { TimeRange } from "@/lib/time-ranges";
+
+type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
+
+/** Replaces every extra segment for one shift (delete-then-insert), inside an existing transaction. */
+export function replaceShiftSegments(tx: Tx, shiftId: string, ranges: TimeRange[]): void {
+ tx.delete(shiftTimeSegments).where(eq(shiftTimeSegments.shiftId, shiftId)).run();
+ if (ranges.length > 0) {
+ tx.insert(shiftTimeSegments)
+ .values(ranges.map((r) => ({ shiftId, startTime: r.startTime, endTime: r.endTime })))
+ .run();
+ }
+}
+
+/** Replaces every extra segment for one preset (delete-then-insert), inside an existing transaction. */
+export function replacePresetSegments(tx: Tx, presetId: string, ranges: TimeRange[]): void {
+ tx.delete(presetTimeSegments).where(eq(presetTimeSegments.presetId, presetId)).run();
+ if (ranges.length > 0) {
+ tx.insert(presetTimeSegments)
+ .values(ranges.map((r) => ({ presetId, startTime: r.startTime, endTime: r.endTime })))
+ .run();
+ }
+}
+
+/** Attaches each shift's extra segments without N+1 queries. */
+export async function withShiftSegments<T extends { id: string }>(
+ rows: T[]
+): Promise<(T & { segments: TimeRange[] })[]> {
+ if (rows.length === 0) return [];
+
+ const allSegments = await db.query.shiftTimeSegments.findMany({
+ where: inArray(
+ shiftTimeSegments.shiftId,
+ rows.map((r) => r.id)
+ ),
+ orderBy: (segments, { asc }) => [asc(segments.startTime)],
+ });
+
+ const byShiftId = new Map<string, TimeRange[]>();
+ for (const segment of allSegments) {
+ const list = byShiftId.get(segment.shiftId) ?? [];
+ list.push({ startTime: segment.startTime, endTime: segment.endTime });
+ byShiftId.set(segment.shiftId, list);
+ }
+
+ return rows.map((row) => ({ ...row, segments: byShiftId.get(row.id) ?? [] }));
+}
+
+/** Attaches each preset's extra segments without N+1 queries. */
+export async function withPresetSegments<T extends { id: string }>(
+ rows: T[]
+): Promise<(T & { segments: TimeRange[] })[]> {
+ if (rows.length === 0) return [];
+
+ const allSegments = await db.query.presetTimeSegments.findMany({
+ where: inArray(
+ presetTimeSegments.presetId,
+ rows.map((r) => r.id)
+ ),
+ orderBy: (segments, { asc }) => [asc(segments.startTime)],
+ });
+
+ const byPresetId = new Map<string, TimeRange[]>();
+ for (const segment of allSegments) {
+ const list = byPresetId.get(segment.presetId) ?? [];
+ list.push({ startTime: segment.startTime, endTime: segment.endTime });
+ byPresetId.set(segment.presetId, list);
+ }
+
+ return rows.map((row) => ({ ...row, segments: byPresetId.get(row.id) ?? [] }));
+}
+```
+
+Note: `tx.delete(...).run()` / `.insert(...).run()` — the `better-sqlite3` Drizzle driver's synchronous query builder exposes `.run()` for statements without a `.returning()`; existing transaction code in `app/api/calendars/route.ts` uses the same synchronous `db.transaction((tx) => {...})` shape without `await` inside.
+
+- [ ] **Step 2: Type-check**
+
+Run: `npx tsc --noEmit`
+Expected: clean. If `Tx` inference fails, replace it with the exact type Drizzle exports for a better-sqlite3 transaction callback parameter (check `app/api/calendars/route.ts`'s `db.transaction((tx) => {` for the inferred type via hover/`tsc`, since that file already uses one) rather than leaving `tx: any`.
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add lib/shift-time-ranges.ts
+git commit -m "feat: add server-side segment persistence helpers"
+```
+
+---
+
+### Task 4: Shifts API — read, create, update
+
+**Files:**
+- Modify: `app/api/shifts/route.ts`
+- Modify: `app/api/shifts/[id]/route.ts`
+
+**Interfaces:**
+- Consumes: `toTimeRanges`, `validateTimeRanges` (`lib/time-ranges.ts`); `replaceShiftSegments`, `withShiftSegments` (`lib/shift-time-ranges.ts`).
+- Produces: shift API responses gain `segments: TimeRange[]`; `POST`/`PUT` accept an optional `segments` field in the body.
+
+- [ ] **Step 1: `GET /api/shifts` — attach segments**
+
+In `app/api/shifts/route.ts`, wrap both returned results through `withShiftSegments`. Replace:
+
+```ts
+ const result = await query.where(
+ and(
+ eq(shifts.calendarId, calendarId),
+ gte(shifts.date, startOfDay),
+ lte(shifts.date, endOfDay),
+ or(isNull(shifts.externalSyncId), eq(externalSyncs.isHidden, false))
+ )
+ );
+ return NextResponse.json(await withSignups(result));
+ }
+
+ const result = await query.where(
+ and(
+ eq(shifts.calendarId, calendarId),
+ or(isNull(shifts.externalSyncId), eq(externalSyncs.isHidden, false))
+ )
+ );
+ return NextResponse.json(await withSignups(result));
+```
+
+with:
+
+```ts
+ const result = await query.where(
+ and(
+ eq(shifts.calendarId, calendarId),
+ gte(shifts.date, startOfDay),
+ lte(shifts.date, endOfDay),
+ or(isNull(shifts.externalSyncId), eq(externalSyncs.isHidden, false))
+ )
+ );
+ return NextResponse.json(await withShiftSegments(await withSignups(result)));
+ }
+
+ const result = await query.where(
+ and(
+ eq(shifts.calendarId, calendarId),
+ or(isNull(shifts.externalSyncId), eq(externalSyncs.isHidden, false))
+ )
+ );
+ return NextResponse.json(await withShiftSegments(await withSignups(result)));
+```
+
+Add the import:
+
+```ts
+import { withShiftSegments, replaceShiftSegments, withPresetSegments } from "@/lib/shift-time-ranges";
+import { toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
+```
+
+(`withPresetSegments` is needed in Step 2 below, for reading a preset's own segments when stamping.)
+
+- [ ] **Step 2: `POST /api/shifts` — validate and persist segments**
+
+Replace the body destructuring:
+
+```ts
+ const {
+ calendarId,
+ date,
+ startTime,
+ endTime,
+ title,
+ color,
+ notes,
+ presetId,
+ isAllDay,
+ isSecondary,
+ signupCapacity,
+ signupUserIds,
+ } = body;
+```
+
+with:
+
+```ts
+ const {
+ calendarId,
+ date,
+ startTime,
+ endTime,
+ title,
+ color,
+ notes,
+ presetId,
+ isAllDay,
+ isSecondary,
+ signupCapacity,
+ signupUserIds,
+ segments: requestedSegments,
+ } = body;
+```
+
+Change the `insertValues` block so both branches also produce a `segmentsToPersist: TimeRange[]`. Replace the whole `if (access.can("createShift")) { ... } else { ... }` block with:
+
+```ts
+ let insertValues: {
+ title: string;
+ startTime: string;
+ endTime: string;
+ color: string;
+ notes: string | null;
+ isAllDay: boolean;
+ };
+ let segmentsToPersist: TimeRange[] = [];
+
+ if (access.can("createShift")) {
+ if (presetId) {
+ const [preset] = await db
+ .select()
+ .from(shiftPresets)
+ .where(
+ and(
+ eq(shiftPresets.id, presetId),
+ eq(shiftPresets.calendarId, calendarId)
+ )
+ );
+ if (!preset) {
+ return NextResponse.json(
+ { error: "Preset not found" },
+ { status: 404 }
+ );
+ }
+ }
+ insertValues = {
+ title,
+ startTime: isAllDay ? "00:00" : startTime,
+ endTime: isAllDay ? "23:59" : endTime,
+ color: color || "#3b82f6",
+ notes: notes || null,
+ isAllDay: isAllDay || false,
+ };
+
+ if (!isAllDay) {
+ const rawSegments: TimeRange[] = Array.isArray(requestedSegments)
+ ? requestedSegments
+ : [];
+ if (rawSegments.length > 0 && !calendar.splitShiftsEnabled) {
+ return NextResponse.json(
+ { error: "Split shifts are not enabled for this calendar" },
+ { status: 400 }
+ );
+ }
+ const allRanges = toTimeRanges({ ...insertValues, segments: rawSegments });
+ const validationError = validateTimeRanges(allRanges);
+ if (validationError) {
+ return NextResponse.json({ error: validationError }, { status: 400 });
+ }
+ segmentsToPersist = rawSegments;
+ }
+ } else {
+ if (!presetId) {
+ return NextResponse.json(
+ { error: "presetId is required" },
+ { status: 400 }
+ );
+ }
+ const [preset] = await db
+ .select()
+ .from(shiftPresets)
+ .where(
+ and(
+ eq(shiftPresets.id, presetId),
+ eq(shiftPresets.calendarId, calendarId)
+ )
+ );
+ if (!preset) {
+ return NextResponse.json(
+ { error: "Preset not found" },
+ { status: 404 }
+ );
+ }
+ insertValues = {
+ title: preset.title,
+ startTime: preset.isAllDay ? "00:00" : preset.startTime,
+ endTime: preset.isAllDay ? "23:59" : preset.endTime,
+ color: preset.color,
+ notes: preset.notes,
+ isAllDay: preset.isAllDay,
+ };
+ if (!preset.isAllDay && calendar.splitShiftsEnabled) {
+ const [presetWithSegments] = await withPresetSegments([preset]);
+ segmentsToPersist = presetWithSegments.segments;
+ }
+ }
+```
+
+- [ ] **Step 3: Persist the shift and its segments in one transaction**
+
+Replace the plain `db.insert(shifts)...returning()` call:
+
+```ts
+ const [shift] = await db
+ .insert(shifts)
+ .values({
+ calendarId,
+ presetId: presetId || null,
+ date: parsedDate,
+ ...insertValues,
+ isSecondary: isSecondary || false,
+ signupCapacity:
+ typeof signupCapacity === "number" ? signupCapacity : null,
+ createdBy: user?.id ?? null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .returning();
+```
+
+with:
+
+```ts
+ const shift = db.transaction((tx) => {
+ const inserted = tx
+ .insert(shifts)
+ .values({
+ calendarId,
+ presetId: presetId || null,
+ date: parsedDate,
+ ...insertValues,
+ isSecondary: isSecondary || false,
+ signupCapacity:
+ typeof signupCapacity === "number" ? signupCapacity : null,
+ createdBy: user?.id ?? null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .returning()
+ .get();
+ replaceShiftSegments(tx, inserted.id, segmentsToPersist);
+ return inserted;
+ });
+```
+
+Update the final response to include segments:
+
+```ts
+ return NextResponse.json(
+ { ...shift, calendar, signups, segments: segmentsToPersist },
+ { status: 201 }
+ );
+```
+
+- [ ] **Step 4: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint app/api/shifts/route.ts`
+Expected: clean (`.returning().get()` is the same synchronous single-row pattern already used in `app/api/calendars/route.ts`'s `db.transaction((tx) => {...})` block).
+
+- [ ] **Step 5: `GET /api/shifts/[id]` — attach segments**
+
+In `app/api/shifts/[id]/route.ts`, add the import `import { withShiftSegments } from "@/lib/shift-time-ranges";` and change the `GET` handler's return:
+
+```ts
+ return NextResponse.json(result[0]);
+```
+to:
+```ts
+ const [withSegments] = await withShiftSegments([result[0]]);
+ return NextResponse.json(withSegments);
+```
+
+- [ ] **Step 6: `PUT /api/shifts/[id]` — validate and persist segments on update**
+
+Add imports:
+
+```ts
+import { replaceShiftSegments, withShiftSegments } from "@/lib/shift-time-ranges";
+import { toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
+```
+
+Before the existing `db.update(shifts)...` call, insert validation and figure out the calendar's `splitShiftsEnabled`:
+
+```ts
+ const nextStartTime = body.startTime ?? existingShift.startTime;
+ const nextEndTime = body.endTime ?? existingShift.endTime;
+ const nextIsAllDay = body.isAllDay ?? existingShift.isAllDay;
+
+ let nextSegments: TimeRange[] | undefined;
+ if (body.segments !== undefined) {
+ const rawSegments: TimeRange[] = Array.isArray(body.segments) ? body.segments : [];
+ if (!nextIsAllDay) {
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, existingShift.calendarId));
+ if (rawSegments.length > 0 && !calendar?.splitShiftsEnabled) {
+ return NextResponse.json(
+ { error: "Split shifts are not enabled for this calendar" },
+ { status: 400 }
+ );
+ }
+ const allRanges = toTimeRanges({
+ startTime: nextStartTime,
+ endTime: nextEndTime,
+ segments: rawSegments,
+ });
+ const validationError = validateTimeRanges(allRanges);
+ if (validationError) {
+ return NextResponse.json({ error: validationError }, { status: 400 });
+ }
+ }
+ nextSegments = nextIsAllDay ? [] : rawSegments;
+ }
+```
+
+(`calendars` needs to be imported in this file — add it to the existing `import { calendars, shiftPresets, shifts } from "@/lib/db/schema";` line.)
+
+Replace the update call:
+
+```ts
+ const [updatedShift] = await db
+ .update(shifts)
+ .set({
+ date,
+ startTime: body.startTime ?? existingShift.startTime,
+ endTime: body.endTime ?? existingShift.endTime,
+ title: body.title ?? existingShift.title,
+ color: body.color ?? existingShift.color,
+ notes: body.notes ?? existingShift.notes,
+ isAllDay: body.isAllDay ?? existingShift.isAllDay,
+ presetId: body.presetId ?? existingShift.presetId,
+ signupCapacity:
+ typeof body.signupCapacity === "number"
+ ? body.signupCapacity
+ : body.signupCapacity === null
+ ? null
+ : existingShift.signupCapacity,
+ updatedAt: new Date(),
+ })
+ .where(eq(shifts.id, id))
+ .returning();
+
+ return NextResponse.json(updatedShift);
+```
+
+with:
+
+```ts
+ const updatedShift = db.transaction((tx) => {
+ const updated = tx
+ .update(shifts)
+ .set({
+ date,
+ startTime: nextStartTime,
+ endTime: nextEndTime,
+ title: body.title ?? existingShift.title,
+ color: body.color ?? existingShift.color,
+ notes: body.notes ?? existingShift.notes,
+ isAllDay: nextIsAllDay,
+ presetId: body.presetId ?? existingShift.presetId,
+ signupCapacity:
+ typeof body.signupCapacity === "number"
+ ? body.signupCapacity
+ : body.signupCapacity === null
+ ? null
+ : existingShift.signupCapacity,
+ updatedAt: new Date(),
+ })
+ .where(eq(shifts.id, id))
+ .returning()
+ .get();
+ if (nextSegments !== undefined) {
+ replaceShiftSegments(tx, id, nextSegments);
+ }
+ return updated;
+ });
+
+ const [withSegments] = await withShiftSegments([updatedShift]);
+ return NextResponse.json(withSegments);
+```
+
+- [ ] **Step 7: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint app/api/shifts/[id]/route.ts app/api/shifts/route.ts`
+Expected: clean.
+
+- [ ] **Step 8: Manual smoke test against the running dev server**
+
+Run `npm run dev` in the background, then (with a real session cookie or `AUTH_ENABLED=false`) exercise both routes:
+```bash
+curl -s -X POST http://localhost:3000/api/shifts -H "Content-Type: application/json" \
+ -d '{"calendarId":"<id>","date":"2026-09-20","startTime":"06:00","endTime":"10:00","title":"Test","segments":[{"startTime":"15:00","endTime":"21:00"}]}' | jq .
+```
+Expected: `201`, response contains `startTime: "06:00"`, `endTime: "10:00"`, `segments: [{"startTime":"15:00","endTime":"21:00"}]` — unless the target calendar has `splitShiftsEnabled: false`, in which case expect a `400` with `"Split shifts are not enabled for this calendar"` (this is expected until Task 6 lets you flip the toggle; for now confirm the 400 path works, then re-test the 201 path after Task 6/9 are done and the toggle is on).
+
+- [ ] **Step 9: Commit**
+
+```bash
+git add app/api/shifts/route.ts app/api/shifts/[id]/route.ts
+git commit -m "feat(api): validate and persist shift time segments"
+```
+
+---
+
+### Task 5: Presets API — read, create, update (with cascade)
+
+**Files:**
+- Modify: `app/api/presets/route.ts`
+- Modify: `app/api/presets/[id]/route.ts`
+
+**Interfaces:**
+- Consumes: `toTimeRanges`, `validateTimeRanges` (`lib/time-ranges.ts`); `replacePresetSegments`, `replaceShiftSegments`, `withPresetSegments` (`lib/shift-time-ranges.ts`).
+- Produces: preset API responses gain `segments: TimeRange[]`; `POST`/`PATCH` accept an optional `segments` field.
+
+- [ ] **Step 1: `GET /api/presets` — attach segments**
+
+Add import `import { withPresetSegments } from "@/lib/shift-time-ranges";`. Replace:
+
+```ts
+ const presets = await db
+ .select()
+ .from(shiftPresets)
+ .where(eq(shiftPresets.calendarId, calendarId))
+ .orderBy(asc(shiftPresets.order));
+ return NextResponse.json(presets);
+```
+
+with:
+
+```ts
+ const presets = await db
+ .select()
+ .from(shiftPresets)
+ .where(eq(shiftPresets.calendarId, calendarId))
+ .orderBy(asc(shiftPresets.order));
+ return NextResponse.json(await withPresetSegments(presets));
+```
+
+- [ ] **Step 2: `POST /api/presets` — validate and persist segments**
+
+Add imports:
+
+```ts
+import { replacePresetSegments } from "@/lib/shift-time-ranges";
+import { toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
+```
+
+Extend the destructuring:
+
+```ts
+ const {
+ calendarId,
+ title,
+ startTime,
+ endTime,
+ color,
+ notes,
+ groupName,
+ isSecondary,
+ isAllDay,
+ hideFromStats,
+ defaultSignupCapacity,
+ segments: requestedSegments,
+ } = body;
+```
+
+After the existing calendar fetch and the `createPreset` capability check, before the "max order" block, add:
+
+```ts
+ const rawSegments: TimeRange[] = isAllDay || !Array.isArray(requestedSegments)
+ ? []
+ : requestedSegments;
+ if (rawSegments.length > 0 && !calendar.splitShiftsEnabled) {
+ return NextResponse.json(
+ { error: "Split shifts are not enabled for this calendar" },
+ { status: 400 }
+ );
+ }
+ if (!isAllDay) {
+ const validationError = validateTimeRanges(
+ toTimeRanges({ startTime, endTime, segments: rawSegments })
+ );
+ if (validationError) {
+ return NextResponse.json({ error: validationError }, { status: 400 });
+ }
+ }
+```
+
+Replace the insert call:
+
+```ts
+ const [preset] = await db
+ .insert(shiftPresets)
+ .values({
+ calendarId,
+ title,
+ startTime: isAllDay ? "00:00" : startTime,
+ endTime: isAllDay ? "23:59" : endTime,
+ color: color || "#3b82f6",
+ notes: notes || null,
+ groupName: groupName ? trimOrNull(groupName) : null,
+ isSecondary: isSecondary || false,
+ isAllDay: isAllDay || false,
+ hideFromStats: hideFromStats || false,
+ defaultSignupCapacity:
+ typeof defaultSignupCapacity === "number"
+ ? defaultSignupCapacity
+ : null,
+ order: maxOrder + 1,
+ createdBy: user?.id ?? null,
+ })
+ .returning();
+
+ return NextResponse.json(preset);
+```
+
+with:
+
+```ts
+ const preset = db.transaction((tx) => {
+ const inserted = tx
+ .insert(shiftPresets)
+ .values({
+ calendarId,
+ title,
+ startTime: isAllDay ? "00:00" : startTime,
+ endTime: isAllDay ? "23:59" : endTime,
+ color: color || "#3b82f6",
+ notes: notes || null,
+ groupName: groupName ? trimOrNull(groupName) : null,
+ isSecondary: isSecondary || false,
+ isAllDay: isAllDay || false,
+ hideFromStats: hideFromStats || false,
+ defaultSignupCapacity:
+ typeof defaultSignupCapacity === "number"
+ ? defaultSignupCapacity
+ : null,
+ order: maxOrder + 1,
+ createdBy: user?.id ?? null,
+ })
+ .returning()
+ .get();
+ replacePresetSegments(tx, inserted.id, rawSegments);
+ return inserted;
+ });
+
+ return NextResponse.json({ ...preset, segments: rawSegments });
+```
+
+Add `import { db } from "@/lib/db";` at the top if not already present (it already is — `db` is imported on line 2 of this file).
+
+- [ ] **Step 3: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint app/api/presets/route.ts`
+Expected: clean.
+
+- [ ] **Step 4: `PATCH /api/presets/[id]` — validate, persist, and cascade to child shifts**
+
+Add imports to `app/api/presets/[id]/route.ts`:
+
+```ts
+import { replacePresetSegments, replaceShiftSegments, withPresetSegments } from "@/lib/shift-time-ranges";
+import { toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
+```
+
+Extend the destructuring in `PATCH`:
+
+```ts
+ const {
+ title,
+ startTime,
+ endTime,
+ color,
+ notes,
+ groupName,
+ isSecondary,
+ isAllDay,
+ hideFromStats,
+ defaultSignupCapacity,
+ segments: requestedSegments,
+ } = body;
+```
+
+After the existing permission check (`hasAccess` for `manageOwnPresets`/`manageAnyPresets`) and before the update call, add:
+
+```ts
+ const nextIsAllDay = isAllDay !== undefined ? isAllDay : existingPreset.isAllDay;
+ 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 validationError = validateTimeRanges(
+ toTimeRanges({
+ startTime: startTime ?? existingPreset.startTime,
+ endTime: endTime ?? existingPreset.endTime,
+ segments: rawSegments,
+ })
+ );
+ if (validationError) {
+ return NextResponse.json({ error: validationError }, { status: 400 });
+ }
+ }
+ nextSegments = nextIsAllDay ? [] : rawSegments;
+ }
+```
+
+Replace the two existing update calls (preset row + cascaded shifts) with a single transaction that also cascades segments:
+
+```ts
+ const updatedPreset = db.transaction((tx) => {
+ const updated = tx
+ .update(shiftPresets)
+ .set({
+ title,
+ startTime: isAllDay ? "00:00" : startTime,
+ endTime: isAllDay ? "23:59" : endTime,
+ 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);
+ }
+
+ // 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" : startTime,
+ endTime: isAllDay ? "23:59" : endTime,
+ 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]);
+ return NextResponse.json(withSegments);
+```
+
+- [ ] **Step 5: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint app/api/presets/[id]/route.ts`
+Expected: clean.
+
+- [ ] **Step 6: Manual smoke test**
+
+With the dev server running, create a preset with two ranges, create a shift from it, then PATCH the preset's segments and confirm the shift picks up the new segments:
+```bash
+curl -s -X PATCH http://localhost:3000/api/presets/<presetId> -H "Content-Type: application/json" \
+ -d '{"title":"Frühdienst","startTime":"06:00","endTime":"10:00","color":"#3b82f6","segments":[{"startTime":"14:00","endTime":"18:00"}]}' | jq .segments
+curl -s http://localhost:3000/api/shifts/<childShiftId> | jq .segments
+```
+Expected: both print `[{"startTime":"14:00","endTime":"18:00"}]`.
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add app/api/presets/route.ts app/api/presets/[id]/route.ts
+git commit -m "feat(api): validate, persist, and cascade preset time segments"
+```
+
+---
+
+### Task 6: Calendars API — the `splitShiftsEnabled` toggle
+
+**Files:**
+- Modify: `app/api/calendars/route.ts`
+- Modify: `app/api/calendars/[id]/route.ts`
+
+**Interfaces:**
+- Produces: `GET /api/calendars` rows include `splitShiftsEnabled`; `PATCH /api/calendars/[id]` accepts and persists `splitShiftsEnabled`.
+
+- [ ] **Step 1: Include the field in the calendars list select**
+
+In `app/api/calendars/route.ts`, in the `.select({...})` block, add the field next to `signupsEnabled`:
+
+```ts
+ signupsEnabled: calendars.signupsEnabled,
+ splitShiftsEnabled: calendars.splitShiftsEnabled,
+```
+
+- [ ] **Step 2: Accept and persist it in the PATCH route**
+
+In `app/api/calendars/[id]/route.ts`, extend the destructuring:
+
+```ts
+ const { name, color, guestBundleId, viewSettings, signupsEnabled, splitShiftsEnabled } = body;
+```
+
+Extend `wantsGeneralChange` so the permission gate also covers this field:
+
+```ts
+ const wantsGeneralChange =
+ name !== undefined ||
+ color !== undefined ||
+ viewSettings !== undefined ||
+ typeof signupsEnabled === "boolean" ||
+ typeof splitShiftsEnabled === "boolean";
+```
+
+Add the write, mirroring the `signupsEnabled` block exactly:
+
+```ts
+ if (
+ typeof splitShiftsEnabled === "boolean" &&
+ splitShiftsEnabled !== existingCalendar.splitShiftsEnabled
+ ) {
+ updateData.splitShiftsEnabled = splitShiftsEnabled;
+ changes.push("splitShiftsEnabled");
+ }
+```
+
+- [ ] **Step 3: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint app/api/calendars/route.ts app/api/calendars/[id]/route.ts`
+Expected: clean.
+
+- [ ] **Step 4: Manual smoke test**
+
+```bash
+curl -s -X PATCH http://localhost:3000/api/calendars/<id> -H "Content-Type: application/json" \
+ -d '{"splitShiftsEnabled": true}' | jq .splitShiftsEnabled
+```
+Expected: `true`. Re-run Task 4 Step 8's `curl` against a shift on this same calendar — it should now return `201` instead of `400`.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add app/api/calendars/route.ts "app/api/calendars/[id]/route.ts"
+git commit -m "feat(api): add splitShiftsEnabled calendar toggle"
+```
+
+---
+
+### Task 7: Duration and display helpers (incl. stats)
+
+**Files:**
+- Modify: `lib/shift-display.ts`
+- Modify: `app/api/shifts/stats/route.ts`
+
+**Interfaces:**
+- Consumes: `toTimeRanges`, `sumRangeDurations` from `lib/time-ranges.ts`.
+- Produces: `formatTimeRange()` now joins multiple ranges; `getShiftMinutes()` now sums across segments.
+
+- [ ] **Step 1: Update `formatTimeRange` and `getShiftMinutes` in `lib/shift-display.ts`**
+
+Add the import: `import { toTimeRanges, sumRangeDurations } from "@/lib/time-ranges";`
+
+Replace:
+
+```ts
+export function getShiftMinutes(shift: ShiftWithCalendar): number {
+ return shift.isAllDay
+ ? 0
+ : calculateShiftDuration(shift.startTime, shift.endTime);
+}
+```
+
+with:
+
+```ts
+export function getShiftMinutes(shift: ShiftWithCalendar): number {
+ return shift.isAllDay ? 0 : sumRangeDurations(toTimeRanges(shift));
+}
+```
+
+Replace:
+
+```ts
+export function formatTimeRange(times: {
+ startTime: string;
+ endTime: string;
+}): string {
+ return `${times.startTime.slice(0, 5)} – ${times.endTime.slice(0, 5)}`;
+}
+```
+
+with:
+
+```ts
+export function formatTimeRange(times: {
+ startTime: string;
+ endTime: string;
+ segments?: { startTime: string; endTime: string }[];
+}): string {
+ return toTimeRanges(times)
+ .map((range) => `${range.startTime.slice(0, 5)} – ${range.endTime.slice(0, 5)}`)
+ .join(", ");
+}
+```
+
+`calculateShiftDuration` is still imported and used elsewhere in this file (e.g. nowhere else currently, so if `tsc`/lint flags it as unused after this change, remove the now-unused import — check with the next step).
+
+- [ ] **Step 2: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint lib/shift-display.ts`
+Expected: clean; if `calculateShiftDuration` is now unused in this file, remove its import.
+
+- [ ] **Step 3: Update the stats route to sum segments**
+
+In `app/api/shifts/stats/route.ts`, add imports:
+
+```ts
+import { withShiftSegments } from "@/lib/shift-time-ranges";
+import { toTimeRanges, sumRangeDurations } from "@/lib/time-ranges";
+```
+
+After the existing `result` query (the `.select({...}).from(shifts)...` call that selects `id, title, date, startTime, endTime, isAllDay`), attach segments:
+
+```ts
+ const resultWithSegments = await withShiftSegments(result);
+```
+
+Replace the duration line inside the `result.forEach((shift) => { ... })` loop — change `result.forEach` to `resultWithSegments.forEach`, and replace:
+
+```ts
+ const duration = shift.isAllDay
+ ? 0
+ : calculateShiftDuration(shift.startTime, shift.endTime);
+```
+
+with:
+
+```ts
+ const duration = shift.isAllDay ? 0 : sumRangeDurations(toTimeRanges(shift));
+```
+
+Also change the later `const totalShifts = result.length;` to `const totalShifts = resultWithSegments.length;` (same value, just keeping the variable name consistent with the renamed source array — check every other bare `result` reference in this file with `grep -n "\bresult\b" app/api/shifts/stats/route.ts` and rename them all to `resultWithSegments` so nothing silently keeps reading the pre-segments array).
+
+- [ ] **Step 4: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint app/api/shifts/stats/route.ts`
+Expected: clean, no leftover references to the old `result` variable name.
+
+- [ ] **Step 5: Manual smoke test**
+
+```bash
+curl -s "http://localhost:3000/api/shifts/stats?calendarId=<id>&period=month" | jq '.totalMinutes, .stats'
+```
+For a calendar with one split shift (`06:00–10:00` + `15:00–21:00` = 240 + 360 = 600 minutes) and nothing else in the period, expect `totalMinutes: 600`.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add lib/shift-display.ts app/api/shifts/stats/route.ts
+git commit -m "feat: sum split-shift durations in display helpers and stats"
+```
+
+---
+
+### Task 8: PDF and ICS exports
+
+**Files:**
+- Modify: `app/api/export/pdf/route.ts`
+- Modify: `app/api/export/ics/route.ts`
+
+**Interfaces:**
+- Consumes: `formatTimeRange` (`lib/shift-display.ts`) for PDF; `toTimeRanges` (`lib/time-ranges.ts`) for ICS.
+
+- [ ] **Step 1: PDF — join ranges**
+
+Both `app/api/export/pdf/route.ts` and `app/api/export/ics/route.ts` use `db.query.shifts.findMany(...)` (the Drizzle relational API), so they can request the relation directly instead of a separate helper call. In `app/api/export/pdf/route.ts`, change the shifts query:
+
+```ts
+ let allShifts = await db.query.shifts.findMany({
+ where: inArray(
+ shifts.calendarId,
+ accessibleCalendars.map((c) => c.id)
+ ),
+ orderBy: (shifts, { asc }) => [asc(shifts.date)],
+ });
+```
+
+to:
+
+```ts
+ let allShifts = await db.query.shifts.findMany({
+ where: inArray(
+ shifts.calendarId,
+ accessibleCalendars.map((c) => c.id)
+ ),
+ orderBy: (shifts, { asc }) => [asc(shifts.date)],
+ with: { segments: true },
+ });
+```
+
+Add the import `import { formatTimeRange } from "@/lib/shift-display";` and replace:
+
+```ts
+ const timeStr = shift.isAllDay
+ ? "—" // Em dash for all-day shifts
+ : `${shift.startTime} - ${shift.endTime}`;
+```
+
+with:
+
+```ts
+ const timeStr = shift.isAllDay ? "—" : formatTimeRange(shift);
+```
+
+- [ ] **Step 2: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint app/api/export/pdf/route.ts`
+Expected: clean.
+
+- [ ] **Step 3: ICS — one VEVENT per range**
+
+In `app/api/export/ics/route.ts`, change the shifts query the same way:
+
+```ts
+ const allShifts = await db.query.shifts.findMany({
+ where: inArray(
+ shifts.calendarId,
+ accessibleCalendars.map((c) => c.id)
+ ),
+ orderBy: (shifts, { asc }) => [asc(shifts.date)],
+ with: { segments: true },
+ });
+```
+
+Add the import `import { toTimeRanges } from "@/lib/time-ranges";`. Replace the whole `for (const shift of allShifts) { ... }` body's event-creation section — everything from `const vevent = new ICAL.Component("vevent");` through `cal.addSubcomponent(vevent);` — with a loop over ranges that shares the shift's summary/description/color but gives each range its own VEVENT:
+
+```ts
+ for (const shift of allShifts) {
+ const shiftDate = shift.date as Date;
+ const calendarName = calendarMap.get(shift.calendarId);
+ const summary = isMultiCalendar
+ ? `[${calendarName}] ${shift.title}`
+ : shift.title;
+
+ const ranges = shift.isAllDay ? [null] : toTimeRanges(shift);
+
+ ranges.forEach((range, index) => {
+ const vevent = new ICAL.Component("vevent");
+ const event = new ICAL.Event(vevent);
+
+ event.uid = index === 0 ? shift.id : `${shift.id}-seg-${index}`;
+ event.summary = summary;
+ if (shift.notes) {
+ event.description = shift.notes;
+ }
+
+ if (!range) {
+ // All-day event (DTEND is exclusive per RFC 5545)
+ const dateStr = formatDateToLocal(shiftDate);
+ event.startDate = ICAL.Time.fromDateString(dateStr);
+
+ const endDate = new Date(shiftDate);
+ endDate.setDate(endDate.getDate() + 1);
+ const endYear = endDate.getFullYear();
+ const endMonth = String(endDate.getMonth() + 1).padStart(2, "0");
+ const endDay = String(endDate.getDate()).padStart(2, "0");
+ event.endDate = ICAL.Time.fromDateString(`${endYear}-${endMonth}-${endDay}`);
+ } else {
+ const [startHour, startMinute] = range.startTime.split(":").map(Number);
+ const [endHour, endMinute] = range.endTime.split(":").map(Number);
+
+ const startDateTime = new Date(shiftDate);
+ startDateTime.setHours(startHour, startMinute, 0, 0);
+
+ const endDateTime = new Date(shiftDate);
+ endDateTime.setHours(endHour, endMinute, 0, 0);
+
+ if (endDateTime <= startDateTime) {
+ endDateTime.setDate(endDateTime.getDate() + 1);
+ }
+
+ event.startDate = ICAL.Time.fromJSDate(startDateTime, true);
+ event.endDate = ICAL.Time.fromJSDate(endDateTime, true);
+ }
+
+ vevent.addPropertyWithValue("color", shift.color);
+ vevent.addPropertyWithValue("x-apple-calendar-color", shift.color);
+
+ cal.addSubcomponent(vevent);
+ });
+ }
+```
+
+- [ ] **Step 4: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint app/api/export/ics/route.ts`
+Expected: clean.
+
+- [ ] **Step 5: Manual smoke test**
+
+```bash
+curl -s -X POST http://localhost:3000/api/export/ics -H "Content-Type: application/json" \
+ -d '{"calendarIds":["<id>"]}' -o /tmp/test-export.ics
+grep -c BEGIN:VEVENT /tmp/test-export.ics
+```
+For a calendar with one split shift (2 ranges) and nothing else, expect `2`.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add app/api/export/pdf/route.ts app/api/export/ics/route.ts
+git commit -m "feat(export): render split-shift ranges in PDF and ICS exports"
+```
+
+---
+
+### Task 9: Calendar settings UI toggle + its i18n keys
+
+**Files:**
+- Modify: `components/calendar-permissions-panel.tsx`
+- Modify: `messages/de.json`, `messages/en.json`, `messages/es.json`, `messages/fr.json`, `messages/it.json`, `messages/cs.json`
+
+**Interfaces:**
+- Consumes: `useCalendars().updateCalendar` (already handles arbitrary `CalendarUpdateInput` fields), `ToggleRow`/`InfoNote`/`SectionLabel` from `components/form-kit`.
+
+- [ ] **Step 1: Add the i18n keys to `messages/de.json`**
+
+Find the `sharingSheet` object (it already has `signupsEnabledLabel`/`signupsEnabledDesc`) and add, next to those two keys:
+
+```json
+ "splitShiftsEnabledLabel": "Geteilte Dienste aktivieren",
+ "splitShiftsEnabledDesc": "Erlaubt mehrere Zeitfenster in einer Schicht oder Vorlage, z. B. 06:00–10:00 und 15:00–21:00. Ausgeschaltet werden zusätzliche Zeitfenster überall ausgeblendet.",
+```
+
+Find the `permissionBundles` object (it has `groups.signups`, `signupsLocked`, `signupsCapabilityHint`) and add:
+
+```json
+ "splitShiftsLocked": "Nur wer Kalendereinstellungen verwalten darf, kann geteilte Dienste ein- oder ausschalten.",
+```
+
+and inside its nested `groups` object, next to `"signups": "Anmeldungen"`:
+
+```json
+ "splitShifts": "Geteilte Dienste",
+```
+
+- [ ] **Step 2: Mirror the same keys into the other 5 locale files**
+
+For each of `en.json`, `es.json`, `fr.json`, `it.json`, `cs.json`, add the same three keys (`sharingSheet.splitShiftsEnabledLabel`, `sharingSheet.splitShiftsEnabledDesc`, `permissionBundles.splitShiftsLocked`, `permissionBundles.groups.splitShifts`) at the same nesting depth, translated. English (`en.json`) reference translation:
+
+```json
+ "splitShiftsEnabledLabel": "Enable split shifts",
+ "splitShiftsEnabledDesc": "Allows multiple time ranges in one shift or preset, e.g. 06:00–10:00 and 15:00–21:00. Turning this off hides extra time ranges everywhere.",
+```
+```json
+ "splitShiftsLocked": "Only someone who can manage calendar settings can turn split shifts on or off.",
+```
+```json
+ "splitShifts": "Split shifts",
+```
+
+Translate the same meaning into `es.json`, `fr.json`, `it.json`, `cs.json` following each file's existing tone for the neighboring `signupsEnabled*`/`signupsLocked`/`groups.signups` keys (open each file, find those keys, and match register/formality).
+
+- [ ] **Step 3: Run the i18n check**
+
+Run: `npm run i18n`
+Expected: no missing/unused key errors for the six new keys.
+
+- [ ] **Step 4: Add the toggle UI**
+
+In `components/calendar-permissions-panel.tsx`, add local state next to `optimisticSignupsEnabled`:
+
+```ts
+ const [optimisticSplitShiftsEnabled, setOptimisticSplitShiftsEnabled] = useState<boolean | null>(null);
+```
+
+Right after `const signupsEnabled = ...` line, add:
+
+```ts
+ const splitShiftsEnabled =
+ optimisticSplitShiftsEnabled ?? calendar?.splitShiftsEnabled ?? false;
+```
+
+Right after `handleSignupsEnabledChange`, add the matching handler:
+
+```ts
+ const handleSplitShiftsEnabledChange = async (value: boolean) => {
+ if (value === splitShiftsEnabled) return;
+ setOptimisticSplitShiftsEnabled(value);
+ setSaving(true);
+ try {
+ await updateCalendar(calendarId, { splitShiftsEnabled: value });
+ } catch {
+ // updateCalendar already reported the error and rolled back the cache.
+ } finally {
+ setSaving(false);
+ setOptimisticSplitShiftsEnabled(null);
+ }
+ };
+```
+
+Right after the existing signups `<section>` block (the one ending with `</section>` that contains the `signups-enabled` `ToggleRow`), add a second section:
+
+```tsx
+ <section className="flex flex-col gap-3 border-t border-line pt-5">
+ <SectionLabel className="mb-0">{t("permissionBundles.groups.splitShifts")}</SectionLabel>
+ <ToggleRow
+ id="split-shifts-enabled"
+ title={t("sharingSheet.splitShiftsEnabledLabel")}
+ description={t("sharingSheet.splitShiftsEnabledDesc")}
+ checked={splitShiftsEnabled}
+ onCheckedChange={handleSplitShiftsEnabledChange}
+ disabled={saving || !canManageSettings}
+ />
+ {!canManageSettings && (
+ <InfoNote icon={Lock}>{t("permissionBundles.splitShiftsLocked")}</InfoNote>
+ )}
+ </section>
+```
+
+- [ ] **Step 5: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint components/calendar-permissions-panel.tsx`
+Expected: clean.
+
+- [ ] **Step 6: Manual verification in the browser**
+
+With `npm run dev` running, open the app, go to a calendar's permissions/sharing panel, confirm the new "Geteilte Dienste" section renders below "Anmeldungen" with a working toggle (disabled for non-managers, saving state visible while in flight).
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add components/calendar-permissions-panel.tsx messages/*.json
+git commit -m "feat(ui): add split-shifts calendar toggle"
+```
+
+---
+
+### Task 10: Shift form — segment editor
+
+**Files:**
+- Modify: `components/shift-sheet.tsx`
+- Modify: `components/shift-form-fields.tsx`
+- Modify: `hooks/useShiftForm.ts`
+- Modify: `hooks/useShifts.ts`
+- Modify: `messages/de.json`, `messages/en.json`, `messages/es.json`, `messages/fr.json`, `messages/it.json`, `messages/cs.json`
+
+**Interfaces:**
+- Consumes: `TimeRange`, `validateTimeRanges` (`lib/time-ranges.ts`); `useCalendars` for `calendar.splitShiftsEnabled`.
+- Produces: `ShiftFormData.segments: TimeRange[]`.
+
+- [ ] **Step 1: Add the i18n keys**
+
+In `messages/de.json`, add a new top-level `timeRanges` object (place it alphabetically near `shiftSheet`/`shiftSignup`):
+
+```json
+ "timeRanges": {
+ "add": "Zeitfenster hinzufügen",
+ "remove": "Zeitfenster entfernen",
+ "errors": {
+ "overlap": "Zeitfenster dürfen sich nicht überschneiden.",
+ "overnight_segment": "Bei mehreren Zeitfenstern muss jedes am selben Tag enden.",
+ "invalid_format": "Ungültige Uhrzeit."
+ }
+ },
+```
+
+Mirror into the other five locale files, e.g. `en.json`:
+
+```json
+ "timeRanges": {
+ "add": "Add time range",
+ "remove": "Remove time range",
+ "errors": {
+ "overlap": "Time ranges must not overlap.",
+ "overnight_segment": "With multiple time ranges, each one must end on the same day.",
+ "invalid_format": "Invalid time."
+ }
+ },
+```
+
+Translate the same three error keys plus `add`/`remove` into `es.json`, `fr.json`, `it.json`, `cs.json`.
+
+Run: `npm run i18n` — expect no missing-key errors (there will be "unused key" warnings until Step 4 below wires up the actual `t()` calls; that's expected mid-task, resolve by the end of this task).
+
+- [ ] **Step 2: `ShiftFormData` gains `segments`**
+
+In `components/shift-sheet.tsx`, add the field:
+
+```ts
+export interface ShiftFormData {
+ date: string;
+ startTime: string;
+ endTime: string;
+ title: string;
+ color?: string;
+ notes?: string;
+ presetId?: string;
+ isAllDay?: boolean;
+ signupCapacity?: number | null;
+ segments?: TimeRange[];
+ signupUserIds?: string[];
+}
+```
+
+Add the import `import type { TimeRange } from "@/lib/time-ranges";`.
+
+Update `snapshot()` to include it in the dirty-check:
+
+```ts
+function snapshot(data: ShiftFormData) {
+ return JSON.stringify({
+ date: data.date,
+ startTime: data.startTime,
+ endTime: data.endTime,
+ title: data.title,
+ notes: data.notes || "",
+ color: data.color,
+ isAllDay: data.isAllDay || false,
+ signupCapacity: data.signupCapacity ?? null,
+ segments: data.segments ?? [],
+ });
+}
+```
+
+Update `initialSnapshot`'s object literal (inside the `useMemo`) to also pass `segments: shift.segments ?? []`.
+
+- [ ] **Step 3: `useShiftForm.ts` manages `segments` in form state**
+
+Add the import `import type { TimeRange } from "@/lib/time-ranges";`. In every place `useState<ShiftFormData>` initializes or `resetForm`/`clearPreset`/`applyPreset` rebuild the object, add `segments: shift?.segments ?? []` (for the initial state and the `open`-effect branch) or `segments: []` (for `resetForm`/`clearPreset`) or `segments: preset.segments ?? []` (for `applyPreset` — the `ShiftPreset` type doesn't carry `segments` by default since it's a joined field, so widen `applyPreset`'s parameter type from `ShiftPreset` to `ShiftPreset & { segments?: TimeRange[] }`).
+
+Concretely:
+- Initial `useState<ShiftFormData>(...)`: add `segments: shift?.segments ?? [],`
+- `applyPreset`: change signature to `(preset: ShiftPreset & { segments?: TimeRange[] })` and add `segments: preset.segments ?? [],` to the `setFormData` call.
+- `clearPreset`: add `segments: [],`
+- `resetForm`: add `segments: [],`
+- The `open`-effect's `newFormData` object: add `segments: shift?.segments ?? [],`, and add `formDataRef.current.segments !== newFormData.segments` is wrong for arrays — instead add a length+content check: extend `needsUpdate` with ``JSON.stringify(formDataRef.current.segments ?? []) !== JSON.stringify(newFormData.segments ?? [])``.
+
+- [ ] **Step 4: `ShiftFormFields` — render the segment editor**
+
+Add imports:
+
+```ts
+import { validateTimeRanges, toTimeRanges, type TimeRange } from "@/lib/time-ranges";
+import { Button } from "@/components/ui/button";
+import { Plus, X } from "lucide-react";
+```
+
+Add a new prop `splitShiftsEnabled?: boolean` to `ShiftFormFieldsProps`.
+
+Right after the existing start/end/duration `<div className="flex gap-2.5">` block (still inside the `<div className="flex flex-col gap-2.5 lg:gap-3">` wrapper, before the `<CheckRow id="allDay" ...>`), add:
+
+```tsx
+ {!formData.isAllDay && (formData.segments?.length ?? 0) > 0 && (
+ <div className="flex flex-col gap-2">
+ {(formData.segments ?? []).map((segment, index) => (
+ <div key={index} className="flex items-end gap-2.5">
+ <Field label={t("shiftSheet.start")} className="flex-1">
+ <Input
+ type="time"
+ value={segment.startTime}
+ onChange={(e) => {
+ const next = [...(formData.segments ?? [])];
+ next[index] = { ...next[index], startTime: e.target.value };
+ onFormDataChange({ ...formData, segments: next });
+ }}
+ disabled={readOnly}
+ className={cn(inputClass, "font-mono")}
+ />
+ </Field>
+ <Field label={t("shiftSheet.end")} className="flex-1">
+ <Input
+ type="time"
+ value={segment.endTime}
+ onChange={(e) => {
+ const next = [...(formData.segments ?? [])];
+ next[index] = { ...next[index], endTime: e.target.value };
+ onFormDataChange({ ...formData, segments: next });
+ }}
+ disabled={readOnly}
+ className={cn(inputClass, "font-mono")}
+ />
+ </Field>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ className="mb-[1px] shrink-0"
+ aria-label={t("timeRanges.remove")}
+ disabled={readOnly}
+ onClick={() => {
+ const next = (formData.segments ?? []).filter((_, i) => i !== index);
+ onFormDataChange({ ...formData, segments: next });
+ }}
+ >
+ <X className="size-4" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {!formData.isAllDay && splitShiftsEnabled && !readOnly && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="self-start"
+ onClick={() =>
+ onFormDataChange({
+ ...formData,
+ segments: [...(formData.segments ?? []), { startTime: "12:00", endTime: "14:00" }],
+ })
+ }
+ >
+ <Plus className="size-4" />
+ {t("timeRanges.add")}
+ </Button>
+ )}
+
+ {!formData.isAllDay &&
+ (() => {
+ const error = validateTimeRanges(toTimeRanges(formData));
+ return error ? (
+ <p className="text-[13px] text-destructive">{t(`timeRanges.errors.${error}`)}</p>
+ ) : null;
+ })()}
+```
+
+Check the exact class name this codebase uses for inline validation-error text (grep `text-destructive` or similar across `components/*.tsx` — e.g. `grep -rn "text-destructive\|text-error\|text-danger" components | head -5`) and use that project's existing error-text class instead of guessing, if it differs.
+
+- [ ] **Step 5: Thread `splitShiftsEnabled` from `ShiftSheet`**
+
+In `components/shift-sheet.tsx`, add `import { useCalendars } from "@/hooks/useCalendars";`. Inside the `ShiftSheet` component, after `const permission = useCalendarPermission(calendarId);`, add:
+
+```ts
+ const { calendars } = useCalendars();
+ const splitShiftsEnabled = calendars.find((c) => c.id === calendarId)?.splitShiftsEnabled ?? false;
+```
+
+Pass it to `<ShiftFormFields ... splitShiftsEnabled={splitShiftsEnabled} />`.
+
+Also update `handleSave`'s `submitData` to pass segments through unchanged for all-day (clear them) shifts:
+
+```ts
+ const submitData = {
+ ...formData,
+ startTime: formData.isAllDay ? "00:00" : formData.startTime,
+ endTime: formData.isAllDay ? "23:59" : formData.endTime,
+ segments: formData.isAllDay ? [] : formData.segments,
+ ...(!shift ? { signupUserIds: pendingSignupUserIds } : {}),
+ };
+```
+
+Also block saving on a validation error — change `saveDisabled` on `<BaseSheet>`:
+
+```tsx
+ saveDisabled={
+ !formData.title.trim() ||
+ (shift && !hasChanges()) ||
+ (!formData.isAllDay && !!validateTimeRanges(toTimeRanges(formData)))
+ }
+```
+(add the same `validateTimeRanges`/`toTimeRanges` import used in Step 4 to this file too).
+
+- [ ] **Step 6: `useShifts.ts` — carry `segments` in the optimistic shift**
+
+Find `createOptimisticShift`-equivalent code inside the `useCreateShift`-style mutation (the block building an optimistic `ShiftWithCalendar` around lines 145-160, referenced by `startTime: formData.startTime, endTime: formData.endTime,`). Add `segments: formData.segments ?? [],` next to those two lines, and do the same in the update mutation's optimistic patch (around lines 255-265).
+
+- [ ] **Step 7: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint components/shift-sheet.tsx components/shift-form-fields.tsx hooks/useShiftForm.ts hooks/useShifts.ts`
+Expected: clean.
+
+- [ ] **Step 8: Run the i18n check again**
+
+Run: `npm run i18n`
+Expected: no missing or unused keys now that `timeRanges.*` is actually referenced from `shift-form-fields.tsx`.
+
+- [ ] **Step 9: Manual browser verification**
+
+With `npm run dev` running and a calendar that has `splitShiftsEnabled: true` (set via the Task 9 UI or a direct `curl` PATCH), open the shift-creation sheet:
+- Confirm the "Add time range" button appears and adds a second start/end row.
+- Enter an overlapping range and confirm the inline error text appears and Save is disabled.
+- Fix the overlap, Save, and confirm the created shift shows both ranges (e.g. via `day-detail.tsx`'s time label).
+- Toggle the calendar's split-shifts setting off and confirm the "Add time range" button disappears from a fresh create sheet (existing split shifts stay visible per the spec's "hidden, not deleted" rule — don't expect them to vanish from the grid, since Task 12 changes only the *display* of the primary+segments label, not a filter).
+
+- [ ] **Step 10: Commit**
+
+```bash
+git add components/shift-sheet.tsx components/shift-form-fields.tsx hooks/useShiftForm.ts hooks/useShifts.ts messages/*.json
+git commit -m "feat(ui): add split-shift time-range editor to the shift form"
+```
+
+---
+
+### Task 11: Preset form — segment editor
+
+**Files:**
+- Modify: `components/preset-form.tsx`
+- Modify: `hooks/usePresets.ts`
+- Modify: `hooks/useShiftForm.ts`
+
+**Interfaces:**
+- Consumes: `TimeRange`, `validateTimeRanges` (`lib/time-ranges.ts`).
+- Produces: `PresetFormData.segments: TimeRange[]`.
+
+**Note (added after Task 10's review):** `hooks/useShiftForm.ts`'s `saveAsPresetHandler` (added/touched in Task 10) builds a `PresetFormData` literal for `createPreset(...)` without `segments` — it couldn't set it before this task, since the field didn't exist yet. Once this task makes `segments: TimeRange[]` required on `PresetFormData`, that call site must be updated explicitly to `segments: shiftData.segments ?? []` — the shift's *actual* segments, not an empty default. Saving a split shift as a preset must preserve its segments; silently defaulting to `[]` here would be a data-loss bug, not just a type-safety fix. This is called out explicitly (not left to the generic "grep for other literals" step below) because it's the one site where real data is available and dropping it would be user-visible.
+
+- [ ] **Step 1: `PresetFormData` gains `segments`**
+
+In `hooks/usePresets.ts`, add the import `import type { TimeRange } from "@/lib/time-ranges";` and extend:
+
+```ts
+export interface PresetFormData {
+ title: string;
+ startTime: string;
+ endTime: string;
+ color: string;
+ notes: string;
+ groupName: string;
+ isSecondary: boolean;
+ isAllDay: boolean;
+ hideFromStats: boolean;
+ defaultSignupCapacity?: number | null;
+ segments: TimeRange[];
+}
+```
+
+Update `createOptimisticPreset` to include `segments: formData.segments,` in its returned object (widen its return type to `ShiftPreset & { segments: TimeRange[] }` since the base `ShiftPreset` type has no `segments` field).
+
+- [ ] **Step 2: `EMPTY_PRESET_FORM`, `presetToFormData`, `samePresetForm` in `components/preset-form.tsx`**
+
+Add the import `import type { TimeRange } from "@/lib/time-ranges";`. Update:
+
+```ts
+export const EMPTY_PRESET_FORM: PresetFormData = {
+ title: "",
+ startTime: "09:00",
+ endTime: "17:00",
+ color: DEFAULT_COLOR,
+ notes: "",
+ groupName: "",
+ isSecondary: false,
+ isAllDay: false,
+ hideFromStats: false,
+ defaultSignupCapacity: null,
+ segments: [],
+};
+
+export function presetToFormData(preset: ShiftPreset & { segments?: TimeRange[] }): PresetFormData {
+ return {
+ title: preset.title,
+ startTime: preset.startTime,
+ endTime: preset.endTime,
+ color: preset.color,
+ notes: preset.notes || "",
+ groupName: preset.groupName || "",
+ isSecondary: preset.isSecondary || false,
+ isAllDay: preset.isAllDay || false,
+ hideFromStats: preset.hideFromStats || false,
+ defaultSignupCapacity: preset.defaultSignupCapacity ?? null,
+ segments: preset.segments ?? [],
+ };
+}
+```
+
+`samePresetForm` already does a generic `Object.keys(a).every((key) => a[key] === b[key])` — a strict `===` on two array values is always `false` even for equal contents, which would make the form perpetually "dirty" once `segments` is non-empty. Change it to:
+
+```ts
+export function samePresetForm(a: PresetFormData, b: PresetFormData): boolean {
+ const { segments: segmentsA, ...restA } = a;
+ const { segments: segmentsB, ...restB } = b;
+ return (
+ (Object.keys(restA) as (keyof typeof restA)[]).every((key) => restA[key] === restB[key]) &&
+ JSON.stringify(segmentsA) === JSON.stringify(segmentsB)
+ );
+}
+```
+
+- [ ] **Step 3: Render the segment editor in `PresetFormCard`**
+
+Add the prop `splitShiftsEnabled?: boolean` to `PresetFormCardProps`. Add imports:
+
+```ts
+import { validateTimeRanges, toTimeRanges } from "@/lib/time-ranges";
+import { Button } from "@/components/ui/button";
+import { Plus, X } from "lucide-react";
+```
+
+Right after the existing `{!value.isAllDay && (<div className="grid grid-cols-2 gap-2.5">...</div>)}` start/end block, add:
+
+```tsx
+ {!value.isAllDay && value.segments.length > 0 && (
+ <div className="flex flex-col gap-2">
+ {value.segments.map((segment, index) => (
+ <div key={index} className="grid grid-cols-[1fr_1fr_auto] items-end gap-2.5">
+ <Field label={t("presetSheet.start")}>
+ <Input
+ type="time"
+ value={segment.startTime}
+ onChange={(e) => {
+ const next = [...value.segments];
+ next[index] = { ...next[index], startTime: e.target.value };
+ onChange({ segments: next });
+ }}
+ className={cn(fieldClass, "font-mono")}
+ disabled={disabled}
+ />
+ </Field>
+ <Field label={t("presetSheet.end")}>
+ <Input
+ type="time"
+ value={segment.endTime}
+ onChange={(e) => {
+ const next = [...value.segments];
+ next[index] = { ...next[index], endTime: e.target.value };
+ onChange({ segments: next });
+ }}
+ className={cn(fieldClass, "font-mono")}
+ disabled={disabled}
+ />
+ </Field>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ aria-label={t("timeRanges.remove")}
+ disabled={disabled}
+ onClick={() => onChange({ segments: value.segments.filter((_, i) => i !== index) })}
+ >
+ <X className="size-4" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {!value.isAllDay && splitShiftsEnabled && !disabled && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="self-start"
+ onClick={() =>
+ onChange({ segments: [...value.segments, { startTime: "12:00", endTime: "14:00" }] })
+ }
+ >
+ <Plus className="size-4" />
+ {t("timeRanges.add")}
+ </Button>
+ )}
+
+ {!value.isAllDay &&
+ (() => {
+ const error = validateTimeRanges(toTimeRanges(value));
+ return error ? <p className="text-[13px] text-destructive">{t(`timeRanges.errors.${error}`)}</p> : null;
+ })()}
+```
+
+- [ ] **Step 4: Thread `splitShiftsEnabled` and prevent saving on validation error**
+
+`components/preset-manage-sheet.tsx` renders `<PresetFormCard>` (around line 225) and already has `calendarId` as a prop. Add the import `import { useCalendars } from "@/hooks/useCalendars";` and `import { validateTimeRanges, toTimeRanges } from "@/lib/time-ranges";`, then inside the `PresetsPanel` component add:
+
+```ts
+ const { calendars } = useCalendars();
+ const splitShiftsEnabled = calendars.find((c) => c.id === calendarId)?.splitShiftsEnabled ?? false;
+```
+
+Pass it to the card: `<PresetFormCard ... splitShiftsEnabled={splitShiftsEnabled} />`.
+
+Extend the existing `canSave` line:
+
+```ts
+ const canSave =
+ !isSaving &&
+ formData.title.trim() !== "" &&
+ (!editingPreset || isDirty) &&
+ (formData.isAllDay || !validateTimeRanges(toTimeRanges(formData)));
+```
+
+- [ ] **Step 5: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint components/preset-form.tsx hooks/usePresets.ts hooks/useShiftForm.ts`
+Expected: clean once `hooks/useShiftForm.ts`'s `saveAsPresetHandler` sets `segments: shiftData.segments ?? []` (see the note at the top of this task — use the shift's real segments there, not an empty default). Also grep for any other direct `PresetFormData` literal construction that would now be missing the required `segments` field: `grep -rn "PresetFormData = {" components hooks` and `grep -rn ": PresetFormData\b" components hooks` — for any other site found this way (unlike `saveAsPresetHandler`, which has real data available), add `segments: []` since there is no better default.
+
+- [ ] **Step 6: Manual browser verification**
+
+With split shifts enabled on the test calendar, open the preset management sheet, create a preset with two time ranges, save it, confirm it round-trips (reopen and see both ranges). Then create a shift by stamping that preset and confirm the shift got both ranges.
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add components/preset-form.tsx hooks/usePresets.ts components/preset-manage-sheet.tsx
+git commit -m "feat(ui): add split-shift time-range editor to the preset form"
+```
+
+---
+
+### Task 12: Month grid display
+
+**Files:**
+- Modify: `components/month-grid.tsx`
+
+**Interfaces:**
+- Consumes: `formatTimeRange` (`lib/shift-display.ts`).
+
+- [ ] **Step 1: Use the joined range label in the desktop chip**
+
+Add the import `import { formatTimeRange } from "@/lib/shift-display";` (if not already imported — check the top of the file first). Replace the `time()` helper:
+
+```ts
+ const time = (shift: ShiftWithCalendar) => (
+ <span className="shrink-0 font-mono text-[10.5px] leading-4 opacity-75">
+ {shift.isAllDay ? t("calendarView.allDayShort") : shift.startTime.slice(0, 5)}
+ </span>
+ );
+```
+
+with:
+
+```ts
+ const time = (shift: ShiftWithCalendar) => (
+ <span className="shrink-0 whitespace-nowrap font-mono text-[10.5px] leading-4 opacity-75">
+ {shift.isAllDay ? t("calendarView.allDayShort") : formatTimeRange(shift)}
+ </span>
+ );
+```
+
+(`whitespace-nowrap` added because the label can now be longer than a single `HH:MM`; the parent chip is already `flex` with `min-w-0`/`truncate` on the title span, so the row itself will just take the width it needs without wrapping oddly — verify visually in Step 3.)
+
+- [ ] **Step 2: Type-check and lint**
+
+Run: `npx tsc --noEmit && npx eslint components/month-grid.tsx`
+Expected: clean.
+
+- [ ] **Step 3: Manual browser verification**
+
+With a split shift visible in the month grid on desktop, confirm the chip shows `06:00 – 10:00, 15:00 – 21:00 · <title>` and doesn't visually break the row. Resize to a narrow desktop width and confirm it still truncates gracefully (the title truncates via its own `truncate` class; the time span itself doesn't need to shrink further since chips already wrap to their content). Then switch to a phone-width viewport and confirm the phone chip is unaffected (still shows only the title, no time) — per the spec, no phone-specific change is expected or needed here.
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add components/month-grid.tsx
+git commit -m "feat(ui): show split-shift ranges in the desktop month grid"
+```
+
+---
+
+### Task 13: Full verification and PR
+
+**Files:** none (verification only, plus opening the PR).
+
+- [ ] **Step 1: Full type check**
+
+Run: `npx tsc --noEmit`
+Expected: zero errors across the whole project.
+
+- [ ] **Step 2: Full test pipeline**
+
+Run: `npm test`
+Expected: lint, build, and i18n all pass. If the build fails on a client component pulling in `better-sqlite3` (the exact failure mode the client/server split in Task 2/3 was meant to avoid), find which client file imports `lib/shift-time-ranges.ts` (it must only ever be imported from `app/api/**` route files) and fix the import to point at `lib/time-ranges.ts` instead.
+
+- [ ] **Step 3: Migration sanity check on a clean database**
+
+```bash
+rm -f data/sqlite.db
+npm run db:migrate
+```
+Expected: exits 0, `data/sqlite.db` is recreated with all tables including `shift_time_segments`, `preset_time_segments`, and `calendars.split_shifts_enabled`. (This only matters for a scratch/dev database — never run this against a database with real data you want to keep.)
+
+- [ ] **Step 4: End-to-end browser walkthrough**
+
+With `npm run dev` running:
+1. Log in (or use `AUTH_ENABLED=false`), create a fresh calendar.
+2. Open its permissions panel, turn on "Geteilte Dienste".
+3. Create a shift with two time ranges (`06:00–10:00`, `15:00–21:00`); confirm it saves and displays both ranges in the month grid and in the day-detail sheet.
+4. Create a preset with two ranges, stamp it onto a day, confirm the resulting shift has both ranges.
+5. Edit the preset's ranges; confirm the previously stamped shift's ranges update too (the cascade from Task 5).
+6. Export that month as PDF and as ICS; open both and confirm the split shift shows both ranges (PDF: one joined line; ICS: two separate events).
+7. Turn "Geteilte Dienste" back off; confirm the "Add time range" button disappears from the create-shift sheet, per the spec's "hidden everywhere, not deleted" rule for the calendar-level toggle.
+8. Create a normal (non-split) shift on an unrelated, already-existing calendar and confirm nothing about its appearance or behavior changed.
+
+- [ ] **Step 5: Push the branch and open the PR**
+
+```bash
+git push -u origin feat/split-shifts
+gh pr create --title "feat: support split shifts with multiple time ranges" --body "$(cat <<'EOF'
+## Summary
+- Shifts and presets can now hold multiple, non-contiguous time ranges on the same day (e.g. 06:00–10:00 and 15:00–21:00), gated per calendar behind a new owner/admin toggle (`splitShiftsEnabled`), off by default.
+- Additional ranges live in two new child tables (`shiftTimeSegments`, `presetTimeSegments`); the primary range stays on the existing `startTime`/`endTime` columns for full backward compatibility.
+- PDF export joins all ranges into one line; ICS export emits one VEVENT per range.
+
+Closes #191.
+
+## Test plan
+- [ ] `npm test` passes (lint, build, i18n)
+- [ ] Create/edit a split shift and a split preset in the browser; verify validation (overlap, chronological order) and the calendar-level toggle
+- [ ] Verify a preset's segment edits cascade to shifts already created from it
+- [ ] Verify PDF and ICS exports for a split shift
+- [ ] Verify existing (non-split) shifts/calendars are visually and functionally unchanged
+EOF
+)"
+```
+
+Expected: PR created; report the URL back.
diff --git a/docs/superpowers/specs/2026-09-15-split-shifts-design.md b/docs/superpowers/specs/2026-09-15-split-shifts-design.md
new file mode 100644
index 0000000..afd7144
--- /dev/null
+++ b/docs/superpowers/specs/2026-09-15-split-shifts-design.md
@@ -0,0 +1,109 @@
+# Split Shifts — Design
+
+Source: [GitHub issue #191](https://github.com/panteLx/BetterShift/issues/191). Common in German elder care ("Altenpflege"): a single duty made of two or more non-contiguous time ranges on the same day, e.g. `06:00–10:00` and `15:00–21:00`.
+
+## Goals
+
+- A shift (and a preset) can have one or more time ranges on the same calendar day, not just one.
+- Backward compatible: the vast majority of shifts stay single-range and every existing code path that reads `shift.startTime`/`shift.endTime` keeps working unmodified.
+- Opt-in per calendar, owner/admin controlled, off by default.
+
+## Non-goals
+
+- A time range spanning midnight *within* a split shift (multi-range wraparound). A single-range shift crossing midnight is already supported today and is untouched.
+- Per-range signups. A signup still applies to the whole shift.
+- A generic multi-range concept for anything other than shifts/presets (e.g. notes, external events).
+
+## Data model
+
+Two new child tables, following the existing `shiftSignups` one-to-many-on-parent-id pattern rather than a JSON column (no JSON-blob precedent exists for arbitrary per-row data in this schema; the closest JSON columns, `calendars.viewSettings` and `calendarPermissionBundles.capabilities`, are fixed-shape and code-typed, not applicable here):
+
+```ts
+export const shiftTimeSegments = sqliteTable(
+ "shift_time_segments",
+ {
+ id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
+ shiftId: text("shift_id").notNull().references(() => shifts.id, { onDelete: "cascade" }),
+ startTime: text("start_time").notNull(),
+ endTime: text("end_time").notNull(),
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),
+ },
+ (table) => [index("shift_time_segments_shiftId_idx").on(table.shiftId)]
+);
+
+export const presetTimeSegments = sqliteTable(
+ "preset_time_segments",
+ {
+ id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
+ presetId: text("preset_id").notNull().references(() => shiftPresets.id, { onDelete: "cascade" }),
+ startTime: text("start_time").notNull(),
+ endTime: text("end_time").notNull(),
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),
+ },
+ (table) => [index("preset_time_segments_presetId_idx").on(table.presetId)]
+);
+```
+
+- These tables hold **only the additional ranges** (segment 2, 3, …). The first/primary range stays on `shifts.startTime`/`endTime` and `shiftPresets.startTime`/`endTime` exactly as today.
+- No `order` column: write-time validation enforces chronological order, read-time code sorts by `startTime` if it ever needs to (in practice segments are already stored in order).
+- Relations added to `shiftsRelations`/`shiftPresetsRelations` (`many(shiftTimeSegments)` / `many(presetTimeSegments)`).
+
+New column:
+
+```ts
+// calendars table
+splitShiftsEnabled: integer("split_shifts_enabled", { mode: "boolean" }).notNull().default(false),
+```
+
+Modeled exactly after `signupsEnabled` ("master switch... Owner/admin only"): a calendar-wide feature flag, not a permission-bundle capability. Off hides the extra segments everywhere (same behavior contract as `signupsEnabled`), not just in the create form — if a calendar's owner turns it off after split shifts already exist, those shifts fall back to showing/using only their primary range until the owner turns it back on. Data in `shiftTimeSegments` is not deleted when the flag is turned off.
+
+No data migration needed beyond the schema migration itself — existing shifts/presets are untouched (no rows in the new tables, flag defaults `false`).
+
+## Validation
+
+Applied both client-side (immediate form feedback) and server-side (routes have no centralized Zod layer today; validation stays inline like the rest of `app/api/shifts/**` and `app/api/presets/**`):
+
+- All ranges (primary + segments) must be non-overlapping and in chronological order, compared as same-day minute-of-day values (no midnight wraparound across ranges — see Non-goals).
+- The server additionally rejects a write with more than one range when `calendars.splitShiftsEnabled` is `false` for the target calendar — the flag is enforced, not just hidden in the UI.
+
+## API contract
+
+Request and response bodies for `/api/shifts`, `/api/shifts/[id]`, `/api/presets`, `/api/presets/[id]` keep `startTime`/`endTime` exactly as they are today (the primary range) and gain one new, optional, additive field: `segments: { startTime: string; endTime: string }[]` — the *additional* ranges only (empty/omitted for a normal shift). This is deliberately not a unified `timeRanges` array that replaces `startTime`/`endTime`: keeping the primary pair as its own top-level fields means every existing reader (grid, exports, sync, stats) needs zero changes to keep working, and the shift/preset form only needs new markup for the extra rows — the existing start/end inputs are untouched.
+
+A shared helper `toTimeRanges({ startTime, endTime, segments })` reassembles the full ordered list `[primary, ...segments]` wherever validation, duration, or display code needs to look at all ranges together. This logic is split across two new files by where it can run:
+
+- `lib/time-ranges.ts` — pure, client-safe (no `db` import, so it can be used from form components): `TimeRange` type, `toTimeRanges()`, `validateTimeRanges()` (returns an error code or `null`), `sumRangeDurations()`.
+- `lib/shift-time-ranges.ts` — server-only (imports `db`): `replaceShiftSegments()`, `replacePresetSegments()` (delete-then-insert into the child table, same transaction as the parent row write), `withShiftSegments()`, `withPresetSegments()` (attach a `segments` array to a list of rows, following the existing `withSignups()` pattern in `lib/shift-signups.ts`).
+
+This split matters: `lib/shift-display.ts` and the shift/preset form components are used client-side, and importing anything that pulls in `better-sqlite3` there would break the client bundle. On write, the route validates the full range list via `toTimeRanges()` + `validateTimeRanges()`, rejects if `segments.length > 0` while the calendar's `splitShiftsEnabled` is `false`, and persists via `replaceShiftSegments()`/`replacePresetSegments()`.
+
+`PATCH /api/presets/[id]` already cascades `title`/`startTime`/`endTime`/`color`/`notes`/`isAllDay` from the preset onto every shift created from it (unconditional overwrite, not just on first creation). This must be extended to also cascade `segments` the same way — otherwise a preset's split-shift edit would silently stop propagating to its already-created shifts, unlike every other field.
+
+## Frontend
+
+- `hooks/useShiftForm.ts` / `hooks/usePresets.ts`'s form data hold `startTime`/`endTime` exactly as today plus a new `segments: TimeRange[]` array (additional ranges only, mirroring the API contract). Preset→shift copy logic (`applyPreset`) copies `preset.segments` into the new shift's `segments`.
+- `components/shift-form-fields.tsx` / `components/preset-form.tsx`: the existing start/end row is untouched; additional rows are rendered by mapping over `segments`, each with its own start/end pickers and a remove ("×") action. An "add range" action appears only when `calendar.splitShiftsEnabled`.
+- `hooks/useDirtyState` comparison (the `snapshot()` function in `shift-sheet.tsx`, `samePresetForm()` for presets) is extended to include `segments` in the compared value.
+- `lib/shift-display.ts`:
+ - `formatTimeRange()` extended to accept an optional `segments` field and join multiple ranges via `toTimeRanges()` (`"06:00–10:00, 15:00–21:00"`). Consumed as-is by `day-detail.tsx` and `shift-sheet.tsx` — both already funnel through this one shared, responsive component for desktop and phone, so no separate mobile treatment is needed (confirmed by inspection: the phone month-grid chips display no time at all today, only the shift title, so they are unaffected either way).
+ - `getShiftMinutes()` uses `toTimeRanges()` + `sumRangeDurations()` (from `lib/time-ranges.ts`) instead of a single `calculateShiftDuration()` call. `app/api/shifts/stats/route.ts` does its own manual `.select()` (not the shared helper), so it separately fetches each result shift's segments and does the same `toTimeRanges()` + `sumRangeDurations()` call in place of its current single-pair `calculateShiftDuration()`.
+- `components/month-grid.tsx` desktop chip: shows the combined `formatTimeRange()` label instead of just `startTime`. Phone chip: unchanged (no time shown there today).
+- `sortShifts` (`lib/shift-display.ts`) keeps sorting by `startTime` — validation guarantees that's the earliest range, so no change in meaning.
+
+## Exports & sync
+
+- **PDF** (`app/api/export/pdf/route.ts`): use the same joined range string instead of the current single `startTime`–`endTime` interpolation.
+- **ICS** (`app/api/export/ics/route.ts`): a split shift becomes multiple VEVENTs — one per range, same `SUMMARY`/`DESCRIPTION`, `UID` of `"<shiftId>"` for the primary range and `"<shiftId>-seg-<n>"` for each additional one, each with its own `DTSTART`/`DTEND`.
+- **External sync** (`lib/external-calendar-utils.ts`, the sync route): unaffected. Incoming events always produce single-range shifts; `shiftTimeSegments` is never populated by sync, so the fingerprint/`needsUpdate` diff logic needs no changes.
+
+## Calendar settings UI
+
+- New toggle in `components/calendar-permissions-panel.tsx`, next to the existing `signupsEnabled` toggle, backed by `splitShiftsEnabled` on the same `PATCH /api/calendars/[id]` route, gated by the same `manageCalendarSettings` capability check already used for that route.
+
+## i18n
+
+New keys (added to `messages/de.json` first, then mirrored to `en`/`es`/`fr`/`it`/`cs` per the project's i18n workflow): add/remove time range labels, the calendar-settings toggle label + description, and the two validation error messages (overlap, chronological order).
+
+## Testing
+
+No unit-test framework in this repo — verification is the standard `npm test` pipeline (lint + build + i18n) plus manual exercising of the feature in the running app (create/edit a split shift and a split preset, toggle the calendar setting off and confirm segments disappear, check PDF and ICS export output, confirm a non-split calendar and non-split shifts are pixel-for-pixel unaffected).
diff --git a/drizzle/0026_marvelous_firebird.sql b/drizzle/0026_marvelous_firebird.sql
new file mode 100644
index 0000000..928a8b2
--- /dev/null
+++ b/drizzle/0026_marvelous_firebird.sql
@@ -0,0 +1,21 @@
+CREATE TABLE `preset_time_segments` (
+ `id` text PRIMARY KEY NOT NULL,
+ `preset_id` text NOT NULL,
+ `start_time` text NOT NULL,
+ `end_time` text NOT NULL,
+ `created_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ FOREIGN KEY (`preset_id`) REFERENCES `shift_presets`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE INDEX `preset_time_segments_presetId_idx` ON `preset_time_segments` (`preset_id`);--> statement-breakpoint
+CREATE TABLE `shift_time_segments` (
+ `id` text PRIMARY KEY NOT NULL,
+ `shift_id` text NOT NULL,
+ `start_time` text NOT NULL,
+ `end_time` text NOT NULL,
+ `created_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ FOREIGN KEY (`shift_id`) REFERENCES `shifts`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE INDEX `shift_time_segments_shiftId_idx` ON `shift_time_segments` (`shift_id`);--> statement-breakpoint
+ALTER TABLE `calendars` ADD `split_shifts_enabled` integer DEFAULT false NOT NULL;
\ No newline at end of file
diff --git a/drizzle/meta/0026_snapshot.json b/drizzle/meta/0026_snapshot.json
new file mode 100644
index 0000000..95c6def
--- /dev/null
+++ b/drizzle/meta/0026_snapshot.json
@@ -0,0 +1,2208 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "7f7a7e35-960b-49fd-9301-f136263622a0",
+ "prevId": "5d6f9d6d-8737-4803-a72b-9db3701bee45",
+ "tables": {
+ "account": {
+ "name": "account",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "account_userId_idx": {
+ "name": "account_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "audit_logs": {
+ "name": "audit_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "resource_type": {
+ "name": "resource_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "severity": {
+ "name": "severity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'info'"
+ },
+ "is_user_visible": {
+ "name": "is_user_visible",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "audit_logs_userId_timestamp_idx": {
+ "name": "audit_logs_userId_timestamp_idx",
+ "columns": [
+ "user_id",
+ "timestamp"
+ ],
+ "isUnique": false
+ },
+ "audit_logs_action_timestamp_idx": {
+ "name": "audit_logs_action_timestamp_idx",
+ "columns": [
+ "action",
+ "timestamp"
+ ],
+ "isUnique": false
+ },
+ "audit_logs_userVisible_userId_timestamp_idx": {
+ "name": "audit_logs_userVisible_userId_timestamp_idx",
+ "columns": [
+ "is_user_visible",
+ "user_id",
+ "timestamp"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "audit_logs_user_id_user_id_fk": {
+ "name": "audit_logs_user_id_user_id_fk",
+ "tableFrom": "audit_logs",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_access_tokens": {
+ "name": "calendar_access_tokens",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bundle_id": {
+ "name": "bundle_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "usage_count": {
+ "name": "usage_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ }
+ },
+ "indexes": {
+ "calendar_access_tokens_token_unique": {
+ "name": "calendar_access_tokens_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ },
+ "calendar_access_tokens_token_idx": {
+ "name": "calendar_access_tokens_token_idx",
+ "columns": [
+ "token"
+ ],
+ "isUnique": false
+ },
+ "calendar_access_tokens_calendarId_isActive_idx": {
+ "name": "calendar_access_tokens_calendarId_isActive_idx",
+ "columns": [
+ "calendar_id",
+ "is_active"
+ ],
+ "isUnique": false
+ },
+ "calendar_access_tokens_createdBy_idx": {
+ "name": "calendar_access_tokens_createdBy_idx",
+ "columns": [
+ "created_by"
+ ],
+ "isUnique": false
+ },
+ "calendar_access_tokens_bundleId_idx": {
+ "name": "calendar_access_tokens_bundleId_idx",
+ "columns": [
+ "bundle_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendar_access_tokens_calendar_id_calendars_id_fk": {
+ "name": "calendar_access_tokens_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_access_tokens",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_access_tokens_bundle_id_calendar_permission_bundles_id_fk": {
+ "name": "calendar_access_tokens_bundle_id_calendar_permission_bundles_id_fk",
+ "tableFrom": "calendar_access_tokens",
+ "tableTo": "calendar_permission_bundles",
+ "columnsFrom": [
+ "bundle_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ },
+ "calendar_access_tokens_created_by_user_id_fk": {
+ "name": "calendar_access_tokens_created_by_user_id_fk",
+ "tableFrom": "calendar_access_tokens",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_notes": {
+ "name": "calendar_notes",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'note'"
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recurring_pattern": {
+ "name": "recurring_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'none'"
+ },
+ "recurring_interval": {
+ "name": "recurring_interval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "calendar_notes_calendar_id_calendars_id_fk": {
+ "name": "calendar_notes_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_notes",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_notes_created_by_user_id_fk": {
+ "name": "calendar_notes_created_by_user_id_fk",
+ "tableFrom": "calendar_notes",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_permission_bundles": {
+ "name": "calendar_permission_bundles",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "seed_key": {
+ "name": "seed_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "capabilities": {
+ "name": "capabilities",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "calendar_permission_bundles_calendarId_idx": {
+ "name": "calendar_permission_bundles_calendarId_idx",
+ "columns": [
+ "calendar_id"
+ ],
+ "isUnique": false
+ },
+ "calendar_permission_bundles_calendarId_seedKey_idx": {
+ "name": "calendar_permission_bundles_calendarId_seedKey_idx",
+ "columns": [
+ "calendar_id",
+ "seed_key"
+ ],
+ "isUnique": true,
+ "where": "\"calendar_permission_bundles\".\"seed_key\" is not null"
+ }
+ },
+ "foreignKeys": {
+ "calendar_permission_bundles_calendar_id_calendars_id_fk": {
+ "name": "calendar_permission_bundles_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_permission_bundles",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_shares": {
+ "name": "calendar_shares",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bundle_id": {
+ "name": "bundle_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "shared_by": {
+ "name": "shared_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "calendar_shares_calendarId_idx": {
+ "name": "calendar_shares_calendarId_idx",
+ "columns": [
+ "calendar_id"
+ ],
+ "isUnique": false
+ },
+ "calendar_shares_userId_idx": {
+ "name": "calendar_shares_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ },
+ "calendar_shares_bundleId_idx": {
+ "name": "calendar_shares_bundleId_idx",
+ "columns": [
+ "bundle_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendar_shares_calendar_id_calendars_id_fk": {
+ "name": "calendar_shares_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_shares_user_id_user_id_fk": {
+ "name": "calendar_shares_user_id_user_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_shares_bundle_id_calendar_permission_bundles_id_fk": {
+ "name": "calendar_shares_bundle_id_calendar_permission_bundles_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "calendar_permission_bundles",
+ "columnsFrom": [
+ "bundle_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ },
+ "calendar_shares_shared_by_user_id_fk": {
+ "name": "calendar_shares_shared_by_user_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "user",
+ "columnsFrom": [
+ "shared_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendars": {
+ "name": "calendars",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "guest_bundle_id": {
+ "name": "guest_bundle_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "signups_enabled": {
+ "name": "signups_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "split_shifts_enabled": {
+ "name": "split_shifts_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "view_settings": {
+ "name": "view_settings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "calendars_ownerId_idx": {
+ "name": "calendars_ownerId_idx",
+ "columns": [
+ "owner_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendars_owner_id_user_id_fk": {
+ "name": "calendars_owner_id_user_id_fk",
+ "tableFrom": "calendars",
+ "tableTo": "user",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "external_syncs": {
+ "name": "external_syncs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sync_type": {
+ "name": "sync_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'icloud'"
+ },
+ "calendar_url": {
+ "name": "calendar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "display_mode": {
+ "name": "display_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "is_hidden": {
+ "name": "is_hidden",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "hide_from_stats": {
+ "name": "hide_from_stats",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "auto_sync_interval": {
+ "name": "auto_sync_interval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "is_one_time_import": {
+ "name": "is_one_time_import",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "last_synced_at": {
+ "name": "last_synced_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "external_syncs_calendar_id_calendars_id_fk": {
+ "name": "external_syncs_calendar_id_calendars_id_fk",
+ "tableFrom": "external_syncs",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "preset_time_segments": {
+ "name": "preset_time_segments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "preset_id": {
+ "name": "preset_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "preset_time_segments_presetId_idx": {
+ "name": "preset_time_segments_presetId_idx",
+ "columns": [
+ "preset_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "preset_time_segments_preset_id_shift_presets_id_fk": {
+ "name": "preset_time_segments_preset_id_shift_presets_id_fk",
+ "tableFrom": "preset_time_segments",
+ "tableTo": "shift_presets",
+ "columnsFrom": [
+ "preset_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session": {
+ "name": "session",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "impersonated_by": {
+ "name": "impersonated_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ },
+ "session_userId_idx": {
+ "name": "session_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shift_presets": {
+ "name": "shift_presets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "group_name": {
+ "name": "group_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_secondary": {
+ "name": "is_secondary",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "is_all_day": {
+ "name": "is_all_day",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "hide_from_stats": {
+ "name": "hide_from_stats",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "default_signup_capacity": {
+ "name": "default_signup_capacity",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "shift_presets_calendar_id_calendars_id_fk": {
+ "name": "shift_presets_calendar_id_calendars_id_fk",
+ "tableFrom": "shift_presets",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shift_presets_created_by_user_id_fk": {
+ "name": "shift_presets_created_by_user_id_fk",
+ "tableFrom": "shift_presets",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shift_signups": {
+ "name": "shift_signups",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "shift_id": {
+ "name": "shift_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "signed_up_by": {
+ "name": "signed_up_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "shift_signups_shiftId_idx": {
+ "name": "shift_signups_shiftId_idx",
+ "columns": [
+ "shift_id"
+ ],
+ "isUnique": false
+ },
+ "shift_signups_userId_idx": {
+ "name": "shift_signups_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ },
+ "shift_signups_shiftId_userId_idx": {
+ "name": "shift_signups_shiftId_userId_idx",
+ "columns": [
+ "shift_id",
+ "user_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "shift_signups_shift_id_shifts_id_fk": {
+ "name": "shift_signups_shift_id_shifts_id_fk",
+ "tableFrom": "shift_signups",
+ "tableTo": "shifts",
+ "columnsFrom": [
+ "shift_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shift_signups_user_id_user_id_fk": {
+ "name": "shift_signups_user_id_user_id_fk",
+ "tableFrom": "shift_signups",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shift_signups_signed_up_by_user_id_fk": {
+ "name": "shift_signups_signed_up_by_user_id_fk",
+ "tableFrom": "shift_signups",
+ "tableTo": "user",
+ "columnsFrom": [
+ "signed_up_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shift_time_segments": {
+ "name": "shift_time_segments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "shift_id": {
+ "name": "shift_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "shift_time_segments_shiftId_idx": {
+ "name": "shift_time_segments_shiftId_idx",
+ "columns": [
+ "shift_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "shift_time_segments_shift_id_shifts_id_fk": {
+ "name": "shift_time_segments_shift_id_shifts_id_fk",
+ "tableFrom": "shift_time_segments",
+ "tableTo": "shifts",
+ "columnsFrom": [
+ "shift_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shifts": {
+ "name": "shifts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "preset_id": {
+ "name": "preset_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_all_day": {
+ "name": "is_all_day",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "is_secondary": {
+ "name": "is_secondary",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "signup_capacity": {
+ "name": "signup_capacity",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "external_event_id": {
+ "name": "external_event_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "external_sync_id": {
+ "name": "external_sync_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "synced_from_external": {
+ "name": "synced_from_external",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "shifts_calendar_id_calendars_id_fk": {
+ "name": "shifts_calendar_id_calendars_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shifts_preset_id_shift_presets_id_fk": {
+ "name": "shifts_preset_id_shift_presets_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "shift_presets",
+ "columnsFrom": [
+ "preset_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "shifts_external_sync_id_external_syncs_id_fk": {
+ "name": "shifts_external_sync_id_external_syncs_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "external_syncs",
+ "columnsFrom": [
+ "external_sync_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shifts_created_by_user_id_fk": {
+ "name": "shifts_created_by_user_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sync_logs": {
+ "name": "sync_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_sync_id": {
+ "name": "external_sync_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_sync_name": {
+ "name": "external_sync_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shifts_created": {
+ "name": "shifts_created",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "shifts_updated": {
+ "name": "shifts_updated",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "shifts_deleted": {
+ "name": "shifts_deleted",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "sync_type": {
+ "name": "sync_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'auto'"
+ },
+ "is_read": {
+ "name": "is_read",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "synced_at": {
+ "name": "synced_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sync_logs_calendar_id_calendars_id_fk": {
+ "name": "sync_logs_calendar_id_calendars_id_fk",
+ "tableFrom": "sync_logs",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sync_logs_external_sync_id_external_syncs_id_fk": {
+ "name": "sync_logs_external_sync_id_external_syncs_id_fk",
+ "tableFrom": "sync_logs",
+ "tableTo": "external_syncs",
+ "columnsFrom": [
+ "external_sync_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "system_settings": {
+ "name": "system_settings",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'default'"
+ },
+ "update_check_enabled": {
+ "name": "update_check_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "update_banner_visibility": {
+ "name": "update_banner_visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'all'"
+ },
+ "allow_guest_access": {
+ "name": "allow_guest_access",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user": {
+ "name": "user",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "banned": {
+ "name": "banned",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "ban_reason": {
+ "name": "ban_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ban_expires": {
+ "name": "ban_expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "must_change_password": {
+ "name": "must_change_password",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ }
+ },
+ "indexes": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_calendar_subscriptions": {
+ "name": "user_calendar_subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'subscribed'"
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'guest'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "user_calendar_subscriptions_userId_idx": {
+ "name": "user_calendar_subscriptions_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ },
+ "user_calendar_subscriptions_calendarId_idx": {
+ "name": "user_calendar_subscriptions_calendarId_idx",
+ "columns": [
+ "calendar_id"
+ ],
+ "isUnique": false
+ },
+ "user_calendar_subscriptions_status_idx": {
+ "name": "user_calendar_subscriptions_status_idx",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "user_calendar_subscriptions_user_id_user_id_fk": {
+ "name": "user_calendar_subscriptions_user_id_user_id_fk",
+ "tableFrom": "user_calendar_subscriptions",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_calendar_subscriptions_calendar_id_calendars_id_fk": {
+ "name": "user_calendar_subscriptions_calendar_id_calendars_id_fk",
+ "tableFrom": "user_calendar_subscriptions",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_preferences": {
+ "name": "user_preferences",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "view_settings": {
+ "name": "view_settings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_preferences_user_id_user_id_fk": {
+ "name": "user_preferences_user_id_user_id_fk",
+ "tableFrom": "user_preferences",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "verification": {
+ "name": "verification",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index 7ec1ff0..983ee41 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -183,6 +183,13 @@
"when": 1789388420861,
"tag": "0025_nappy_swarm",
"breakpoints": true
+ },
+ {
+ "idx": 26,
+ "version": "6",
+ "when": 1789470189574,
+ "tag": "0026_marvelous_firebird",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/hooks/useCalendars.ts b/hooks/useCalendars.ts
index 3b77b72..e98abd8 100644
--- a/hooks/useCalendars.ts
+++ b/hooks/useCalendars.ts
@@ -25,6 +25,7 @@ export interface CalendarUpdateInput {
guestBundleId?: string | null;
viewSettings?: CalendarViewSettings | null;
signupsEnabled?: boolean;
+ splitShiftsEnabled?: boolean;
}
// API functions
diff --git a/hooks/useCompareData.ts b/hooks/useCompareData.ts
index 9105e40..198bc35 100644
--- a/hooks/useCompareData.ts
+++ b/hooks/useCompareData.ts
@@ -12,6 +12,10 @@ import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { useCalendarAccessFilter } from "@/hooks/useCalendars";
import { LIVE_REFETCH_INTERVAL } from "@/lib/query-client";
+import type { TimeRange } from "@/lib/time-ranges";
+
+// The API attaches `segments` as a joined field; ShiftPreset itself doesn't declare it.
+export type PresetWithSegments = ShiftPreset & { segments?: TimeRange[] };
// API functions
async function fetchShiftsApi(
@@ -38,7 +42,7 @@ async function fetchExternalSyncsApi(
return await response.json();
}
-async function fetchPresetsApi(calendarId: string): Promise<ShiftPreset[]> {
+async function fetchPresetsApi(calendarId: string): Promise<PresetWithSegments[]> {
const response = await fetch(`/api/presets?calendarId=${calendarId}`);
if (!response.ok) return [];
return await response.json();
@@ -162,7 +166,7 @@ export function useCompareData({
}, [calendarIds, externalSyncsDataArray]);
const presetsMap = useMemo(() => {
- const map = new Map<string, ShiftPreset[]>();
+ const map = new Map<string, PresetWithSegments[]>();
calendarIds.forEach((id, index) => {
map.set(id, presetsDataArray[index] || []);
});
diff --git a/hooks/useCompareMode.ts b/hooks/useCompareMode.ts
index 63c7243..a701ff6 100644
--- a/hooks/useCompareMode.ts
+++ b/hooks/useCompareMode.ts
@@ -181,6 +181,7 @@ export function useCompareMode({
notes: preset.notes || "",
presetId: preset.id,
isAllDay: preset.isAllDay || false,
+ segments: preset.segments ?? [],
},
});
}
diff --git a/hooks/usePresets.ts b/hooks/usePresets.ts
index c28daf1..da44736 100644
--- a/hooks/usePresets.ts
+++ b/hooks/usePresets.ts
@@ -6,6 +6,7 @@ import { queryKeys } from "@/lib/query-keys";
import { ApiError } from "@/lib/api-error";
import { generateTempId } from "@/lib/utils";
import { useIsCalendarAccessible } from "@/hooks/useCalendars";
+import type { TimeRange } from "@/lib/time-ranges";
// Form data interface
export interface PresetFormData {
@@ -19,6 +20,7 @@ export interface PresetFormData {
isAllDay: boolean;
hideFromStats: boolean;
defaultSignupCapacity?: number | null;
+ segments: TimeRange[];
}
// API functions
@@ -102,7 +104,7 @@ async function reorderPresetsApi(
function createOptimisticPreset(
calendarId: string,
formData: PresetFormData
-): ShiftPreset {
+): ShiftPreset & { segments: TimeRange[] } {
return {
id: `temp-${generateTempId()}`,
calendarId,
@@ -116,6 +118,7 @@ function createOptimisticPreset(
isAllDay: formData.isAllDay,
hideFromStats: formData.hideFromStats,
defaultSignupCapacity: formData.defaultSignupCapacity ?? null,
+ segments: formData.segments,
order: 999, // Will be corrected by server
createdBy: null,
createdAt: new Date(),
diff --git a/hooks/useShiftActions.ts b/hooks/useShiftActions.ts
index dc92b57..4de75af 100644
--- a/hooks/useShiftActions.ts
+++ b/hooks/useShiftActions.ts
@@ -4,10 +4,11 @@ import { ShiftFormData } from "@/components/shift-sheet";
import { ShiftWithCalendar } from "@/lib/types";
import { ShiftPreset } from "@/lib/db/schema";
import { formatDateToLocal, toLocalDate } from "@/lib/date-utils";
+import type { TimeRange } from "@/lib/time-ranges";
interface UseShiftActionsProps {
shifts: ShiftWithCalendar[];
- presets: ShiftPreset[];
+ presets: (ShiftPreset & { segments?: TimeRange[] })[];
createShift: (data: ShiftFormData) => Promise<ShiftWithCalendar>;
deleteShift: (id: string) => Promise<void>;
onStatsRefresh?: () => void;
@@ -91,6 +92,7 @@ export function useShiftActions({
notes: preset.notes || "",
presetId: preset.id,
isAllDay: preset.isAllDay || false,
+ segments: preset.segments ?? [],
};
try {
diff --git a/hooks/useShiftForm.ts b/hooks/useShiftForm.ts
index 77c6165..aa20b8d 100644
--- a/hooks/useShiftForm.ts
+++ b/hooks/useShiftForm.ts
@@ -5,6 +5,7 @@ import { ShiftWithCalendar } from "@/lib/types";
import { formatDateToLocal } from "@/lib/date-utils";
import { usePresets } from "@/hooks/usePresets";
import { DEFAULT_COLOR } from "@/lib/constants";
+import type { TimeRange } from "@/lib/time-ranges";
interface UseShiftFormOptions {
open: boolean;
@@ -33,6 +34,7 @@ export function useShiftForm({
color: shift?.color || DEFAULT_COLOR,
isAllDay: false,
signupCapacity: shift?.signupCapacity ?? null,
+ segments: shift?.segments ?? [],
});
const { presets, createPreset } = usePresets(calendarId);
@@ -53,12 +55,13 @@ export function useShiftForm({
isAllDay: shiftData.isAllDay || false,
isSecondary: false,
hideFromStats: false,
+ segments: shiftData.segments ?? [],
});
return success;
};
- const applyPreset = (preset: ShiftPreset) => {
+ const applyPreset = (preset: ShiftPreset & { segments?: TimeRange[] }) => {
setFormData({
...formData,
startTime: preset.startTime,
@@ -68,6 +71,7 @@ export function useShiftForm({
color: preset.color,
isAllDay: preset.isAllDay || false,
signupCapacity: preset.defaultSignupCapacity ?? null,
+ segments: preset.segments ?? [],
});
};
@@ -82,6 +86,7 @@ export function useShiftForm({
color: DEFAULT_COLOR,
isAllDay: false,
signupCapacity: null,
+ segments: [],
});
};
@@ -97,6 +102,7 @@ export function useShiftForm({
color: DEFAULT_COLOR,
isAllDay: false,
signupCapacity: null,
+ segments: [],
});
setPresetName("");
setSaveAsPreset(false);
@@ -125,6 +131,7 @@ export function useShiftForm({
color: shift?.color || DEFAULT_COLOR,
isAllDay: shift?.isAllDay || false,
signupCapacity: shift?.signupCapacity ?? null,
+ segments: shift?.segments ?? [],
};
// Compare form data fields directly
@@ -136,7 +143,9 @@ export function useShiftForm({
formDataRef.current.notes !== newFormData.notes ||
formDataRef.current.color !== newFormData.color ||
formDataRef.current.isAllDay !== newFormData.isAllDay ||
- formDataRef.current.signupCapacity !== newFormData.signupCapacity;
+ formDataRef.current.signupCapacity !== newFormData.signupCapacity ||
+ JSON.stringify(formDataRef.current.segments ?? []) !==
+ JSON.stringify(newFormData.segments ?? []);
if (needsUpdate) {
setFormData(newFormData);
diff --git a/hooks/useShifts.ts b/hooks/useShifts.ts
index 3546369..61b43c9 100644
--- a/hooks/useShifts.ts
+++ b/hooks/useShifts.ts
@@ -150,6 +150,7 @@ export function useShifts(calendarId: string | undefined) {
date: parseLocalDate(formData.date),
startTime: formData.startTime,
endTime: formData.endTime,
+ segments: formData.segments ?? [],
title: formData.title,
color: formData.color || "#3b82f6",
notes: formData.notes || null,
@@ -258,6 +259,7 @@ export function useShifts(calendarId: string | undefined) {
date: parseLocalDate(formData.date),
startTime: formData.startTime,
endTime: formData.endTime,
+ segments: formData.segments ?? [],
title: formData.title,
color: formData.color || s.color,
notes: formData.notes || null,
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 54214a7..3da6ca1 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -135,6 +135,12 @@ export const calendars = sqliteTable(
signupsEnabled: integer("signups_enabled", { mode: "boolean" })
.notNull()
.default(true),
+ // Master switch for split shifts (multiple time ranges per shift/preset)
+ // on this calendar. Owner/admin only; off hides extra ranges everywhere,
+ // same contract as signupsEnabled above.
+ splitShiftsEnabled: integer("split_shifts_enabled", { mode: "boolean" })
+ .notNull()
+ .default(false),
// null = no own view; every user sees their personal view
viewSettings: text("view_settings", {
mode: "json",
@@ -393,6 +399,42 @@ export const shiftPresets = sqliteTable("shift_presets", {
.default(sql`CURRENT_TIMESTAMP`),
});
+export const shiftTimeSegments = sqliteTable(
+ "shift_time_segments",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ shiftId: text("shift_id")
+ .notNull()
+ .references(() => shifts.id, { onDelete: "cascade" }),
+ startTime: text("start_time").notNull(),
+ endTime: text("end_time").notNull(),
+ createdAt: integer("created_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ },
+ (table) => [index("shift_time_segments_shiftId_idx").on(table.shiftId)]
+);
+
+export const presetTimeSegments = sqliteTable(
+ "preset_time_segments",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ presetId: text("preset_id")
+ .notNull()
+ .references(() => shiftPresets.id, { onDelete: "cascade" }),
+ startTime: text("start_time").notNull(),
+ endTime: text("end_time").notNull(),
+ createdAt: integer("created_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ },
+ (table) => [index("preset_time_segments_presetId_idx").on(table.presetId)]
+);
+
export const calendarNotes = sqliteTable("calendar_notes", {
id: text("id")
.primaryKey()
@@ -565,6 +607,10 @@ export type Shift = typeof shifts.$inferSelect;
export type NewShift = typeof shifts.$inferInsert;
export type ShiftPreset = typeof shiftPresets.$inferSelect;
export type NewShiftPreset = typeof shiftPresets.$inferInsert;
+export type ShiftTimeSegment = typeof shiftTimeSegments.$inferSelect;
+export type NewShiftTimeSegment = typeof shiftTimeSegments.$inferInsert;
+export type PresetTimeSegment = typeof presetTimeSegments.$inferSelect;
+export type NewPresetTimeSegment = typeof presetTimeSegments.$inferInsert;
export type CalendarNote = typeof calendarNotes.$inferSelect;
export type NewCalendarNote = typeof calendarNotes.$inferInsert;
export type SyncLog = typeof syncLogs.$inferSelect;
@@ -656,23 +702,45 @@ export const shiftsRelations = relations(shifts, ({ one, many }) => ({
references: [shiftPresets.id],
}),
signups: many(shiftSignups),
+ segments: many(shiftTimeSegments),
creator: one(user, {
fields: [shifts.createdBy],
references: [user.id],
}),
}));
-export const shiftPresetsRelations = relations(shiftPresets, ({ one }) => ({
+export const shiftPresetsRelations = relations(shiftPresets, ({ one, many }) => ({
calendar: one(calendars, {
fields: [shiftPresets.calendarId],
references: [calendars.id],
}),
+ segments: many(presetTimeSegments),
creator: one(user, {
fields: [shiftPresets.createdBy],
references: [user.id],
}),
}));
+export const shiftTimeSegmentsRelations = relations(
+ shiftTimeSegments,
+ ({ one }) => ({
+ shift: one(shifts, {
+ fields: [shiftTimeSegments.shiftId],
+ references: [shifts.id],
+ }),
+ })
+);
+
+export const presetTimeSegmentsRelations = relations(
+ presetTimeSegments,
+ ({ one }) => ({
+ preset: one(shiftPresets, {
+ fields: [presetTimeSegments.presetId],
+ references: [shiftPresets.id],
+ }),
+ })
+);
+
export const calendarNotesRelations = relations(calendarNotes, ({ one }) => ({
calendar: one(calendars, {
fields: [calendarNotes.calendarId],
diff --git a/lib/shift-display.ts b/lib/shift-display.ts
index 7de97fb..96dd733 100644
--- a/lib/shift-display.ts
+++ b/lib/shift-display.ts
@@ -3,7 +3,7 @@ import { isSameDay } from "date-fns";
import { useTranslations } from "next-intl";
import { ShiftWithCalendar } from "@/lib/types";
import { ExternalSync, ShiftPreset } from "@/lib/db/schema";
-import { calculateShiftDuration } from "@/lib/date-utils";
+import { toTimeRanges, sumRangeDurations } from "@/lib/time-ranges";
export type ShiftSortType = "startTime" | "createdAt" | "title";
export type ShiftSortOrder = "asc" | "desc";
@@ -134,9 +134,7 @@ export function buildDayShiftLayout(
}
export function getShiftMinutes(shift: ShiftWithCalendar): number {
- return shift.isAllDay
- ? 0
- : calculateShiftDuration(shift.startTime, shift.endTime);
+ return shift.isAllDay ? 0 : sumRangeDurations(toTimeRanges(shift));
}
export function sumShiftMinutes(shifts: ShiftWithCalendar[]): number {
@@ -197,8 +195,11 @@ export function presetTime(
export function formatTimeRange(times: {
startTime: string;
endTime: string;
+ segments?: { startTime: string; endTime: string }[];
}): string {
- return `${times.startTime.slice(0, 5)} – ${times.endTime.slice(0, 5)}`;
+ return toTimeRanges(times)
+ .map((range) => `${range.startTime.slice(0, 5)} – ${range.endTime.slice(0, 5)}`)
+ .join(", ");
}
export interface PresetGroup {
diff --git a/lib/shift-time-ranges.ts b/lib/shift-time-ranges.ts
new file mode 100644
index 0000000..c78478a
--- /dev/null
+++ b/lib/shift-time-ranges.ts
@@ -0,0 +1,74 @@
+import { db } from "@/lib/db";
+import { shiftTimeSegments, presetTimeSegments } from "@/lib/db/schema";
+import { eq, inArray } from "drizzle-orm";
+import type { TimeRange } from "@/lib/time-ranges";
+
+type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
+
+/** Replaces every extra segment for one shift (delete-then-insert), inside an existing transaction. */
+export function replaceShiftSegments(tx: Tx, shiftId: string, ranges: TimeRange[]): void {
+ tx.delete(shiftTimeSegments).where(eq(shiftTimeSegments.shiftId, shiftId)).run();
+ if (ranges.length > 0) {
+ tx.insert(shiftTimeSegments)
+ .values(ranges.map((r) => ({ shiftId, startTime: r.startTime, endTime: r.endTime })))
+ .run();
+ }
+}
+
+/** Replaces every extra segment for one preset (delete-then-insert), inside an existing transaction. */
+export function replacePresetSegments(tx: Tx, presetId: string, ranges: TimeRange[]): void {
+ tx.delete(presetTimeSegments).where(eq(presetTimeSegments.presetId, presetId)).run();
+ if (ranges.length > 0) {
+ tx.insert(presetTimeSegments)
+ .values(ranges.map((r) => ({ presetId, startTime: r.startTime, endTime: r.endTime })))
+ .run();
+ }
+}
+
+/** Attaches each shift's extra segments without N+1 queries. */
+export async function withShiftSegments<T extends { id: string }>(
+ rows: T[]
+): Promise<(T & { segments: TimeRange[] })[]> {
+ if (rows.length === 0) return [];
+
+ const allSegments = await db.query.shiftTimeSegments.findMany({
+ where: inArray(
+ shiftTimeSegments.shiftId,
+ rows.map((r) => r.id)
+ ),
+ orderBy: (segments, { asc }) => [asc(segments.startTime)],
+ });
+
+ const byShiftId = new Map<string, TimeRange[]>();
+ for (const segment of allSegments) {
+ const list = byShiftId.get(segment.shiftId) ?? [];
+ list.push({ startTime: segment.startTime, endTime: segment.endTime });
+ byShiftId.set(segment.shiftId, list);
+ }
+
+ return rows.map((row) => ({ ...row, segments: byShiftId.get(row.id) ?? [] }));
+}
+
+/** Attaches each preset's extra segments without N+1 queries. */
+export async function withPresetSegments<T extends { id: string }>(
+ rows: T[]
+): Promise<(T & { segments: TimeRange[] })[]> {
+ if (rows.length === 0) return [];
+
+ const allSegments = await db.query.presetTimeSegments.findMany({
+ where: inArray(
+ presetTimeSegments.presetId,
+ rows.map((r) => r.id)
+ ),
+ orderBy: (segments, { asc }) => [asc(segments.startTime)],
+ });
+
+ const byPresetId = new Map<string, TimeRange[]>();
+ for (const segment of allSegments) {
+ const list = byPresetId.get(segment.presetId) ?? [];
+ list.push({ startTime: segment.startTime, endTime: segment.endTime });
+ byPresetId.set(segment.presetId, list);
+ }
+
+ return rows.map((row) => ({ ...row, segments: byPresetId.get(row.id) ?? [] }));
+}
diff --git a/lib/time-ranges.ts b/lib/time-ranges.ts
new file mode 100644
index 0000000..bd5aef0
--- /dev/null
+++ b/lib/time-ranges.ts
@@ -0,0 +1,100 @@
+import { calculateShiftDuration } from "@/lib/date-utils";
+
+export interface TimeRange {
+ startTime: string;
+ endTime: string;
+}
+
+export type TimeRangeError = "invalid_format" | "overnight_segment" | "overlap";
+
+const TIME_PATTERN = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/;
+
+function toMinutes(time: string): number {
+ const [hours, minutes] = time.split(":").map(Number);
+ return hours * 60 + minutes;
+}
+
+/** Reassembles the primary range plus any extra segments into one ordered-by-input list. */
+export function toTimeRanges(entity: {
+ startTime: string;
+ endTime: string;
+ segments?: TimeRange[];
+}): TimeRange[] {
+ return [
+ { startTime: entity.startTime, endTime: entity.endTime },
+ ...(entity.segments ?? []),
+ ];
+}
+
+/**
+ * Validates a full list of ranges for a shift/preset. A single range is
+ * always valid here (including one that crosses midnight — unchanged
+ * existing behavior); chronological order, non-overlap and same-day-only
+ * are enforced only once there is more than one range.
+ */
+export function validateTimeRanges(ranges: TimeRange[]): TimeRangeError | null {
+ for (const range of ranges) {
+ if (!TIME_PATTERN.test(range.startTime) || !TIME_PATTERN.test(range.endTime)) {
+ return "invalid_format";
+ }
+ }
+
+ if (ranges.length <= 1) return null;
+
+ for (const range of ranges) {
+ if (toMinutes(range.endTime) <= toMinutes(range.startTime)) {
+ return "overnight_segment";
+ }
+ }
+
+ const sorted = [...ranges].sort((a, b) => toMinutes(a.startTime) - toMinutes(b.startTime));
+ for (let i = 1; i < sorted.length; i++) {
+ if (toMinutes(sorted[i].startTime) < toMinutes(sorted[i - 1].endTime)) {
+ return "overlap";
+ }
+ }
+
+ return null;
+}
+
+/** Total duration across all ranges, in minutes. */
+export function sumRangeDurations(ranges: TimeRange[]): number {
+ return ranges.reduce(
+ (total, range) => total + calculateShiftDuration(range.startTime, range.endTime),
+ 0
+ );
+}
+
+/**
+ * Sorts a validated range list chronologically and splits it back into a
+ * primary range plus segments, so the persisted primary is always the
+ * earliest range regardless of the order ranges were submitted in.
+ */
+export function normalizeTimeRanges(
+ ranges: TimeRange[]
+): { startTime: string; endTime: string; segments: TimeRange[] } {
+ const sorted = [...ranges].sort((a, b) => toMinutes(a.startTime) - toMinutes(b.startTime));
+ const [primary, ...rest] = sorted;
+ return { startTime: primary.startTime, endTime: primary.endTime, segments: rest };
+}
+
+/**
+ * Seeds a new segment's time range starting 2h after the latest range's end,
+ * so "add time range" never collides with the form's own current ranges.
+ * Falls back to a fixed late-evening slot when there's no room left before midnight.
+ */
+export function suggestNextTimeRange(ranges: TimeRange[]): TimeRange {
+ const FALLBACK: TimeRange = { startTime: "22:00", endTime: "23:59" };
+ const END_OF_DAY = 24 * 60 - 1; // 23:59
+ const GAP_MINUTES = 120;
+
+ const toTime = (minutes: number) =>
+ `${String(Math.floor(minutes / 60)).padStart(2, "0")}:${String(minutes % 60).padStart(2, "0")}`;
+
+ const lastEnd = ranges.reduce((max, r) => Math.max(max, toMinutes(r.endTime)), 0);
+ const start = lastEnd + GAP_MINUTES;
+ if (start >= END_OF_DAY) return FALLBACK;
+
+ const end = Math.min(start + GAP_MINUTES, END_OF_DAY);
+ return { startTime: toTime(start), endTime: toTime(end) };
+}
diff --git a/lib/types.ts b/lib/types.ts
index cd37666..5997df9 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -14,6 +14,7 @@ export interface CalendarWithCount {
ownerId?: string | null;
guestBundleId?: string | null;
signupsEnabled?: boolean;
+ splitShiftsEnabled?: boolean;
/** The calendar's own view; null means everyone sees their personal view */
viewSettings?: CalendarViewSettings | null;
createdAt: Date | null;
@@ -49,6 +50,8 @@ export interface ShiftWithCalendar {
externalSyncId?: string | null;
signupCapacity?: number | null;
signups?: ShiftSignupUser[];
+ /** Additional time ranges beyond startTime/endTime (split shifts). Empty/undefined for a normal shift. */
+ segments?: { startTime: string; endTime: string }[];
// Optional (not just nullable): the create-mutation's optimistic shift in
// useShifts.ts predates the server response and has no value for it yet.
createdBy?: string | null;
diff --git a/messages/cs.json b/messages/cs.json
index b6b5e6a..4e25e82 100644
--- a/messages/cs.json
+++ b/messages/cs.json
@@ -857,7 +857,9 @@
"linkInfoGuestsOn": "Odkaz otevře kalendář přímo, bez přihlášení. V seznamu ho můžete kdykoli zrušit — pak okamžitě přestane platit.",
"linkInfoGuestsOff": "Odkaz otevře kalendář přímo. Přístup pro hosty je na této instanci vypnutý, takže se příjemci musí přihlásit. V seznamu ho můžete kdykoli zrušit — pak okamžitě přestane platit.",
"signupsEnabledLabel": "Povolit přihlašování na směny",
- "signupsEnabledDesc": "Umožní lidem přihlásit se na směny. Po vypnutí zmizí seznamy přihlášených, avatary i maximální počet osob."
+ "signupsEnabledDesc": "Umožní lidem přihlásit se na směny. Po vypnutí zmizí seznamy přihlášených, avatary i maximální počet osob.",
+ "splitShiftsEnabledLabel": "Povolit dělené směny",
+ "splitShiftsEnabledDesc": "Umožní více časových úseků v jedné směně nebo šabloně, např. 06:00–10:00 a 15:00–21:00. Po vypnutí se všude skryjí další časové úseky."
},
"shiftSheet": {
"start": "Začátek",
@@ -1088,6 +1090,15 @@
},
"addOtherHint": "Nemůžete někoho najít? Nejdřív s ním sdílejte kalendář, pak ho tu budete moct vybrat."
},
+ "timeRanges": {
+ "add": "Přidat časový úsek",
+ "remove": "Odebrat časový úsek",
+ "errors": {
+ "overlap": "Časové úseky se nesmí překrývat.",
+ "overnight_segment": "Při více časových úsecích musí každý skončit ve stejný den.",
+ "invalid_format": "Neplatný čas."
+ }
+ },
"permissionBundles": {
"bundle": "Skupina oprávnění",
"title": "Oprávnění",
@@ -1107,6 +1118,7 @@
"requiredByHint": "Nelze odebrat, dokud je aktivní „{capability}“",
"signupsCapabilityHint": "Kdo se smí přihlásit sám nebo přihlásit ostatní na směny, se nastavuje po skupinách na kartě „Skupiny“ (práva „Přihlásit se“ / „Přihlásit ostatní“).",
"signupsLocked": "Zapnout nebo vypnout přihlašování může jen ten, kdo smí spravovat nastavení kalendáře.",
+ "splitShiftsLocked": "Zapnout nebo vypnout dělené směny může jen ten, kdo smí spravovat nastavení kalendáře.",
"usageShares": "{count, plural, one {# sdílení} few {# sdílení} other {# sdílení}}",
"usageTokens": "{count, plural, one {# odkaz} few {# odkazy} other {# odkazů}}",
"usageGuestAccess": "hostovský přístup",
@@ -1124,6 +1136,7 @@
"shifts": "Směny",
"notesEvents": "Poznámky a události",
"signups": "Přihlášky",
+ "splitShifts": "Dělené směny",
"presets": "Předvolby",
"externalSync": "Externí synchronizace",
"administration": "Administrace"
diff --git a/messages/de.json b/messages/de.json
index 0f71be1..5874e54 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -857,7 +857,9 @@
"linkInfoGuestsOn": "Der Link öffnet den Kalender direkt, ohne Anmeldung. Er lässt sich jederzeit in der Liste widerrufen — dann ist er sofort ungültig.",
"linkInfoGuestsOff": "Der Link öffnet den Kalender direkt. Weil der Gastzugang auf dieser Instanz aus ist, müssen sich Empfänger anmelden. Er lässt sich jederzeit in der Liste widerrufen — dann ist er sofort ungültig.",
"signupsEnabledLabel": "Schicht-Anmeldungen aktivieren",
- "signupsEnabledDesc": "Erlaubt, dass sich Personen für Schichten eintragen. Ausgeschaltet verschwinden Anmeldelisten, Avatare und die maximale Personenanzahl aus der Ansicht."
+ "signupsEnabledDesc": "Erlaubt, dass sich Personen für Schichten eintragen. Ausgeschaltet verschwinden Anmeldelisten, Avatare und die maximale Personenanzahl aus der Ansicht.",
+ "splitShiftsEnabledLabel": "Geteilte Dienste aktivieren",
+ "splitShiftsEnabledDesc": "Erlaubt mehrere Zeitfenster in einer Schicht oder Vorlage, z. B. 06:00–10:00 und 15:00–21:00. Ausgeschaltet werden zusätzliche Zeitfenster überall ausgeblendet."
},
"shiftSheet": {
"start": "Beginn",
@@ -1088,6 +1090,15 @@
},
"addOtherHint": "Person nicht in der Liste? Teile den Kalender zuerst mit ihr, dann kannst du sie hier auswählen."
},
+ "timeRanges": {
+ "add": "Zeitfenster hinzufügen",
+ "remove": "Zeitfenster entfernen",
+ "errors": {
+ "overlap": "Zeitfenster dürfen sich nicht überschneiden.",
+ "overnight_segment": "Bei mehreren Zeitfenstern muss jedes am selben Tag enden.",
+ "invalid_format": "Ungültige Uhrzeit."
+ }
+ },
"permissionBundles": {
"bundle": "Berechtigungsgruppe",
"title": "Berechtigungen",
@@ -1107,6 +1118,7 @@
"requiredByHint": "Kann nicht entfernt werden, solange „{capability}“ aktiviert ist",
"signupsCapabilityHint": "Wer sich selbst oder andere für Schichten eintragen darf, wird pro Gruppe im Tab „Gruppen“ festgelegt (Rechte „Sich selbst eintragen“ / „Andere eintragen“).",
"signupsLocked": "Nur wer Kalendereinstellungen verwalten darf, kann Anmeldungen ein- oder ausschalten.",
+ "splitShiftsLocked": "Nur wer Kalendereinstellungen verwalten darf, kann geteilte Dienste ein- oder ausschalten.",
"usageShares": "{count, plural, one {# Freigabe} other {# Freigaben}}",
"usageTokens": "{count, plural, one {# Link} other {# Links}}",
"usageGuestAccess": "dem Gastzugang",
@@ -1124,6 +1136,7 @@
"shifts": "Schichten",
"notesEvents": "Notizen & Events",
"signups": "Anmeldungen",
+ "splitShifts": "Geteilte Dienste",
"presets": "Presets",
"externalSync": "Externer Sync",
"administration": "Verwaltung"
diff --git a/messages/en.json b/messages/en.json
index 97bc33f..a3da5f4 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -857,7 +857,9 @@
"linkInfoGuestsOn": "The link opens the calendar directly, without signing in. You can revoke it from the list at any time — it stops working immediately.",
"linkInfoGuestsOff": "The link opens the calendar directly. Guest access is off on this instance, so recipients need to sign in. You can revoke it from the list at any time — it stops working immediately.",
"signupsEnabledLabel": "Enable shift signups",
- "signupsEnabledDesc": "Lets people sign up for shifts. Turning this off hides signup lists, avatars, and the maximum headcount everywhere."
+ "signupsEnabledDesc": "Lets people sign up for shifts. Turning this off hides signup lists, avatars, and the maximum headcount everywhere.",
+ "splitShiftsEnabledLabel": "Enable split shifts",
+ "splitShiftsEnabledDesc": "Allows multiple time ranges in one shift or preset, e.g. 06:00–10:00 and 15:00–21:00. Turning this off hides extra time ranges everywhere."
},
"shiftSheet": {
"start": "Start",
@@ -1088,6 +1090,15 @@
},
"addOtherHint": "Can't find someone? Share the calendar with them first, then you can pick them here."
},
+ "timeRanges": {
+ "add": "Add time range",
+ "remove": "Remove time range",
+ "errors": {
+ "overlap": "Time ranges must not overlap.",
+ "overnight_segment": "With multiple time ranges, each one must end on the same day.",
+ "invalid_format": "Invalid time."
+ }
+ },
"permissionBundles": {
"bundle": "Permission bundle",
"title": "Permissions",
@@ -1107,6 +1118,7 @@
"requiredByHint": "Can't be removed while “{capability}” is enabled",
"signupsCapabilityHint": "Who may sign themselves or others up for shifts is set per group in the “Groups” tab (the “Sign up self” / “Sign up others” capabilities).",
"signupsLocked": "Only someone who can manage calendar settings can turn sign-ups on or off.",
+ "splitShiftsLocked": "Only someone who can manage calendar settings can turn split shifts on or off.",
"usageShares": "{count, plural, one {# share} other {# shares}}",
"usageTokens": "{count, plural, one {# link} other {# links}}",
"usageGuestAccess": "guest access",
@@ -1124,6 +1136,7 @@
"shifts": "Shifts",
"notesEvents": "Notes & Events",
"signups": "Signups",
+ "splitShifts": "Split shifts",
"presets": "Presets",
"externalSync": "External Sync",
"administration": "Administration"
diff --git a/messages/es.json b/messages/es.json
index 2f074bc..1b1814e 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -857,7 +857,9 @@
"linkInfoGuestsOn": "El enlace abre el calendario directamente, sin iniciar sesión. Puedes revocarlo en la lista en cualquier momento; deja de funcionar al instante.",
"linkInfoGuestsOff": "El enlace abre el calendario directamente. El acceso de invitados está desactivado en esta instancia, así que los destinatarios deben iniciar sesión. Puedes revocarlo en la lista en cualquier momento; deja de funcionar al instante.",
"signupsEnabledLabel": "Activar inscripciones a turnos",
- "signupsEnabledDesc": "Permite que las personas se inscriban en turnos. Al desactivarlo desaparecen las listas de inscripción, los avatares y el número máximo de personas."
+ "signupsEnabledDesc": "Permite que las personas se inscriban en turnos. Al desactivarlo desaparecen las listas de inscripción, los avatares y el número máximo de personas.",
+ "splitShiftsEnabledLabel": "Activar turnos partidos",
+ "splitShiftsEnabledDesc": "Permite varios tramos horarios en un turno o plantilla, p. ej., 06:00–10:00 y 15:00–21:00. Al desactivarlo desaparecen los tramos horarios adicionales en todas partes."
},
"shiftSheet": {
"start": "Inicio",
@@ -1088,6 +1090,15 @@
},
"addOtherHint": "¿No encuentras a alguien? Comparte primero el calendario con esa persona; luego podrás seleccionarla aquí."
},
+ "timeRanges": {
+ "add": "Añadir tramo horario",
+ "remove": "Quitar tramo horario",
+ "errors": {
+ "overlap": "Los tramos horarios no deben superponerse.",
+ "overnight_segment": "Con varios tramos horarios, cada uno debe terminar el mismo día.",
+ "invalid_format": "Hora no válida."
+ }
+ },
"permissionBundles": {
"bundle": "Grupo de permisos",
"title": "Permisos",
@@ -1107,6 +1118,7 @@
"requiredByHint": "No se puede quitar mientras «{capability}» esté activado",
"signupsCapabilityHint": "Quién puede inscribirse a sí mismo o a otros en turnos se define por grupo en la pestaña «Grupos» (permisos «Inscribirse» / «Inscribir a otros»).",
"signupsLocked": "Solo quien puede gestionar los ajustes del calendario puede activar o desactivar las inscripciones.",
+ "splitShiftsLocked": "Solo quien puede gestionar los ajustes del calendario puede activar o desactivar los turnos partidos.",
"usageShares": "{count, plural, one {# compartido} other {# compartidos}}",
"usageTokens": "{count, plural, one {# enlace} other {# enlaces}}",
"usageGuestAccess": "el acceso de invitados",
@@ -1124,6 +1136,7 @@
"shifts": "Turnos",
"notesEvents": "Notas y eventos",
"signups": "Inscripciones",
+ "splitShifts": "Turnos partidos",
"presets": "Plantillas",
"externalSync": "Sincronización externa",
"administration": "Administración"
diff --git a/messages/fr.json b/messages/fr.json
index a2df82e..cf2375c 100755
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -857,7 +857,9 @@
"linkInfoGuestsOn": "Le lien ouvre directement le calendrier, sans connexion. Vous pouvez le révoquer à tout moment dans la liste ; il cesse alors immédiatement de fonctionner.",
"linkInfoGuestsOff": "Le lien ouvre directement le calendrier. L’accès invité est désactivé sur cette instance : les destinataires doivent se connecter. Vous pouvez le révoquer à tout moment dans la liste ; il cesse alors immédiatement de fonctionner.",
"signupsEnabledLabel": "Activer les inscriptions aux gardes",
- "signupsEnabledDesc": "Permet aux personnes de s'inscrire aux gardes. La désactivation masque les listes d'inscription, les avatars et l'effectif maximal partout."
+ "signupsEnabledDesc": "Permet aux personnes de s'inscrire aux gardes. La désactivation masque les listes d'inscription, les avatars et l'effectif maximal partout.",
+ "splitShiftsEnabledLabel": "Activer les gardes fractionnées",
+ "splitShiftsEnabledDesc": "Permet plusieurs plages horaires dans une garde ou un modèle, par ex. 06:00–10:00 et 15:00–21:00. La désactivation masque partout les plages horaires supplémentaires."
},
"shiftSheet": {
"start": "Début",
@@ -1088,6 +1090,15 @@
},
"addOtherHint": "Vous ne trouvez pas quelqu'un ? Partagez d'abord le calendrier avec cette personne, vous pourrez ensuite la sélectionner ici."
},
+ "timeRanges": {
+ "add": "Ajouter une plage horaire",
+ "remove": "Supprimer la plage horaire",
+ "errors": {
+ "overlap": "Les plages horaires ne doivent pas se chevaucher.",
+ "overnight_segment": "Avec plusieurs plages horaires, chacune doit se terminer le même jour.",
+ "invalid_format": "Heure invalide."
+ }
+ },
"permissionBundles": {
"bundle": "Groupe de permissions",
"title": "Autorisations",
@@ -1107,6 +1118,7 @@
"requiredByHint": "Ne peut pas être retiré tant que « {capability} » est activé",
"signupsCapabilityHint": "Qui peut s'inscrire ou inscrire d'autres personnes aux créneaux se définit par groupe dans l'onglet « Groupes » (droits « S'inscrire » / « Inscrire d'autres personnes »).",
"signupsLocked": "Seule une personne pouvant gérer les paramètres du calendrier peut activer ou désactiver les inscriptions.",
+ "splitShiftsLocked": "Seule une personne pouvant gérer les paramètres du calendrier peut activer ou désactiver les gardes fractionnées.",
"usageShares": "{count, plural, one {# partage} other {# partages}}",
"usageTokens": "{count, plural, one {# lien} other {# liens}}",
"usageGuestAccess": "l'accès invité",
@@ -1124,6 +1136,7 @@
"shifts": "Créneaux",
"notesEvents": "Notes et événements",
"signups": "Inscriptions",
+ "splitShifts": "Gardes fractionnées",
"presets": "Modèles",
"externalSync": "Synchronisation externe",
"administration": "Administration"
diff --git a/messages/it.json b/messages/it.json
index 83c6c61..d8d4cd4 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -857,7 +857,9 @@
"linkInfoGuestsOn": "Il link apre direttamente il calendario, senza accesso. Puoi revocarlo dalla lista in qualsiasi momento: smette subito di funzionare.",
"linkInfoGuestsOff": "Il link apre direttamente il calendario. L’accesso ospite è disattivato su questa istanza, quindi i destinatari devono accedere. Puoi revocarlo dalla lista in qualsiasi momento: smette subito di funzionare.",
"signupsEnabledLabel": "Attiva le iscrizioni ai turni",
- "signupsEnabledDesc": "Permette alle persone di iscriversi ai turni. Disattivandolo, elenchi di iscrizione, avatar e numero massimo di persone scompaiono ovunque."
+ "signupsEnabledDesc": "Permette alle persone di iscriversi ai turni. Disattivandolo, elenchi di iscrizione, avatar e numero massimo di persone scompaiono ovunque.",
+ "splitShiftsEnabledLabel": "Attiva i turni spezzati",
+ "splitShiftsEnabledDesc": "Permette più fasce orarie in un turno o modello, ad es. 06:00–10:00 e 15:00–21:00. Disattivandolo, le fasce orarie aggiuntive vengono nascoste ovunque."
},
"shiftSheet": {
"start": "Inizio",
@@ -1088,6 +1090,15 @@
},
"addOtherHint": "Non trovi qualcuno? Condividi prima il calendario con questa persona, poi potrai selezionarla qui."
},
+ "timeRanges": {
+ "add": "Aggiungi fascia oraria",
+ "remove": "Rimuovi fascia oraria",
+ "errors": {
+ "overlap": "Le fasce orarie non devono sovrapporsi.",
+ "overnight_segment": "Con più fasce orarie, ciascuna deve terminare lo stesso giorno.",
+ "invalid_format": "Ora non valida."
+ }
+ },
"permissionBundles": {
"bundle": "Gruppo di permessi",
"title": "Permessi",
@@ -1107,6 +1118,7 @@
"requiredByHint": "Non può essere rimosso finché «{capability}» è attivo",
"signupsCapabilityHint": "Chi può iscrivere sé stesso o altri ai turni si stabilisce per gruppo nella scheda «Gruppi» (diritti «Iscriversi» / «Iscrivere altri»).",
"signupsLocked": "Solo chi può gestire le impostazioni del calendario può attivare o disattivare le iscrizioni.",
+ "splitShiftsLocked": "Solo chi può gestire le impostazioni del calendario può attivare o disattivare i turni spezzati.",
"usageShares": "{count, plural, one {# condivisione} other {# condivisioni}}",
"usageTokens": "{count, plural, one {# link} other {# link}}",
"usageGuestAccess": "l'accesso ospite",
@@ -1124,6 +1136,7 @@
"shifts": "Turni",
"notesEvents": "Note ed eventi",
"signups": "Iscrizioni",
+ "splitShifts": "Turni spezzati",
"presets": "Preset",
"externalSync": "Sync esterno",
"administration": "Amministrazione"