Skip to content

Your favorite shift management application!

feat: custom fields for shifts and presets (#215)

panteLe3c8e10ec796
diff --git a/.env.example b/.env.example
index df58e07..d20e35e 100644
--- a/.env.example
+++ b/.env.example
@@ -235,6 +235,10 @@ ALLOW_USER_REGISTRATION=true # Enable/disable new user signups
# RATE_LIMIT_BUNDLE_MUTATIONS_REQUESTS=30 # Bundle create/update/delete/clone
# RATE_LIMIT_BUNDLE_MUTATIONS_WINDOW=3600 # 1 hour
+# Custom Field Catalog (per calendar)
+# RATE_LIMIT_CUSTOM_FIELD_MUTATIONS_REQUESTS=30 # Field create/update/delete/reorder
+# RATE_LIMIT_CUSTOM_FIELD_MUTATIONS_WINDOW=3600 # 1 hour
+
# Admin Panel (per admin user)
# RATE_LIMIT_ADMIN_USER_MUTATIONS=10 # User ban/unban/delete/edit
# RATE_LIMIT_ADMIN_USER_MUTATIONS_WINDOW=60 # 1 minute
diff --git a/.gitignore b/.gitignore
index eb3217c..edb04cd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -86,3 +86,4 @@ public/workbox-*.js.map
# Superpowers specs and plans (local planning artifacts, not part of the product docs)
docs/superpowers/
+.superpowers/
diff --git a/CLAUDE.md b/CLAUDE.md
index cf053ab..3ec2cb1 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -89,6 +89,8 @@ Shifts produced this way carry `syncedFromExternal` and an `externalSyncId` and
Client-side, all cache keys come from `lib/query-keys.ts`; an ad-hoc key array silently breaks invalidation. Mutations are optimistic and follow `onMutate` (cancel → snapshot → patch cache) / `onError` (roll back → toast) / `onSettled` (invalidate). `hooks/useShifts.ts` is the reference; copy its shape for new mutations.
+**Custom fields.** A calendar can define extra typed fields (`calendarCustomFields`) whose values hang off shifts and presets in two child tables mirroring the time-segment tables. `lib/custom-fields.ts` holds the type catalog, serialisation and validation shared by routes and client; `lib/shift-custom-fields.ts` holds the DB helpers. Values are not separate resources — they travel as `customFields: Record<key, value>` on the existing shift and preset payloads, carried by the shift `PUT` and preset `PATCH` handlers. A preset's values pre-fill a shift client-side in `applyPreset()` for a caller with `createShift`; the `stampPreset`-only path reads them server-side from the preset row instead, because that path never trusts the request body.
+
### i18n
`messages/de.json` is the source of truth, `en`, `es`, `fr`, `it` and `cs` are mirrors. `scripts/i18n-checks.ts` flattens every locale to dot keys, greps `app/`, `components/`, `hooks/`, `lib/` for usages, and reports keys used but missing from `de.json`, keys missing from other locales, and unused keys. It runs in CI, so add the German key first, then translate. Locale resolution is server-side in `lib/i18n.ts`: `NEXT_LOCALE` cookie → `Accept-Language` → `DEFAULT_LOCALE`. A new locale also needs an entry in `lib/locales.ts`, including its `date-fns` locale — an unknown `DEFAULT_LOCALE` throws at startup.
diff --git a/app/api/calendars/[id]/custom-fields/[fieldId]/route.ts b/app/api/calendars/[id]/custom-fields/[fieldId]/route.ts
new file mode 100644
index 0000000..fb1d53b
--- /dev/null
+++ b/app/api/calendars/[id]/custom-fields/[fieldId]/route.ts
@@ -0,0 +1,142 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import {
+ calendarCustomFields,
+ presetCustomFieldValues,
+ shiftCustomFieldValues,
+} from "@/lib/db/schema";
+import { and, eq, sql } from "drizzle-orm";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { hasCapability } from "@/lib/auth/permissions";
+import { rateLimit } from "@/lib/rate-limiter";
+import {
+ logUserAction,
+ type CustomFieldDeletedMetadata,
+ type CustomFieldUpdatedMetadata,
+} from "@/lib/audit-log";
+import { sanitizeDefinitionInput } from "@/lib/custom-fields";
+import { getCalendarName } from "@/lib/auth/permission-bundles-service";
+
+async function loadField(calendarId: string, fieldId: string) {
+ const [field] = await db
+ .select()
+ .from(calendarCustomFields)
+ .where(
+ and(
+ eq(calendarCustomFields.id, fieldId),
+ eq(calendarCustomFields.calendarId, calendarId)
+ )
+ );
+ return field ?? null;
+}
+
+export async function PATCH(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string; fieldId: string }> }
+) {
+ try {
+ const { id: calendarId, fieldId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ if (!(await hasCapability(user?.id, calendarId, "manageCustomFields"))) {
+ return NextResponse.json({ error: "Insufficient permissions" }, { status: 403 });
+ }
+
+ const limited = rateLimit(request, user?.id, "custom-field-mutations", calendarId);
+ if (limited) return limited;
+
+ const field = await loadField(calendarId, fieldId);
+ if (!field) {
+ return NextResponse.json({ error: "Custom field not found" }, { status: 404 });
+ }
+
+ const body = await request.json();
+ // key and type are immutable: re-sanitise against the stored type so a
+ // client cannot change either by sending them.
+ const input = sanitizeDefinitionInput({ ...body, type: field.type });
+ if (!input) {
+ return NextResponse.json({ error: "Invalid custom field" }, { status: 400 });
+ }
+
+ const [updated] = await db
+ .update(calendarCustomFields)
+ .set({
+ label: input.label,
+ options: input.options,
+ required: input.required,
+ showInCalendar: input.showInCalendar,
+ })
+ .where(eq(calendarCustomFields.id, fieldId))
+ .returning();
+
+ await logUserAction<CustomFieldUpdatedMetadata>({
+ userId: user?.id,
+ action: "calendar.customField.updated",
+ request,
+ metadata: {
+ calendarId,
+ calendarName: await getCalendarName(calendarId),
+ fieldKey: updated.key,
+ fieldLabel: updated.label,
+ },
+ });
+
+ return NextResponse.json(updated);
+ } catch (error) {
+ console.error("Failed to update custom field:", error);
+ return NextResponse.json({ error: "Failed to update custom field" }, { status: 500 });
+ }
+}
+
+export async function DELETE(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string; fieldId: string }> }
+) {
+ try {
+ const { id: calendarId, fieldId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ if (!(await hasCapability(user?.id, calendarId, "manageCustomFields"))) {
+ return NextResponse.json({ error: "Insufficient permissions" }, { status: 403 });
+ }
+
+ const limited = rateLimit(request, user?.id, "custom-field-mutations", calendarId);
+ if (limited) return limited;
+
+ const field = await loadField(calendarId, fieldId);
+ if (!field) {
+ return NextResponse.json({ error: "Custom field not found" }, { status: 404 });
+ }
+
+ // Counted before the delete; the rows go away with it via ON DELETE CASCADE.
+ const [{ shiftCount }] = await db
+ .select({ shiftCount: sql<number>`count(*)` })
+ .from(shiftCustomFieldValues)
+ .where(eq(shiftCustomFieldValues.fieldId, fieldId));
+ const [{ presetCount }] = await db
+ .select({ presetCount: sql<number>`count(*)` })
+ .from(presetCustomFieldValues)
+ .where(eq(presetCustomFieldValues.fieldId, fieldId));
+
+ await db.delete(calendarCustomFields).where(eq(calendarCustomFields.id, fieldId));
+
+ await logUserAction<CustomFieldDeletedMetadata>({
+ userId: user?.id,
+ action: "calendar.customField.deleted",
+ request,
+ metadata: {
+ calendarId,
+ calendarName: await getCalendarName(calendarId),
+ fieldKey: field.key,
+ fieldLabel: field.label,
+ affectedShifts: shiftCount,
+ affectedPresets: presetCount,
+ },
+ });
+
+ return NextResponse.json({ success: true });
+ } catch (error) {
+ console.error("Failed to delete custom field:", error);
+ return NextResponse.json({ error: "Failed to delete custom field" }, { status: 500 });
+ }
+}
diff --git a/app/api/calendars/[id]/custom-fields/reorder/route.ts b/app/api/calendars/[id]/custom-fields/reorder/route.ts
new file mode 100644
index 0000000..f50d25e
--- /dev/null
+++ b/app/api/calendars/[id]/custom-fields/reorder/route.ts
@@ -0,0 +1,48 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { calendarCustomFields } from "@/lib/db/schema";
+import { and, eq } from "drizzle-orm";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { hasCapability } from "@/lib/auth/permissions";
+import { rateLimit } from "@/lib/rate-limiter";
+
+export async function PATCH(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id: calendarId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ if (!(await hasCapability(user?.id, calendarId, "manageCustomFields"))) {
+ return NextResponse.json({ error: "Insufficient permissions" }, { status: 403 });
+ }
+
+ const limited = rateLimit(request, user?.id, "custom-field-mutations", calendarId);
+ if (limited) return limited;
+
+ const { fieldIds } = await request.json();
+ if (!Array.isArray(fieldIds) || fieldIds.some((id) => typeof id !== "string")) {
+ return NextResponse.json({ error: "Invalid fieldIds" }, { status: 400 });
+ }
+
+ db.transaction((tx) => {
+ fieldIds.forEach((fieldId: string, index: number) => {
+ tx.update(calendarCustomFields)
+ .set({ order: index })
+ .where(
+ and(
+ eq(calendarCustomFields.id, fieldId),
+ eq(calendarCustomFields.calendarId, calendarId)
+ )
+ )
+ .run();
+ });
+ });
+
+ return NextResponse.json({ success: true });
+ } catch (error) {
+ console.error("Failed to reorder custom fields:", error);
+ return NextResponse.json({ error: "Failed to reorder custom fields" }, { status: 500 });
+ }
+}
diff --git a/app/api/calendars/[id]/custom-fields/route.ts b/app/api/calendars/[id]/custom-fields/route.ts
new file mode 100644
index 0000000..44f929d
--- /dev/null
+++ b/app/api/calendars/[id]/custom-fields/route.ts
@@ -0,0 +1,104 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { calendarCustomFields } from "@/lib/db/schema";
+import { and, eq, sql } from "drizzle-orm";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { hasCapability } from "@/lib/auth/permissions";
+import { rateLimit } from "@/lib/rate-limiter";
+import { logUserAction, type CustomFieldCreatedMetadata } from "@/lib/audit-log";
+import { getCalendarCustomFields } from "@/lib/shift-custom-fields";
+import { sanitizeDefinitionInput } from "@/lib/custom-fields";
+import { getCalendarName } from "@/lib/auth/permission-bundles-service";
+
+export async function GET(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id: calendarId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ // Read-only users need the catalog to label the values they can see.
+ if (!(await hasCapability(user?.id, calendarId, "viewShifts"))) {
+ return NextResponse.json({ error: "Insufficient permissions" }, { status: 403 });
+ }
+
+ return NextResponse.json(await getCalendarCustomFields(calendarId));
+ } catch (error) {
+ console.error("Failed to fetch custom fields:", error);
+ return NextResponse.json({ error: "Failed to fetch custom fields" }, { status: 500 });
+ }
+}
+
+export async function POST(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id: calendarId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ if (!(await hasCapability(user?.id, calendarId, "manageCustomFields"))) {
+ return NextResponse.json({ error: "Insufficient permissions" }, { status: 403 });
+ }
+
+ const limited = rateLimit(request, user?.id, "custom-field-mutations", calendarId);
+ if (limited) return limited;
+
+ const input = sanitizeDefinitionInput(await request.json());
+ if (!input || !input.key) {
+ return NextResponse.json({ error: "Invalid custom field" }, { status: 400 });
+ }
+
+ const [existing] = await db
+ .select({ id: calendarCustomFields.id })
+ .from(calendarCustomFields)
+ .where(
+ and(
+ eq(calendarCustomFields.calendarId, calendarId),
+ eq(calendarCustomFields.key, input.key)
+ )
+ );
+ if (existing) {
+ return NextResponse.json({ error: "KEY_IN_USE" }, { status: 409 });
+ }
+
+ const [{ maxOrder }] = await db
+ .select({ maxOrder: sql<number>`coalesce(max(${calendarCustomFields.order}), -1)` })
+ .from(calendarCustomFields)
+ .where(eq(calendarCustomFields.calendarId, calendarId));
+
+ const [created] = await db
+ .insert(calendarCustomFields)
+ .values({
+ calendarId,
+ key: input.key,
+ label: input.label,
+ type: input.type,
+ options: input.options,
+ required: input.required,
+ showInCalendar: input.showInCalendar,
+ order: maxOrder + 1,
+ createdBy: user?.id ?? null,
+ })
+ .returning();
+
+ await logUserAction<CustomFieldCreatedMetadata>({
+ userId: user?.id,
+ action: "calendar.customField.created",
+ request,
+ metadata: {
+ calendarId,
+ calendarName: await getCalendarName(calendarId),
+ fieldKey: created.key,
+ fieldLabel: created.label,
+ fieldType: created.type,
+ },
+ });
+
+ return NextResponse.json(created, { status: 201 });
+ } catch (error) {
+ console.error("Failed to create custom field:", error);
+ return NextResponse.json({ error: "Failed to create custom field" }, { status: 500 });
+ }
+}
diff --git a/app/api/export/ics/route.ts b/app/api/export/ics/route.ts
index 68d7875..75b5bc4 100644
--- a/app/api/export/ics/route.ts
+++ b/app/api/export/ics/route.ts
@@ -8,6 +8,8 @@ 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";
+import { getCalendarCustomFields, withShiftCustomFields } from "@/lib/shift-custom-fields";
+import { formatValueForDisplay } from "@/lib/custom-fields";
export async function POST(request: NextRequest) {
try {
@@ -17,6 +19,9 @@ export async function POST(request: NextRequest) {
const rateLimitResponse = rateLimit(request, user?.id, "export-ics");
if (rateLimitResponse) return rateLimitResponse;
+ const { searchParams } = new URL(request.url);
+ const locale = searchParams.get("locale") || "en";
+
const { calendarIds } = await request.json();
if (!Array.isArray(calendarIds) || calendarIds.length === 0) {
@@ -77,6 +82,24 @@ export async function POST(request: NextRequest) {
// Create calendar name lookup
const calendarMap = new Map(accessibleCalendars.map((c) => [c.id, c.name]));
+ // Field keys are per calendar, so definitions and values must be resolved calendar by calendar.
+ const definitionsByCalendar = new Map(
+ await Promise.all(
+ accessibleCalendars.map(
+ async (c) => [c.id, await getCalendarCustomFields(c.id)] as const
+ )
+ )
+ );
+ const customFieldsByShiftId = new Map<string, Record<string, string | number | boolean | null>>();
+ for (const c of accessibleCalendars) {
+ const definitions = definitionsByCalendar.get(c.id) ?? [];
+ const calendarShifts = allShifts.filter((s) => s.calendarId === c.id);
+ const withFields = await withShiftCustomFields(calendarShifts, definitions);
+ for (const s of withFields) {
+ customFieldsByShiftId.set(s.id, s.customFields);
+ }
+ }
+
// Get server timezone for proper time conversion
const serverTimezone = getServerTimezone();
@@ -110,14 +133,25 @@ export async function POST(request: NextRequest) {
const ranges = shift.isAllDay ? [null] : toTimeRanges(shift);
+ const definitions = definitionsByCalendar.get(shift.calendarId) ?? [];
+ const customFields = customFieldsByShiftId.get(shift.id) ?? {};
+ const fieldLines = definitions
+ .map((d) => {
+ const raw = customFields[d.key];
+ if (raw === null || raw === undefined || raw === "") return null;
+ return `${d.label}: ${formatValueForDisplay(d, String(raw), locale)}`;
+ })
+ .filter((line): line is string => line !== null);
+ const description = [shift.notes, ...fieldLines].filter(Boolean).join("\n");
+
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 (description) {
+ event.description = description;
}
if (!range) {
diff --git a/app/api/export/pdf/route.ts b/app/api/export/pdf/route.ts
index b534db5..175d524 100644
--- a/app/api/export/pdf/route.ts
+++ b/app/api/export/pdf/route.ts
@@ -8,6 +8,8 @@ import { hasCapability } from "@/lib/auth/permissions";
import { rateLimit } from "@/lib/rate-limiter";
import { formatDateToLocal } from "@/lib/date-utils";
import { formatTimeRange } from "@/lib/shift-display";
+import { getCalendarCustomFields, withShiftCustomFields } from "@/lib/shift-custom-fields";
+import { formatValueForDisplay } from "@/lib/custom-fields";
export async function POST(request: NextRequest) {
try {
@@ -102,6 +104,24 @@ export async function POST(request: NextRequest) {
accessibleCalendars.map((c) => [c.id, { name: c.name, color: c.color }])
);
+ // Field keys are per calendar, so definitions and values must be resolved calendar by calendar.
+ const definitionsByCalendar = new Map(
+ await Promise.all(
+ accessibleCalendars.map(
+ async (c) => [c.id, await getCalendarCustomFields(c.id)] as const
+ )
+ )
+ );
+ const customFieldsByShiftId = new Map<string, Record<string, string | number | boolean | null>>();
+ for (const c of accessibleCalendars) {
+ const definitions = definitionsByCalendar.get(c.id) ?? [];
+ const calendarShifts = allShifts.filter((s) => s.calendarId === c.id);
+ const withFields = await withShiftCustomFields(calendarShifts, definitions);
+ for (const s of withFields) {
+ customFieldsByShiftId.set(s.id, s.customFields);
+ }
+ }
+
// Determine if multi-calendar export
const isMultiCalendar = accessibleCalendars.length > 1;
@@ -274,12 +294,23 @@ export async function POST(request: NextRequest) {
yPosition += 5;
- // Notes (if present)
- if (shift.notes) {
+ // Notes and custom field values, wrapped and paged together
+ const definitions = definitionsByCalendar.get(shift.calendarId) ?? [];
+ const customFields = customFieldsByShiftId.get(shift.id) ?? {};
+ const fieldLines = definitions
+ .map((d) => {
+ const raw = customFields[d.key];
+ if (raw === null || raw === undefined || raw === "") return null;
+ return `${d.label}: ${formatValueForDisplay(d, String(raw), locale)}`;
+ })
+ .filter((line): line is string => line !== null);
+ const noteText = [shift.notes, ...fieldLines].filter(Boolean).join("\n");
+
+ if (noteText) {
doc.setFont("helvetica", "italic");
doc.setFontSize(9);
const notesLines = doc.splitTextToSize(
- shift.notes,
+ noteText,
pageWidth - margin * 2 - 10
);
for (const line of notesLines) {
diff --git a/app/api/presets/[id]/route.ts b/app/api/presets/[id]/route.ts
index 8a3ac37..4e59273 100644
--- a/app/api/presets/[id]/route.ts
+++ b/app/api/presets/[id]/route.ts
@@ -7,6 +7,13 @@ import { hasCapability, hasOwnedCapability } from "@/lib/auth/permissions";
import { trimOrNull } from "@/lib/utils";
import { replacePresetSegments, replaceShiftSegments, withPresetSegments } from "@/lib/shift-time-ranges";
import { normalizeTimeRanges, toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
+import {
+ getCalendarCustomFields,
+ withPresetCustomFields,
+ resolveCustomFieldValues,
+ replacePresetCustomFieldValues,
+ type CustomFieldValueRow,
+} from "@/lib/shift-custom-fields";
// GET single preset
export async function GET(
@@ -82,6 +89,7 @@ export async function PATCH(
hideFromStats,
defaultSignupCapacity,
segments: requestedSegments,
+ customFields,
} = body;
// groupName: undefined leaves it unchanged, null explicitly clears it,
@@ -173,6 +181,18 @@ export async function PATCH(
}
}
+ const customFieldDefinitions = await getCalendarCustomFields(existingPreset.calendarId);
+ // null means "not mentioned in the request" — leave existing values untouched;
+ // an empty object still resolves to [] and clears them.
+ let customFieldValuesToPersist: CustomFieldValueRow[] | null = null;
+ if (customFields !== undefined) {
+ const resolved = resolveCustomFieldValues(customFieldDefinitions, customFields);
+ if ("error" in resolved) {
+ return NextResponse.json({ error: resolved.error }, { status: 400 });
+ }
+ customFieldValuesToPersist = resolved.values;
+ }
+
const updatedPreset = db.transaction((tx) => {
const updated = tx
.update(shiftPresets)
@@ -200,6 +220,10 @@ export async function PATCH(
replacePresetSegments(tx, id, nextSegments);
}
+ if (customFieldValuesToPersist !== null) {
+ replacePresetCustomFieldValues(tx, id, customFieldValuesToPersist);
+ }
+
// Cascade to every shift created from this preset — title/time/color/
// notes/isAllDay are already cascaded unconditionally below; segments
// must follow the same rule so a preset's split-shift edit doesn't
@@ -243,7 +267,8 @@ export async function PATCH(
});
const [withSegments] = await withPresetSegments([updatedPreset]);
- return NextResponse.json(withSegments);
+ const [withCustomFields] = await withPresetCustomFields([withSegments], customFieldDefinitions);
+ return NextResponse.json(withCustomFields);
} 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 d8fc1fe..ba3b32f 100644
--- a/app/api/presets/route.ts
+++ b/app/api/presets/route.ts
@@ -7,6 +7,12 @@ 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";
+import {
+ getCalendarCustomFields,
+ withPresetCustomFields,
+ resolveCustomFieldValues,
+ replacePresetCustomFieldValues,
+} from "@/lib/shift-custom-fields";
// GET all presets for a calendar
export async function GET(request: NextRequest) {
@@ -50,9 +56,11 @@ export async function GET(request: NextRequest) {
.from(shiftPresets)
.where(eq(shiftPresets.calendarId, calendarId))
.orderBy(asc(shiftPresets.order));
- return NextResponse.json(
- calendar.splitShiftsEnabled ? await withPresetSegments(presets) : presets
- );
+ const withSegs = calendar.splitShiftsEnabled
+ ? await withPresetSegments(presets)
+ : presets;
+ const definitions = await getCalendarCustomFields(calendarId);
+ return NextResponse.json(await withPresetCustomFields(withSegs, definitions));
} catch (error) {
console.error("Error fetching presets:", error);
return NextResponse.json(
@@ -79,6 +87,7 @@ export async function POST(request: NextRequest) {
hideFromStats,
defaultSignupCapacity,
segments: requestedSegments,
+ customFields,
} = body;
if (!calendarId || !title) {
@@ -148,6 +157,15 @@ export async function POST(request: NextRequest) {
segmentsToPersist = normalized.segments;
}
+ const customFieldDefinitions = await getCalendarCustomFields(calendarId);
+ const resolvedCustomFields = resolveCustomFieldValues(
+ customFieldDefinitions,
+ customFields
+ );
+ if ("error" in resolvedCustomFields) {
+ return NextResponse.json({ error: resolvedCustomFields.error }, { status: 400 });
+ }
+
const preset = db.transaction((tx) => {
const inserted = tx
.insert(shiftPresets)
@@ -172,10 +190,12 @@ export async function POST(request: NextRequest) {
.returning()
.get();
replacePresetSegments(tx, inserted.id, segmentsToPersist);
+ replacePresetCustomFieldValues(tx, inserted.id, resolvedCustomFields.values);
return inserted;
});
- return NextResponse.json({ ...preset, segments: segmentsToPersist });
+ const [withFields] = await withPresetCustomFields([preset], customFieldDefinitions);
+ return NextResponse.json({ ...withFields, 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 5c545d3..ec33070 100644
--- a/app/api/shifts/[id]/route.ts
+++ b/app/api/shifts/[id]/route.ts
@@ -7,6 +7,13 @@ 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";
+import {
+ getCalendarCustomFields,
+ withShiftCustomFields,
+ resolveCustomFieldValues,
+ replaceShiftCustomFieldValues,
+ type CustomFieldValueRow,
+} from "@/lib/shift-custom-fields";
// GET single shift
export async function GET(
@@ -239,6 +246,18 @@ export async function PUT(
}
}
+ const customFieldDefinitions = await getCalendarCustomFields(existingShift.calendarId);
+ // null means "not mentioned in the request" — leave existing values untouched;
+ // an empty object still resolves to [] and clears them.
+ let customFieldValuesToPersist: CustomFieldValueRow[] | null = null;
+ if (body.customFields !== undefined) {
+ const resolved = resolveCustomFieldValues(customFieldDefinitions, body.customFields);
+ if ("error" in resolved) {
+ return NextResponse.json({ error: resolved.error }, { status: 400 });
+ }
+ customFieldValuesToPersist = resolved.values;
+ }
+
// Update the shift
const updatedShift = db.transaction((tx) => {
const updated = tx
@@ -266,11 +285,15 @@ export async function PUT(
if (nextSegments !== undefined) {
replaceShiftSegments(tx, id, nextSegments);
}
+ if (customFieldValuesToPersist !== null) {
+ replaceShiftCustomFieldValues(tx, id, customFieldValuesToPersist);
+ }
return updated;
});
const [withSegments] = await withShiftSegments([updatedShift]);
- return NextResponse.json(withSegments);
+ const [withCustomFields] = await withShiftCustomFields([withSegments], customFieldDefinitions);
+ return NextResponse.json(withCustomFields);
} 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 0ab56b8..7453bd0 100644
--- a/app/api/shifts/route.ts
+++ b/app/api/shifts/route.ts
@@ -9,6 +9,16 @@ 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";
+import type { CustomFieldInputValue } from "@/lib/custom-fields";
+import {
+ getCalendarCustomFields,
+ withShiftCustomFields,
+ withPresetCustomFields,
+ resolveCustomFieldValues,
+ replaceShiftCustomFieldValues,
+ readPresetCustomFieldValues,
+ type CustomFieldValueRow,
+} from "@/lib/shift-custom-fields";
// GET shifts for a calendar (with optional date filter)
export async function GET(request: Request) {
@@ -103,9 +113,11 @@ export async function GET(request: Request) {
)
);
const withSigs = await withSignups(result);
- return NextResponse.json(
- calendar.splitShiftsEnabled ? await withShiftSegments(withSigs) : withSigs
- );
+ const withSegs = calendar.splitShiftsEnabled
+ ? await withShiftSegments(withSigs)
+ : withSigs;
+ const definitions = await getCalendarCustomFields(calendarId);
+ return NextResponse.json(await withShiftCustomFields(withSegs, definitions));
}
const result = await query.where(
@@ -116,9 +128,11 @@ export async function GET(request: Request) {
)
);
const withSigs = await withSignups(result);
- return NextResponse.json(
- calendar.splitShiftsEnabled ? await withShiftSegments(withSigs) : withSigs
- );
+ const withSegs = calendar.splitShiftsEnabled
+ ? await withShiftSegments(withSigs)
+ : withSigs;
+ const definitions = await getCalendarCustomFields(calendarId);
+ return NextResponse.json(await withShiftCustomFields(withSegs, definitions));
} catch (error) {
console.error("Failed to fetch shifts:", error);
return NextResponse.json(
@@ -146,6 +160,7 @@ export async function POST(request: Request) {
signupCapacity,
signupUserIds,
segments: requestedSegments,
+ customFields,
} = body;
if (!calendarId || !date || !title) {
@@ -206,7 +221,13 @@ export async function POST(request: Request) {
isAllDay: boolean;
};
let segmentsToPersist: TimeRange[] = [];
+ let customFieldValuesToPersist: CustomFieldValueRow[] = [];
+ const customFieldDefinitions = await getCalendarCustomFields(calendarId);
if (access.can("createShift")) {
+ // A preset's own stored values are the defaults; a value the client
+ // actually submits (e.g. edited in the shift dialog after picking the
+ // preset) still wins, since this branch is the trusted-body path.
+ let presetCustomFieldDefaults: Record<string, CustomFieldInputValue> = {};
if (presetId) {
const [preset] = await db
.select()
@@ -223,6 +244,11 @@ export async function POST(request: Request) {
{ status: 404 }
);
}
+ const [presetWithFields] = await withPresetCustomFields(
+ [preset],
+ customFieldDefinitions
+ );
+ presetCustomFieldDefaults = presetWithFields.customFields;
}
insertValues = {
title,
@@ -232,6 +258,16 @@ export async function POST(request: Request) {
notes: notes || null,
isAllDay: isAllDay || false,
};
+ const resolved = resolveCustomFieldValues(customFieldDefinitions, {
+ ...presetCustomFieldDefaults,
+ ...(typeof customFields === "object" && customFields !== null && !Array.isArray(customFields)
+ ? customFields
+ : {}),
+ });
+ if ("error" in resolved) {
+ return NextResponse.json({ error: resolved.error }, { status: 400 });
+ }
+ customFieldValuesToPersist = resolved.values;
if (!isAllDay) {
const rawSegments: TimeRange[] = Array.isArray(requestedSegments)
@@ -284,6 +320,9 @@ export async function POST(request: Request) {
notes: preset.notes,
isAllDay: preset.isAllDay,
};
+ // Ignore any customFields in the body — stampPreset must not let
+ // "presets only" access set arbitrary values via a stamped preset.
+ customFieldValuesToPersist = await readPresetCustomFieldValues(preset.id);
if (!preset.isAllDay && calendar.splitShiftsEnabled) {
const [presetWithSegments] = await withPresetSegments([preset]);
segmentsToPersist = presetWithSegments.segments;
@@ -308,6 +347,7 @@ export async function POST(request: Request) {
.returning()
.get();
replaceShiftSegments(tx, inserted.id, segmentsToPersist);
+ replaceShiftCustomFieldValues(tx, inserted.id, customFieldValuesToPersist);
return inserted;
});
@@ -333,8 +373,14 @@ export async function POST(request: Request) {
}
}
+ const [withCustomFields] = await withShiftCustomFields([shift], customFieldDefinitions);
return NextResponse.json(
- { ...shift, calendar, signups, segments: segmentsToPersist },
+ {
+ ...withCustomFields,
+ calendar,
+ signups,
+ segments: segmentsToPersist,
+ },
{ status: 201 }
);
} catch (error) {
diff --git a/components/custom-field-inputs.tsx b/components/custom-field-inputs.tsx
new file mode 100644
index 0000000..6b1a606
--- /dev/null
+++ b/components/custom-field-inputs.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+import { useId } from "react";
+import { useTranslations } from "next-intl";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Field, ToggleRow, inputClass } from "@/components/form-kit";
+import type { CustomFieldDefinition, CustomFieldInputValue } from "@/lib/custom-fields";
+import { cn } from "@/lib/utils";
+
+// Radix Select can't carry an empty string as an item value, so an unset optional
+// select needs its own sentinel that never collides with a real option id.
+const SELECT_EMPTY = "__none__";
+
+interface CustomFieldInputsProps {
+ definitions: CustomFieldDefinition[];
+ values: Record<string, CustomFieldInputValue>;
+ onChange: (next: Record<string, CustomFieldInputValue>) => void;
+ disabled?: boolean;
+}
+
+export function CustomFieldInputs({
+ definitions,
+ values,
+ onChange,
+ disabled = false,
+}: CustomFieldInputsProps) {
+ const t = useTranslations();
+ const idPrefix = useId();
+
+ if (definitions.length === 0) return null;
+
+ const setValue = (key: string, value: CustomFieldInputValue) => {
+ onChange({ ...values, [key]: value });
+ };
+
+ return (
+ <div className="flex flex-col gap-3 lg:gap-4">
+ {definitions.map((definition) => {
+ const inputId = `${idPrefix}-${definition.id}`;
+ const value = values[definition.key] ?? null;
+ const optional = !definition.required;
+
+ switch (definition.type) {
+ case "checkbox":
+ return (
+ <ToggleRow
+ key={definition.id}
+ id={inputId}
+ title={definition.label}
+ checked={value === true}
+ onCheckedChange={(checked) => setValue(definition.key, checked)}
+ disabled={disabled}
+ />
+ );
+
+ case "select": {
+ const selected = typeof value === "string" ? value : null;
+ return (
+ <Field key={definition.id} label={definition.label} htmlFor={inputId} optional={optional}>
+ <Select
+ value={selected ?? SELECT_EMPTY}
+ onValueChange={(next) =>
+ setValue(definition.key, next === SELECT_EMPTY ? null : next)
+ }
+ disabled={disabled}
+ >
+ <SelectTrigger
+ id={inputId}
+ className="h-10 w-full rounded-[9px] px-3 text-[14px] data-[size=default]:h-10"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {optional && (
+ <SelectItem value={SELECT_EMPTY}>{t("customFields.selectNone")}</SelectItem>
+ )}
+ {(definition.options ?? []).map((option) => (
+ <SelectItem key={option.id} value={option.id}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ );
+ }
+
+ case "date":
+ return (
+ <Field key={definition.id} label={definition.label} htmlFor={inputId} optional={optional}>
+ <Input
+ id={inputId}
+ type="date"
+ value={typeof value === "string" ? value : ""}
+ onChange={(e) =>
+ setValue(definition.key, e.target.value === "" ? null : e.target.value)
+ }
+ disabled={disabled}
+ className={cn(inputClass, "font-mono")}
+ />
+ </Field>
+ );
+
+ case "number":
+ return (
+ <Field key={definition.id} label={definition.label} htmlFor={inputId} optional={optional}>
+ <Input
+ id={inputId}
+ type="number"
+ value={typeof value === "number" ? value : ""}
+ onChange={(e) =>
+ setValue(
+ definition.key,
+ e.target.value === "" ? null : Number(e.target.value)
+ )
+ }
+ disabled={disabled}
+ className={inputClass}
+ />
+ </Field>
+ );
+
+ default:
+ return (
+ <Field key={definition.id} label={definition.label} htmlFor={inputId} optional={optional}>
+ <Input
+ id={inputId}
+ type="text"
+ value={typeof value === "string" ? value : ""}
+ onChange={(e) =>
+ setValue(definition.key, e.target.value === "" ? null : e.target.value)
+ }
+ disabled={disabled}
+ className={inputClass}
+ />
+ </Field>
+ );
+ }
+ })}
+ </div>
+ );
+}
diff --git a/components/custom-field-summary.tsx b/components/custom-field-summary.tsx
new file mode 100644
index 0000000..ddbd08c
--- /dev/null
+++ b/components/custom-field-summary.tsx
@@ -0,0 +1,83 @@
+"use client";
+
+import { useLocale } from "next-intl";
+import { cn } from "@/lib/utils";
+import {
+ formatValueForDisplay,
+ type CustomFieldDefinition,
+ type CustomFieldInputValue,
+} from "@/lib/custom-fields";
+
+type CustomFieldValues = Record<string, CustomFieldInputValue>;
+
+interface VisibleField {
+ definition: CustomFieldDefinition;
+ raw: CustomFieldInputValue;
+}
+
+/** Definitions marked for the calendar, with an actual value — an unticked checkbox is not a value. */
+function visibleFields(
+ values: CustomFieldValues | undefined,
+ definitions: CustomFieldDefinition[]
+): VisibleField[] {
+ if (!values) return [];
+ return definitions
+ .filter((d) => d.showInCalendar)
+ .map((d) => ({ definition: d, raw: values[d.key] }))
+ .filter(
+ (f): f is VisibleField => f.raw !== null && f.raw !== undefined && f.raw !== "" && f.raw !== false
+ );
+}
+
+/**
+ * Whether CustomFieldSummary would render anything for these values.
+ * Shared with the grid row-height calculation so the two never disagree on whether a line is drawn.
+ */
+export function hasVisibleCustomFields(
+ values: CustomFieldValues | undefined,
+ definitions: CustomFieldDefinition[]
+): boolean {
+ return visibleFields(values, definitions).length > 0;
+}
+
+interface CustomFieldSummaryProps {
+ values: CustomFieldValues | undefined;
+ definitions: CustomFieldDefinition[];
+ variant: "detail" | "compact";
+ className?: string;
+}
+
+/**
+ * Read-only render of a shift's calendar-visible custom field values.
+ * "detail" is one line per field (day detail column); "compact" joins everything
+ * into a single truncated line so a grid cell never grows by more than one row.
+ */
+export function CustomFieldSummary({ values, definitions, variant, className }: CustomFieldSummaryProps) {
+ const locale = useLocale();
+ const fields = visibleFields(values, definitions);
+ if (fields.length === 0) return null;
+
+ const rendered = fields.map((f) => ({
+ definition: f.definition,
+ text: formatValueForDisplay(f.definition, String(f.raw), locale),
+ }));
+
+ if (variant === "compact") {
+ return (
+ <span className={cn("block truncate text-[10.5px] leading-[14px] opacity-75", className)}>
+ {rendered.map((e) => `${e.definition.label}: ${e.text}`).join(" · ")}
+ </span>
+ );
+ }
+
+ return (
+ <div className={cn("mt-1 space-y-0.5 text-xs text-fg-secondary", className)}>
+ {rendered.map((e) => (
+ <div key={e.definition.id} className="truncate">
+ <span className="text-fg-tertiary">{e.definition.label}: </span>
+ {e.text}
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/components/custom-fields-panel.tsx b/components/custom-fields-panel.tsx
new file mode 100644
index 0000000..ee4ea80
--- /dev/null
+++ b/components/custom-fields-panel.tsx
@@ -0,0 +1,465 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useTranslations } from "next-intl";
+import {
+ DndContext,
+ closestCenter,
+ KeyboardSensor,
+ PointerSensor,
+ useSensor,
+ useSensors,
+ type DragEndEvent,
+} from "@dnd-kit/core";
+import {
+ SortableContext,
+ arrayMove,
+ sortableKeyboardCoordinates,
+ useSortable,
+ verticalListSortingStrategy,
+} from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+import { GripVertical, Pencil, Plus, Trash2, X } from "lucide-react";
+import { PanelBody, PanelFooter } from "@/components/panel-dialog";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import {
+ Field,
+ ListRow,
+ Pill,
+ RowIconButton,
+ ToggleRow,
+ inputClass,
+} from "@/components/form-kit";
+import { useCustomFields } from "@/hooks/useCustomFields";
+import { useCustomFieldActions } from "@/hooks/useCustomFieldActions";
+import { useCustomFieldForm } from "@/hooks/useCustomFieldForm";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { useReportDirty } from "@/hooks/useDirtyState";
+import { useShifts } from "@/hooks/useShifts";
+import { usePresets } from "@/hooks/usePresets";
+import { CUSTOM_FIELD_TYPES, type CustomFieldDefinition, type CustomFieldType } from "@/lib/custom-fields";
+import { cn } from "@/lib/utils";
+
+interface CustomFieldsPanelProps {
+ calendarId: string;
+ onDirtyChange?: (dirty: boolean) => void;
+}
+
+function useTypeLabels() {
+ const t = useTranslations();
+ const labels: Record<CustomFieldType, string> = {
+ text: t("customFields.typeText"),
+ number: t("customFields.typeNumber"),
+ date: t("customFields.typeDate"),
+ checkbox: t("customFields.typeCheckbox"),
+ select: t("customFields.typeSelect"),
+ };
+ return labels;
+}
+
+function SortableFieldRow({
+ definition,
+ draggable,
+ busy,
+ typeLabels,
+ onEdit,
+ onDelete,
+}: {
+ definition: CustomFieldDefinition;
+ draggable: boolean;
+ busy: boolean;
+ typeLabels: Record<CustomFieldType, string>;
+ onEdit: (definition: CustomFieldDefinition) => void;
+ onDelete: (definition: CustomFieldDefinition) => void;
+}) {
+ const t = useTranslations();
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ setActivatorNodeRef,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({ id: definition.id, disabled: !draggable });
+
+ return (
+ <div
+ ref={setNodeRef}
+ style={{
+ transform: CSS.Transform.toString(transform),
+ transition: isDragging ? undefined : transition,
+ }}
+ className={cn("relative", isDragging && "z-10 opacity-60")}
+ >
+ <ListRow className={cn("gap-2.5 py-2.5 pr-1.5", draggable ? "pl-1.5" : "pl-3.5")}>
+ {draggable && (
+ <button
+ ref={setActivatorNodeRef}
+ type="button"
+ aria-label={t("presetSheet.dragHandle")}
+ className="-my-1 flex h-8 w-6 shrink-0 cursor-grab touch-none items-center justify-center rounded-md text-fg-tertiary transition-colors hover:bg-surface-sunken active:cursor-grabbing"
+ {...attributes}
+ {...listeners}
+ >
+ <GripVertical className="size-4" />
+ </button>
+ )}
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[14px] font-semibold text-fg-strong">
+ {definition.label}
+ </div>
+ <div className="mt-0.5 flex flex-wrap items-center gap-1.5">
+ <span className="font-mono text-[12px] text-fg-tertiary">{definition.key}</span>
+ <Pill>{typeLabels[definition.type]}</Pill>
+ {definition.required && <Pill tone="warning">{t("customFields.requiredLabel")}</Pill>}
+ </div>
+ </div>
+ <RowIconButton
+ icon={Pencil}
+ label={t("preset.edit")}
+ onClick={() => onEdit(definition)}
+ disabled={busy}
+ />
+ <RowIconButton
+ icon={Trash2}
+ tone="danger"
+ label={t("presetSheet.delete")}
+ onClick={() => onDelete(definition)}
+ disabled={busy}
+ />
+ </ListRow>
+ </div>
+ );
+}
+
+/** Calendar settings section for managing the custom field catalog. */
+export function CustomFieldsPanel({ calendarId, onDirtyChange }: CustomFieldsPanelProps) {
+ const t = useTranslations();
+ const typeLabels = useTypeLabels();
+ const permission = useCalendarPermission(calendarId);
+ const canManage = permission.can("manageCustomFields");
+ const { customFields, isLoading } = useCustomFields(calendarId);
+ const { createField, updateField, deleteField, reorderFields } =
+ useCustomFieldActions(calendarId);
+ const { shifts } = useShifts(calendarId);
+ const { presets } = usePresets(calendarId);
+ const form = useCustomFieldForm();
+
+ const [showEditor, setShowEditor] = useState(false);
+ const [isSaving, setIsSaving] = useState(false);
+ const [deletingId, setDeletingId] = useState<string | null>(null);
+ const [deleteTarget, setDeleteTarget] = useState<CustomFieldDefinition | null>(null);
+ const [pendingOrder, setPendingOrder] = useState<string[] | null>(null);
+
+ const ordered = useMemo(() => {
+ if (!pendingOrder) return customFields;
+ const rank = new Map(pendingOrder.map((id, index) => [id, index]));
+ const last = pendingOrder.length;
+ return [...customFields].sort((a, b) => (rank.get(a.id) ?? last) - (rank.get(b.id) ?? last));
+ }, [customFields, pendingOrder]);
+
+ const sensors = useSensors(
+ useSensor(PointerSensor),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
+ );
+
+ const isDirty = showEditor && form.isDirty;
+ useReportDirty(isDirty, onDirtyChange);
+
+ const closeEditor = () => {
+ setShowEditor(false);
+ form.reset();
+ };
+
+ const startCreate = () => {
+ form.startCreate();
+ setShowEditor(true);
+ };
+
+ const startEdit = (definition: CustomFieldDefinition) => {
+ form.startEdit(definition);
+ setShowEditor(true);
+ };
+
+ const saveOrder = async (nextIds: string[]) => {
+ setPendingOrder(nextIds);
+ await reorderFields(nextIds);
+ setPendingOrder((current) => (current === nextIds ? null : current));
+ };
+
+ const handleDragEnd = ({ active, over }: DragEndEvent) => {
+ if (!over || active.id === over.id) return;
+ const ids = ordered.map((f) => f.id);
+ const oldIndex = ids.indexOf(active.id as string);
+ const newIndex = ids.indexOf(over.id as string);
+ if (oldIndex < 0 || newIndex < 0) return;
+ void saveOrder(arrayMove(ids, oldIndex, newIndex));
+ };
+
+ const hasOptions = form.formData.type !== "select" || form.formData.options.length > 0;
+ const canSave =
+ !isSaving &&
+ form.formData.label.trim() !== "" &&
+ !!form.formData.key &&
+ hasOptions &&
+ (form.isNew || form.isDirty);
+
+ const handleSave = async () => {
+ if (!canSave) return;
+ setIsSaving(true);
+ try {
+ const options = form.formData.type === "select" ? form.formData.options : null;
+ if (form.editing) {
+ const success = await updateField(form.editing.id, {
+ label: form.formData.label.trim(),
+ options,
+ required: form.formData.required,
+ showInCalendar: form.formData.showInCalendar,
+ });
+ if (success) closeEditor();
+ } else {
+ const result = await createField({
+ key: form.formData.key,
+ label: form.formData.label.trim(),
+ type: form.formData.type,
+ options,
+ required: form.formData.required,
+ showInCalendar: form.formData.showInCalendar,
+ });
+ if (result === "ok") closeEditor();
+ else if (result === "key-in-use") form.setKeyInUse(true);
+ }
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ const deleteCounts = useMemo(() => {
+ if (!deleteTarget) return { shifts: 0, presets: 0 };
+ const key = deleteTarget.key;
+ return {
+ shifts: shifts.filter((s) => s.customFields?.[key] !== undefined).length,
+ presets: presets.filter((p) => p.customFields?.[key] !== undefined).length,
+ };
+ }, [deleteTarget, shifts, presets]);
+
+ const handleDeleteConfirm = async () => {
+ const target = deleteTarget;
+ if (!target) return;
+ setDeleteTarget(null);
+ setDeletingId(target.id);
+ try {
+ const success = await deleteField(target.id);
+ if (success && form.editing?.id === target.id) closeEditor();
+ } finally {
+ setDeletingId(null);
+ }
+ };
+
+ return (
+ <>
+ <PanelBody>
+ <div className="flex flex-col gap-4">
+ {customFields.length === 0 && !isLoading && (
+ <p className="rounded-[11px] border border-dashed border-control px-4 py-5 text-center text-[13px] text-fg-tertiary">
+ {t("customFields.empty")}
+ </p>
+ )}
+
+ {ordered.length > 0 && (
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
+ <SortableContext
+ items={ordered.map((f) => f.id)}
+ strategy={verticalListSortingStrategy}
+ >
+ <div className="flex flex-col gap-2">
+ {ordered.map((definition) => (
+ <SortableFieldRow
+ key={definition.id}
+ definition={definition}
+ draggable={canManage && ordered.length > 1}
+ busy={deletingId === definition.id}
+ typeLabels={typeLabels}
+ onEdit={startEdit}
+ onDelete={setDeleteTarget}
+ />
+ ))}
+ </div>
+ </SortableContext>
+ </DndContext>
+ )}
+
+ {showEditor && (
+ <div className="flex flex-col gap-4 border-t border-line pt-4">
+ <Field label={t("customFields.labelLabel")} htmlFor="custom-field-label">
+ <Input
+ id="custom-field-label"
+ className={inputClass}
+ value={form.formData.label}
+ onChange={(e) => form.setLabel(e.target.value)}
+ disabled={isSaving}
+ autoFocus
+ />
+ </Field>
+
+ <Field
+ label={t("customFields.keyLabel")}
+ htmlFor="custom-field-key"
+ hint={
+ form.keyInUse ? (
+ <span className="text-danger">{t("customFields.keyInUse")}</span>
+ ) : (
+ t("customFields.keyHint")
+ )
+ }
+ >
+ <Input
+ id="custom-field-key"
+ className={cn(inputClass, "font-mono")}
+ value={form.formData.key}
+ onChange={(e) => form.setKey(e.target.value)}
+ disabled={isSaving || !!form.editing}
+ aria-invalid={form.keyInUse}
+ />
+ </Field>
+
+ <Field
+ label={t("customFields.typeLabel")}
+ htmlFor="custom-field-type"
+ hint={form.editing ? t("customFields.typeImmutableHint") : undefined}
+ >
+ <Select
+ value={form.formData.type}
+ onValueChange={(value) => form.setType(value as CustomFieldType)}
+ disabled={!!form.editing || isSaving}
+ >
+ <SelectTrigger
+ id="custom-field-type"
+ className="h-10 w-full rounded-[9px] px-3 text-[14px] data-[size=default]:h-10"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {CUSTOM_FIELD_TYPES.map((type) => (
+ <SelectItem key={type} value={type}>
+ {typeLabels[type]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+
+ {form.formData.type === "select" && (
+ <Field
+ label={t("customFields.optionsLabel")}
+ hint={
+ form.formData.options.length === 0 ? t("customFields.optionsHint") : undefined
+ }
+ >
+ <div className="flex flex-col gap-2">
+ {form.formData.options.map((option, index) => (
+ <div key={option.id} className="flex items-center gap-2">
+ <Input
+ className={inputClass}
+ value={option.label}
+ onChange={(e) => form.setOptionLabel(index, e.target.value)}
+ disabled={isSaving}
+ />
+ <RowIconButton
+ icon={X}
+ label={t("common.delete")}
+ onClick={() => form.removeOption(index)}
+ disabled={isSaving}
+ />
+ </div>
+ ))}
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-9 self-start font-semibold"
+ onClick={form.addOption}
+ disabled={isSaving}
+ >
+ <Plus className="size-4" />
+ {t("customFields.addOption")}
+ </Button>
+ </div>
+ </Field>
+ )}
+
+ <ToggleRow
+ id="custom-field-required"
+ title={t("customFields.requiredLabel")}
+ description={t("customFields.requiredHint")}
+ checked={form.formData.required}
+ onCheckedChange={form.setRequired}
+ disabled={isSaving}
+ />
+ <ToggleRow
+ id="custom-field-show-in-calendar"
+ title={t("customFields.showInCalendarLabel")}
+ description={t("customFields.showInCalendarHint")}
+ checked={form.formData.showInCalendar}
+ onCheckedChange={form.setShowInCalendar}
+ disabled={isSaving}
+ />
+ </div>
+ )}
+ </div>
+ </PanelBody>
+
+ {(showEditor || canManage) && (
+ <PanelFooter>
+ {showEditor ? (
+ <>
+ <Button
+ type="button"
+ variant="outline"
+ className="h-10 flex-1 font-semibold"
+ onClick={closeEditor}
+ disabled={isSaving}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ className="h-10 flex-1 font-semibold"
+ onClick={handleSave}
+ disabled={!canSave}
+ >
+ {isSaving ? t("common.saving") : t("common.save")}
+ </Button>
+ </>
+ ) : (
+ <Button type="button" className="h-10 w-full font-semibold" onClick={startCreate}>
+ <Plus className="size-4" />
+ {t("customFields.addButton")}
+ </Button>
+ )}
+ </PanelFooter>
+ )}
+
+ <ConfirmationDialog
+ open={!!deleteTarget}
+ onOpenChange={(next) => !next && setDeleteTarget(null)}
+ onConfirm={handleDeleteConfirm}
+ title={t("presetSheet.delete")}
+ description={t("customFields.deleteConfirm", deleteCounts)}
+ cancelText={t("common.cancel")}
+ confirmText={t("common.delete")}
+ confirmVariant="destructive"
+ />
+ </>
+ );
+}
diff --git a/components/day-cell-entries.tsx b/components/day-cell-entries.tsx
index ec7db00..399d27f 100644
--- a/components/day-cell-entries.tsx
+++ b/components/day-cell-entries.tsx
@@ -7,6 +7,8 @@ import { ShiftWithCalendar } from "@/lib/types";
import { CalendarNote, ExternalSync } from "@/lib/db/schema";
import { formatDateToLocal } from "@/lib/date-utils";
import { findNotesForDate } from "@/lib/event-utils";
+import { CustomFieldSummary } from "@/components/custom-field-summary";
+import type { CustomFieldDefinition } from "@/lib/custom-fields";
import {
DayLayoutOptions,
DayShiftLayout,
@@ -242,12 +244,14 @@ export function ShiftChip({
shift,
showNote,
signupsEnabled,
+ customFieldDefinitions = [],
wrap = false,
interactive = false,
}: {
shift: ShiftWithCalendar;
showNote: boolean;
signupsEnabled: boolean;
+ customFieldDefinitions?: CustomFieldDefinition[];
wrap?: boolean;
/** Week view only: the cell is a div, not a button, so a nested signup button is valid here */
interactive?: boolean;
@@ -273,6 +277,11 @@ export function ShiftChip({
{shift.notes}
</span>
)}
+ <CustomFieldSummary
+ values={shift.customFields}
+ definitions={customFieldDefinitions}
+ variant="compact"
+ />
<ChipTime shift={shift} full={wrap} stacked />
</span>
</span>
@@ -291,6 +300,11 @@ export function ShiftChip({
{shift.notes}
</span>
)}
+ <CustomFieldSummary
+ values={shift.customFields}
+ definitions={customFieldDefinitions}
+ variant="compact"
+ />
</span>
<SignupBadge shift={shift} enabled={signupsEnabled} />
{interactive && <QuickSignupButton shift={shift} />}
diff --git a/components/day-detail.tsx b/components/day-detail.tsx
index 69f0811..0155708 100644
--- a/components/day-detail.tsx
+++ b/components/day-detail.tsx
@@ -31,6 +31,8 @@ import { cn, getUserInitials } from "@/lib/utils";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useShiftSignupPermission } from "@/hooks/useShiftSignups";
import { QuickSignupButton } from "@/components/day-cell-entries";
+import { CustomFieldSummary } from "@/components/custom-field-summary";
+import { useCustomFields } from "@/hooks/useCustomFields";
/** Compact avatar stack for who signed up; renders nothing when unused. */
function ShiftSignupBadge({
@@ -136,6 +138,7 @@ export function ShiftDetailRow({
const minutes = getShiftMinutes(shift);
const { signupsEnabled } = useShiftSignupPermission(shift.calendarId);
+ const { customFields: customFieldDefinitions } = useCustomFields(shift.calendarId);
return (
<div
@@ -158,6 +161,11 @@ export function ShiftDetailRow({
{shift.notes}
</div>
)}
+ <CustomFieldSummary
+ values={shift.customFields}
+ definitions={customFieldDefinitions}
+ variant="detail"
+ />
</div>
<ShiftSignupBadge shift={shift} signupsEnabled={signupsEnabled} />
<QuickSignupButton shift={shift} />
diff --git a/components/export-dialog.tsx b/components/export-dialog.tsx
index ad36ad2..097cb81 100644
--- a/components/export-dialog.tsx
+++ b/components/export-dialog.tsx
@@ -68,8 +68,8 @@ export function ExportPanel({
setLoading(true);
try {
const params = new URLSearchParams();
+ params.append("locale", locale);
if (format === "pdf") {
- params.append("locale", locale);
if (range === "month") params.append("month", month);
if (range === "year") params.append("year", year);
}
diff --git a/components/month-grid.tsx b/components/month-grid.tsx
index e137efa..39cf07f 100644
--- a/components/month-grid.tsx
+++ b/components/month-grid.tsx
@@ -22,6 +22,8 @@ import {
useDayPress,
useSignupsEnabled,
} from "@/components/day-cell-entries";
+import { hasVisibleCustomFields } from "@/components/custom-field-summary";
+import { useCustomFields } from "@/hooks/useCustomFields";
const WEEKDAY_KEYS = [
"monday",
@@ -162,6 +164,8 @@ export function MonthGrid({
const locale = useLocale();
const signupsEnabled = useSignupsEnabled();
const dayPress = useDayPress(onDayClick, onDayContextMenu);
+ // All shifts in one grid instance share a calendar; falls back to none while shifts are still loading.
+ const { customFields: customFieldDefinitions } = useCustomFields(shifts[0]?.calendarId ?? null);
const phone = variant === "phone";
const desktop = variant === "desktop";
// 2024-01-01 was a Monday
@@ -245,7 +249,11 @@ export function MonthGrid({
];
const heights = entries.map((entry) => {
if (entry.kind === "shift") {
- return DESKTOP_ROW + (showShiftNotes && entry.shift.notes ? DESKTOP_SUB_LINE : 0);
+ const noteLine = showShiftNotes && entry.shift.notes ? DESKTOP_SUB_LINE : 0;
+ const fieldLine = hasVisibleCustomFields(entry.shift.customFields, customFieldDefinitions)
+ ? DESKTOP_SUB_LINE
+ : 0;
+ return DESKTOP_ROW + noteLine + fieldLine;
}
return entry.kind === "note" ? DESKTOP_PLAIN_ROW : DESKTOP_ROW;
});
@@ -286,6 +294,7 @@ export function MonthGrid({
shift={entry.shift}
showNote={showShiftNotes}
signupsEnabled={signupsEnabled(entry.shift.calendarId)}
+ customFieldDefinitions={customFieldDefinitions}
/>
);
case "external":
diff --git a/components/preset-form.tsx b/components/preset-form.tsx
index eda7577..9fe2767 100644
--- a/components/preset-form.tsx
+++ b/components/preset-form.tsx
@@ -4,13 +4,13 @@ import { Ref, useId } from "react";
import { useTranslations } from "next-intl";
import { Input } from "@/components/ui/input";
import { CheckRow, ColorSwatches, Field, inputClass } from "@/components/form-kit";
-import { ShiftPreset } from "@/lib/db/schema";
+import { CustomFieldInputs } from "@/components/custom-field-inputs";
import { DEFAULT_COLOR } from "@/lib/constants";
-import type { PresetFormData } from "@/hooks/usePresets";
+import type { PresetFormData, ShiftPresetWithValues } from "@/hooks/usePresets";
import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { useCustomFields } from "@/hooks/useCustomFields";
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";
@@ -26,9 +26,10 @@ export const EMPTY_PRESET_FORM: PresetFormData = {
hideFromStats: false,
defaultSignupCapacity: null,
segments: [],
+ customFields: {},
};
-export function presetToFormData(preset: ShiftPreset & { segments?: TimeRange[] }): PresetFormData {
+export function presetToFormData(preset: ShiftPresetWithValues): PresetFormData {
return {
title: preset.title,
startTime: preset.startTime,
@@ -41,15 +42,17 @@ export function presetToFormData(preset: ShiftPreset & { segments?: TimeRange[]
hideFromStats: preset.hideFromStats || false,
defaultSignupCapacity: preset.defaultSignupCapacity ?? null,
segments: preset.segments ?? [],
+ customFields: preset.customFields ?? {},
};
}
export function samePresetForm(a: PresetFormData, b: PresetFormData): boolean {
- const { segments: segmentsA, ...restA } = a;
- const { segments: segmentsB, ...restB } = b;
+ const { segments: segmentsA, customFields: customFieldsA, ...restA } = a;
+ const { segments: segmentsB, customFields: customFieldsB, ...restB } = b;
return (
(Object.keys(restA) as (keyof typeof restA)[]).every((key) => restA[key] === restB[key]) &&
- JSON.stringify(segmentsA) === JSON.stringify(segmentsB)
+ JSON.stringify(segmentsA) === JSON.stringify(segmentsB) &&
+ JSON.stringify(customFieldsA ?? {}) === JSON.stringify(customFieldsB ?? {})
);
}
@@ -66,6 +69,7 @@ interface PresetFormCardProps {
/** Existing group names across this calendar's presets, offered as datalist suggestions. */
existingGroupNames?: string[];
splitShiftsEnabled?: boolean;
+ calendarId?: string;
}
/** "Neue Vorlage" card; the same card edits an existing preset. */
@@ -80,10 +84,12 @@ export function PresetFormCard({
titleRef,
existingGroupNames = [],
splitShiftsEnabled,
+ calendarId,
}: PresetFormCardProps) {
const t = useTranslations();
const id = useId();
const { isAuthEnabled } = useAuthFeatures();
+ const { customFields } = useCustomFields(calendarId ?? null);
const fieldClass = cn(inputClass, "bg-surface-card");
return (
@@ -223,6 +229,20 @@ export function PresetFormCard({
/>
</Field>
+ {customFields.length > 0 && (
+ <div className="flex flex-col gap-3">
+ <div className="text-[13px] font-semibold text-fg-body">
+ {t("customFields.presetDefaultsTitle")}
+ </div>
+ <CustomFieldInputs
+ definitions={customFields}
+ values={value.customFields ?? {}}
+ onChange={(customFields) => onChange({ customFields })}
+ disabled={disabled}
+ />
+ </div>
+ )}
+
{isAuthEnabled && (
<Field
label={t("presetSheet.defaultSignupCapacityLabel")}
diff --git a/components/preset-manage-sheet.tsx b/components/preset-manage-sheet.tsx
index fcb6041..2299a33 100644
--- a/components/preset-manage-sheet.tsx
+++ b/components/preset-manage-sheet.tsx
@@ -241,6 +241,7 @@ export function PresetsPanel({
titleRef={titleRef}
existingGroupNames={existingGroupNames}
splitShiftsEnabled={splitShiftsEnabled}
+ calendarId={calendarId}
/>
)}
</PanelBody>
diff --git a/components/settings-dialog.tsx b/components/settings-dialog.tsx
index 8748998..34552d9 100644
--- a/components/settings-dialog.tsx
+++ b/components/settings-dialog.tsx
@@ -6,6 +6,7 @@ import {
Bell,
Download,
Layers,
+ ListChecks,
Palette,
RefreshCw,
SlidersHorizontal,
@@ -21,6 +22,7 @@ import { ColorSwatches, DangerZone, Field, inputClass } from "@/components/form-
import { ExportPanel } from "@/components/export-dialog";
import { CalendarViewPanel, ViewSettingsState } from "@/components/view-settings-sheet";
import { PresetsPanel } from "@/components/preset-manage-sheet";
+import { CustomFieldsPanel } from "@/components/custom-fields-panel";
import { ExternalSyncPanel } from "@/components/external-sync-manage-sheet";
import { SyncNotificationsPanel } from "@/components/sync-notification-dialog";
import { PermissionsPanel } from "@/components/calendar-permissions-panel";
@@ -42,7 +44,8 @@ export type SettingsSection =
| "permissions"
| "export"
| "view"
- | "notifications";
+ | "notifications"
+ | "customFields";
export interface SettingsItem {
id: SettingsSection;
@@ -216,6 +219,13 @@ export function useCalendarSettings(calendarId: string | null) {
description: t("settings.externalHint", { count: externalSyncs.length }),
meta: externalSyncs.length,
});
+ if (permission.can("manageCustomFields"))
+ items.push({
+ id: "customFields",
+ icon: ListChecks,
+ title: t("customFields.title"),
+ description: t("customFields.description"),
+ });
// S2: the panel is worth opening with either capability — it self-gates each
// section (manageShares for people, manageGuestAccess for guest/links).
if (isAuthEnabled && canOpenPermissions)
@@ -318,6 +328,8 @@ export function CalendarSettingsPanel({
);
case "notifications":
return <SyncNotificationsPanel calendarId={calendarId} onClose={onClose} />;
+ case "customFields":
+ return <CustomFieldsPanel calendarId={calendarId} onDirtyChange={onDirtyChange} />;
}
}
diff --git a/components/shift-form-fields.tsx b/components/shift-form-fields.tsx
index 8a2c9e6..cccaab3 100644
--- a/components/shift-form-fields.tsx
+++ b/components/shift-form-fields.tsx
@@ -11,7 +11,9 @@ import {
textareaClass,
} from "@/components/form-kit";
import { ShiftFormData } from "@/components/shift-sheet";
+import { CustomFieldInputs } from "@/components/custom-field-inputs";
import { useAutoFocusRef } from "@/hooks/useAutoFocus";
+import { useCustomFields } from "@/hooks/useCustomFields";
import { DEFAULT_COLOR } from "@/lib/constants";
import { formatHours } from "@/lib/shift-display";
import { sumRangeDurations, suggestNextTimeRange, validateTimeRanges, toTimeRanges } from "@/lib/time-ranges";
@@ -27,6 +29,9 @@ interface ShiftFormFieldsProps {
isEditing: boolean;
readOnly?: boolean;
splitShiftsEnabled?: boolean;
+ calendarId?: string;
+ /** Externally synced shifts show their custom field values but cannot edit them. */
+ syncedFromExternal?: boolean;
}
const TIME_PATTERN = /^\d{2}:\d{2}$/;
@@ -41,10 +46,14 @@ export function ShiftFormFields({
isEditing,
readOnly = false,
splitShiftsEnabled = false,
+ calendarId,
+ syncedFromExternal = false,
}: ShiftFormFieldsProps) {
const t = useTranslations();
const locale = useLocale();
const titleRef = useAutoFocusRef<HTMLInputElement>(!readOnly);
+ const { customFields } = useCustomFields(calendarId ?? null);
+ const customFieldsDisabled = readOnly || syncedFromExternal;
const validTimes =
!formData.isAllDay &&
@@ -225,6 +234,13 @@ export function ShiftFormFields({
/>
</Field>
+ <CustomFieldInputs
+ definitions={customFields}
+ values={formData.customFields ?? {}}
+ onChange={(customFields) => onFormDataChange({ ...formData, customFields })}
+ disabled={customFieldsDisabled}
+ />
+
{!isEditing && !readOnly && (
<div className="flex flex-col gap-2.5 lg:gap-3">
<CheckRow
diff --git a/components/shift-sheet.tsx b/components/shift-sheet.tsx
index a6c706a..e8683db 100644
--- a/components/shift-sheet.tsx
+++ b/components/shift-sheet.tsx
@@ -14,6 +14,8 @@ 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";
+import { validateFieldValue, type CustomFieldInputValue } from "@/lib/custom-fields";
+import { useCustomFields } from "@/hooks/useCustomFields";
interface ShiftSheetProps {
open: boolean;
@@ -39,6 +41,7 @@ export interface ShiftFormData {
segments?: TimeRange[];
/** New shifts only: people to sign up immediately once the shift is created. */
signupUserIds?: string[];
+ customFields?: Record<string, CustomFieldInputValue>;
}
// presetId is left out: the form never changes it and does not load it
@@ -53,9 +56,16 @@ function snapshot(data: ShiftFormData) {
isAllDay: data.isAllDay || false,
signupCapacity: data.signupCapacity ?? null,
segments: data.segments ?? [],
+ customFields: data.customFields ?? {},
});
}
+/** Whether any custom field carries a user-entered value (used for the new-shift "any data entered" check). */
+function hasCustomFieldEntries(values?: Record<string, CustomFieldInputValue>) {
+ if (!values) return false;
+ return Object.values(values).some((v) => v !== null && v !== undefined && v !== "" && v !== false);
+}
+
export function ShiftSheet({
open,
onOpenChange,
@@ -71,6 +81,7 @@ export function ShiftSheet({
const permission = useCalendarPermission(calendarId);
const { calendars } = useCalendars();
const splitShiftsEnabled = calendars.find((c) => c.id === calendarId)?.splitShiftsEnabled ?? false;
+ const { customFields: customFieldDefinitions } = useCustomFields(calendarId ?? null);
const [isSaving, setIsSaving] = useState(false);
// Determine if sheet should be in read-only mode
@@ -120,6 +131,7 @@ export function ShiftSheet({
isAllDay: shift.isAllDay || false,
signupCapacity: shift.signupCapacity ?? null,
segments: shift.segments ?? [],
+ customFields: shift.customFields ?? {},
})
: null,
[shift]
@@ -136,7 +148,8 @@ export function ShiftSheet({
formData.notes?.trim() !== "" ||
saveAsPreset ||
presetName.trim() !== "" ||
- pendingSignupUserIds.length > 0
+ pendingSignupUserIds.length > 0 ||
+ hasCustomFieldEntries(formData.customFields)
);
};
@@ -184,6 +197,12 @@ export function ShiftSheet({
clearPreset();
};
+ // Same required-field values calendar settings enforce on save — kept in sync
+ // client-side so the button reflects it before the request round-trips.
+ const missingRequiredCustomField = customFieldDefinitions.some(
+ (definition) => !validateFieldValue(definition, formData.customFields?.[definition.key]).ok
+ );
+
const dateLabel = /^\d{4}-\d{2}-\d{2}$/.test(formData.date)
? formatLongDate(parseLocalDate(formData.date), locale, { year: true })
: undefined;
@@ -201,7 +220,8 @@ export function ShiftSheet({
saveDisabled={
!formData.title.trim() ||
(shift && !hasChanges()) ||
- (!formData.isAllDay && !!validateTimeRanges(toTimeRanges(formData)))
+ (!formData.isAllDay && !!validateTimeRanges(toTimeRanges(formData))) ||
+ missingRequiredCustomField
}
saveLabel={shift ? undefined : t("shiftSheet.createAction")}
hasUnsavedChanges={!isReadOnly && hasChanges()}
@@ -228,6 +248,8 @@ export function ShiftSheet({
isEditing={!!shift}
readOnly={isReadOnly}
splitShiftsEnabled={splitShiftsEnabled}
+ calendarId={calendarId}
+ syncedFromExternal={shift?.syncedFromExternal || !!shift?.externalSyncId}
/>
{/* Signups aren't gated by isReadOnly: a read-only member may still
diff --git a/components/week-grid.tsx b/components/week-grid.tsx
index 68da7fd..81af51c 100644
--- a/components/week-grid.tsx
+++ b/components/week-grid.tsx
@@ -20,6 +20,7 @@ import {
useDayPress,
useSignupsEnabled,
} from "@/components/day-cell-entries";
+import { useCustomFields } from "@/hooks/useCustomFields";
interface WeekGridProps {
variant: "desktop" | "phone";
@@ -63,6 +64,8 @@ export function WeekGrid({
const locale = useLocale();
const signupsEnabled = useSignupsEnabled();
const dayPress = useDayPress(onDayClick, onDayContextMenu);
+ // All shifts in one grid instance share a calendar; falls back to none while shifts are still loading.
+ const { customFields: customFieldDefinitions } = useCustomFields(shifts[0]?.calendarId ?? null);
const desktop = variant === "desktop";
const { sortType, sortOrder, combinedSort } = layout;
@@ -100,6 +103,7 @@ export function WeekGrid({
shift={shift}
showNote={showShiftNotes}
signupsEnabled={signupsEnabled(shift.calendarId)}
+ customFieldDefinitions={customFieldDefinitions}
interactive
wrap
/>
diff --git a/docs/PERMISSIONS.md b/docs/PERMISSIONS.md
index 5ee2c7f..ce84102 100644
--- a/docs/PERMISSIONS.md
+++ b/docs/PERMISSIONS.md
@@ -30,7 +30,7 @@ Recommended defaults for a newly created calendar:
| **Read** | View shifts, notes & events, and statistics; sign up for shifts with open slots |
| **Contribute** | Everything in Read, plus: create shifts, stamp presets, create presets, edit/delete shifts, presets, and notes/events you created yourself |
| **Manage** | Everything in Contribute, plus: edit/delete shifts, presets, and notes/events created by anyone, and sign up other people |
-| **Admin** | Everything in Manage, plus: manage external calendar sync, delete sync log entries, manage shares, manage guest access & links, and manage calendar settings |
+| **Admin** | Everything in Manage, plus: manage external calendar sync, delete sync log entries, manage shares, manage guest access & links, manage calendar settings, and manage custom fields |
These are only a starting point. Every capability can be added to or removed from any bundle, including the four starter ones — there's nothing special about them once edited, aside from the translated name.
@@ -68,6 +68,7 @@ The bundle editor groups capabilities by area:
- Manage shares — decide who has access to the calendar, and edit any bundle's contents (see [Who can assign or edit bundles](#who-can-assign-or-edit-bundles))
- Manage guest access — control public access and share links, and edit any bundle's contents
- Manage calendar settings — change the calendar's name, color, and other calendar-wide settings
+- Manage custom fields — define, edit, and delete the calendar's custom fields
### Editing your own vs. anyone's entries
@@ -77,16 +78,19 @@ One rule to keep in mind: an entry with no known creator — imported legacy dat
### Capabilities that can never reach a guest or a link
-Five capabilities can never be granted through guest access or a share link, no matter what an owner ticks into the bundle used there:
+Six capabilities can never be granted through guest access or a share link, no matter what an owner ticks into the bundle used there:
- Manage shares
- Manage guest access
- Manage calendar settings
- Manage external sync
- Delete sync logs
+- Manage custom fields
The bundle picker shown when assigning guest access or a link only offers bundles that don't contain any of these. If you try to add one of them to a bundle that's already assigned to guest access or a link, saving the change is rejected and you're told which assignment is blocking it. This lockout is enforced again on the server independently of what a bundle claims to contain, so it holds even for bundles edited or reassigned later — a guest or link can never end up with administrative or sync-management capabilities by any path.
+Manage custom fields ships only in the Admin bundle's seed for newly created calendars; it is not added to any existing calendar's bundles on upgrade, so an owner who wants contributors to manage custom fields must tick it into a bundle explicitly.
+
### Read access is enforced everywhere
Viewing shifts, notes & events, statistics, and the member list is checked on every request that reads that data, not just used to decide what the interface shows. A bundle without "view statistics", for example, gets the statistics endpoint blocked outright — removing a button from the UI isn't what keeps the underlying data private. As a UX improvement, the client also hides the corresponding controls and summaries (the statistics panel and its button, replaced by a plain "all shifts in month" link when absent, and the preset-stamp bar) when these capabilities are missing, though the server-side enforcement above remains the actual security boundary.
@@ -210,7 +214,7 @@ The per-calendar bundle applies to visitors without an account only while Guest
### Guest Access Bundles
-The "Public access" picker in the Assignments tab only offers bundles that are guest-eligible (see [Capabilities that can never reach a guest or a link](#capabilities-that-can-never-reach-a-guest-or-a-link)) — the Admin bundle and any custom bundle holding one of the five locked capabilities are never offered here. Picking "No access" removes guest access entirely for this calendar.
+The "Public access" picker in the Assignments tab only offers bundles that are guest-eligible (see [Capabilities that can never reach a guest or a link](#capabilities-that-can-never-reach-a-guest-or-a-link)) — the Admin bundle and any custom bundle holding one of the six locked capabilities are never offered here. Picking "No access" removes guest access entirely for this calendar.
### Guest vs. Token Access
@@ -262,7 +266,7 @@ When a user accesses a calendar, BetterShift resolves their capabilities in this
4. **Guest bundle check**: Does the calendar have a guest access bundle assigned, and is `ALLOW_GUEST_ACCESS` enabled? An anonymous visitor gets that bundle directly. A signed-in user who is neither the owner nor explicitly shared only gets it if they're subscribed to the calendar (see [Calendar Discovery](#calendar-discovery)) — a public calendar someone dismissed grants them nothing until they re-subscribe.
5. **No access**: None of the above → access denied.
-The first matching rule determines the bundle, and therefore the capabilities, that apply. Whatever the resolved bundle contains, a token or guest-bundle source additionally has the five guest-locked capabilities filtered out before anything is granted (see [Capabilities that can never reach a guest or a link](#capabilities-that-can-never-reach-a-guest-or-a-link)) — this happens regardless of what the bundle's saved contents claim.
+The first matching rule determines the bundle, and therefore the capabilities, that apply. Whatever the resolved bundle contains, a token or guest-bundle source additionally has the six guest-locked capabilities filtered out before anything is granted (see [Capabilities that can never reach a guest or a link](#capabilities-that-can-never-reach-a-guest-or-a-link)) — this happens regardless of what the bundle's saved contents claim.
---
diff --git a/drizzle/0027_lush_thunderbolt.sql b/drizzle/0027_lush_thunderbolt.sql
new file mode 100644
index 0000000..f30c777
--- /dev/null
+++ b/drizzle/0027_lush_thunderbolt.sql
@@ -0,0 +1,41 @@
+CREATE TABLE `calendar_custom_fields` (
+ `id` text PRIMARY KEY NOT NULL,
+ `calendar_id` text NOT NULL,
+ `key` text NOT NULL,
+ `label` text NOT NULL,
+ `type` text NOT NULL,
+ `options` text,
+ `required` integer DEFAULT false NOT NULL,
+ `show_in_calendar` integer DEFAULT false NOT NULL,
+ `order` integer DEFAULT 0 NOT NULL,
+ `created_by` text,
+ `created_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ `updated_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ FOREIGN KEY (`calendar_id`) REFERENCES `calendars`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`created_by`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE INDEX `calendar_custom_fields_calendarId_idx` ON `calendar_custom_fields` (`calendar_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `calendar_custom_fields_calendarId_key_idx` ON `calendar_custom_fields` (`calendar_id`,`key`);--> statement-breakpoint
+CREATE TABLE `preset_custom_field_values` (
+ `id` text PRIMARY KEY NOT NULL,
+ `preset_id` text NOT NULL,
+ `field_id` text NOT NULL,
+ `value` text NOT NULL,
+ FOREIGN KEY (`preset_id`) REFERENCES `shift_presets`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`field_id`) REFERENCES `calendar_custom_fields`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE INDEX `preset_custom_field_values_presetId_idx` ON `preset_custom_field_values` (`preset_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `preset_custom_field_values_presetId_fieldId_idx` ON `preset_custom_field_values` (`preset_id`,`field_id`);--> statement-breakpoint
+CREATE TABLE `shift_custom_field_values` (
+ `id` text PRIMARY KEY NOT NULL,
+ `shift_id` text NOT NULL,
+ `field_id` text NOT NULL,
+ `value` text NOT NULL,
+ FOREIGN KEY (`shift_id`) REFERENCES `shifts`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`field_id`) REFERENCES `calendar_custom_fields`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE INDEX `shift_custom_field_values_shiftId_idx` ON `shift_custom_field_values` (`shift_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `shift_custom_field_values_shiftId_fieldId_idx` ON `shift_custom_field_values` (`shift_id`,`field_id`);
\ No newline at end of file
diff --git a/drizzle/meta/0027_snapshot.json b/drizzle/meta/0027_snapshot.json
new file mode 100644
index 0000000..57922f1
--- /dev/null
+++ b/drizzle/meta/0027_snapshot.json
@@ -0,0 +1,2512 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "114ad1a7-59d2-4003-8924-65546bb35bba",
+ "prevId": "7f7a7e35-960b-49fd-9301-f136263622a0",
+ "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_custom_fields": {
+ "name": "calendar_custom_fields",
+ "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
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "options": {
+ "name": "options",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "required": {
+ "name": "required",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "show_in_calendar": {
+ "name": "show_in_calendar",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 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": {
+ "calendar_custom_fields_calendarId_idx": {
+ "name": "calendar_custom_fields_calendarId_idx",
+ "columns": [
+ "calendar_id"
+ ],
+ "isUnique": false
+ },
+ "calendar_custom_fields_calendarId_key_idx": {
+ "name": "calendar_custom_fields_calendarId_key_idx",
+ "columns": [
+ "calendar_id",
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "calendar_custom_fields_calendar_id_calendars_id_fk": {
+ "name": "calendar_custom_fields_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_custom_fields",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_custom_fields_created_by_user_id_fk": {
+ "name": "calendar_custom_fields_created_by_user_id_fk",
+ "tableFrom": "calendar_custom_fields",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "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_custom_field_values": {
+ "name": "preset_custom_field_values",
+ "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
+ },
+ "field_id": {
+ "name": "field_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "preset_custom_field_values_presetId_idx": {
+ "name": "preset_custom_field_values_presetId_idx",
+ "columns": [
+ "preset_id"
+ ],
+ "isUnique": false
+ },
+ "preset_custom_field_values_presetId_fieldId_idx": {
+ "name": "preset_custom_field_values_presetId_fieldId_idx",
+ "columns": [
+ "preset_id",
+ "field_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "preset_custom_field_values_preset_id_shift_presets_id_fk": {
+ "name": "preset_custom_field_values_preset_id_shift_presets_id_fk",
+ "tableFrom": "preset_custom_field_values",
+ "tableTo": "shift_presets",
+ "columnsFrom": [
+ "preset_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "preset_custom_field_values_field_id_calendar_custom_fields_id_fk": {
+ "name": "preset_custom_field_values_field_id_calendar_custom_fields_id_fk",
+ "tableFrom": "preset_custom_field_values",
+ "tableTo": "calendar_custom_fields",
+ "columnsFrom": [
+ "field_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_custom_field_values": {
+ "name": "shift_custom_field_values",
+ "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
+ },
+ "field_id": {
+ "name": "field_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "shift_custom_field_values_shiftId_idx": {
+ "name": "shift_custom_field_values_shiftId_idx",
+ "columns": [
+ "shift_id"
+ ],
+ "isUnique": false
+ },
+ "shift_custom_field_values_shiftId_fieldId_idx": {
+ "name": "shift_custom_field_values_shiftId_fieldId_idx",
+ "columns": [
+ "shift_id",
+ "field_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "shift_custom_field_values_shift_id_shifts_id_fk": {
+ "name": "shift_custom_field_values_shift_id_shifts_id_fk",
+ "tableFrom": "shift_custom_field_values",
+ "tableTo": "shifts",
+ "columnsFrom": [
+ "shift_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shift_custom_field_values_field_id_calendar_custom_fields_id_fk": {
+ "name": "shift_custom_field_values_field_id_calendar_custom_fields_id_fk",
+ "tableFrom": "shift_custom_field_values",
+ "tableTo": "calendar_custom_fields",
+ "columnsFrom": [
+ "field_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 983ee41..1c5d8b3 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -190,6 +190,13 @@
"when": 1789470189574,
"tag": "0026_marvelous_firebird",
"breakpoints": true
+ },
+ {
+ "idx": 27,
+ "version": "6",
+ "when": 1789753626628,
+ "tag": "0027_lush_thunderbolt",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/hooks/useCustomFieldActions.ts b/hooks/useCustomFieldActions.ts
new file mode 100644
index 0000000..1467632
--- /dev/null
+++ b/hooks/useCustomFieldActions.ts
@@ -0,0 +1,285 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useTranslations } from "next-intl";
+import { toast } from "sonner";
+import { queryKeys } from "@/lib/query-keys";
+import { ApiError } from "@/lib/api-error";
+import { generateTempId } from "@/lib/utils";
+import type { CustomFieldDefinition, CustomFieldOption, CustomFieldType } from "@/lib/custom-fields";
+import { isRateLimitError, handleRateLimitError } from "@/lib/rate-limit-client";
+
+export interface CreateCustomFieldInput {
+ key: string;
+ label: string;
+ type: CustomFieldType;
+ options: CustomFieldOption[] | null;
+ required: boolean;
+ showInCalendar: boolean;
+}
+
+export interface UpdateCustomFieldInput {
+ label?: string;
+ options?: CustomFieldOption[] | null;
+ required?: boolean;
+ showInCalendar?: boolean;
+}
+
+/** Carries the HTTP status so a create's 409 (key already in use) can be told apart from a generic failure. */
+export class CustomFieldApiError extends ApiError {
+ constructor(message: string, status: number) {
+ super(message, status);
+ this.name = "CustomFieldApiError";
+ }
+}
+
+/** Thrown instead of CustomFieldApiError on a 429 so onError can show the rate-limit toast. */
+class RateLimitError extends Error {
+ constructor(public response: Response) {
+ super("Rate limit exceeded");
+ this.name = "RateLimitError";
+ }
+}
+
+async function parseErrorResponse(response: Response, fallback: string): Promise<never> {
+ if (isRateLimitError(response)) {
+ throw new RateLimitError(response);
+ }
+ const body = await response.json().catch(() => ({}));
+ throw new CustomFieldApiError(body.error || fallback, response.status);
+}
+
+/** True for the create endpoint's 409 on a key collision, so the form can mark the key field. */
+export function isKeyInUse(err: unknown): boolean {
+ return err instanceof CustomFieldApiError && err.status === 409 && err.message === "KEY_IN_USE";
+}
+
+async function createFieldApi(
+ calendarId: string,
+ input: CreateCustomFieldInput
+): Promise<CustomFieldDefinition> {
+ const response = await fetch(`/api/calendars/${calendarId}/custom-fields`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(input),
+ });
+ if (!response.ok) {
+ return parseErrorResponse(response, "Failed to create custom field");
+ }
+ return response.json();
+}
+
+async function updateFieldApi(
+ calendarId: string,
+ fieldId: string,
+ input: UpdateCustomFieldInput
+): Promise<CustomFieldDefinition> {
+ const response = await fetch(`/api/calendars/${calendarId}/custom-fields/${fieldId}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(input),
+ });
+ if (!response.ok) {
+ return parseErrorResponse(response, "Failed to update custom field");
+ }
+ return response.json();
+}
+
+async function deleteFieldApi(calendarId: string, fieldId: string): Promise<void> {
+ const response = await fetch(`/api/calendars/${calendarId}/custom-fields/${fieldId}`, {
+ method: "DELETE",
+ });
+ if (!response.ok) {
+ return parseErrorResponse(response, "Failed to delete custom field");
+ }
+}
+
+async function reorderFieldsApi(calendarId: string, fieldIds: string[]): Promise<void> {
+ const response = await fetch(`/api/calendars/${calendarId}/custom-fields/reorder`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ fieldIds }),
+ });
+ if (!response.ok) {
+ return parseErrorResponse(response, "Failed to reorder custom fields");
+ }
+}
+
+interface MutationContext {
+ previous?: CustomFieldDefinition[];
+}
+
+/**
+ * CRUD for a calendar's custom field catalog, optimistic per the
+ * onMutate/onError/onSettled pattern in hooks/useShifts.ts. Every mutation
+ * invalidates shifts and presets alongside the catalog itself: deleting a
+ * definition cascades its values away, so a stale cache would keep showing
+ * values that no longer exist.
+ */
+export function useCustomFieldActions(calendarId: string) {
+ const t = useTranslations();
+ const queryClient = useQueryClient();
+ const queryKey = queryKeys.customFields.byCalendar(calendarId);
+
+ const invalidate = () => {
+ queryClient.invalidateQueries({ queryKey });
+ queryClient.invalidateQueries({ queryKey: queryKeys.shifts.byCalendar(calendarId) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.presets.byCalendar(calendarId) });
+ };
+
+ const rollback = (context?: MutationContext) => {
+ if (context?.previous) queryClient.setQueryData(queryKey, context.previous);
+ };
+
+ const createMutation = useMutation<
+ CustomFieldDefinition,
+ Error,
+ CreateCustomFieldInput,
+ MutationContext
+ >({
+ mutationFn: (input) => createFieldApi(calendarId, input),
+ onMutate: async (input) => {
+ await queryClient.cancelQueries({ queryKey });
+ const previous = queryClient.getQueryData<CustomFieldDefinition[]>(queryKey);
+ const optimistic: CustomFieldDefinition = {
+ id: `temp-${generateTempId()}`,
+ calendarId,
+ order: previous?.length ?? 0,
+ ...input,
+ };
+ queryClient.setQueryData<CustomFieldDefinition[]>(queryKey, (old = []) => [
+ ...old,
+ optimistic,
+ ]);
+ return { previous };
+ },
+ onError: async (err, _input, context) => {
+ rollback(context);
+ console.error("Failed to create custom field:", err);
+ if (err instanceof RateLimitError) {
+ await handleRateLimitError(err.response, t);
+ return;
+ }
+ // 409 (key already in use) is left for the form to detect via isKeyInUse and
+ // mark the key field inline, so it does not also get the generic toast here.
+ if (!isKeyInUse(err)) {
+ toast.error(t("customFields.saveFailed"));
+ }
+ },
+ onSettled: invalidate,
+ });
+
+ const updateMutation = useMutation<
+ CustomFieldDefinition,
+ Error,
+ { fieldId: string; input: UpdateCustomFieldInput },
+ MutationContext
+ >({
+ mutationFn: ({ fieldId, input }) => updateFieldApi(calendarId, fieldId, input),
+ onMutate: async ({ fieldId, input }) => {
+ await queryClient.cancelQueries({ queryKey });
+ const previous = queryClient.getQueryData<CustomFieldDefinition[]>(queryKey);
+ queryClient.setQueryData<CustomFieldDefinition[]>(queryKey, (old = []) =>
+ old.map((f) => (f.id === fieldId ? { ...f, ...input } : f))
+ );
+ return { previous };
+ },
+ onError: async (err, _variables, context) => {
+ rollback(context);
+ console.error("Failed to update custom field:", err);
+ if (err instanceof RateLimitError) {
+ await handleRateLimitError(err.response, t);
+ return;
+ }
+ toast.error(t("customFields.saveFailed"));
+ },
+ onSettled: invalidate,
+ });
+
+ const deleteMutation = useMutation<void, Error, string, MutationContext>({
+ mutationFn: (fieldId) => deleteFieldApi(calendarId, fieldId),
+ onMutate: async (fieldId) => {
+ await queryClient.cancelQueries({ queryKey });
+ const previous = queryClient.getQueryData<CustomFieldDefinition[]>(queryKey);
+ queryClient.setQueryData<CustomFieldDefinition[]>(queryKey, (old = []) =>
+ old.filter((f) => f.id !== fieldId)
+ );
+ return { previous };
+ },
+ onError: async (err, _fieldId, context) => {
+ rollback(context);
+ console.error("Failed to delete custom field:", err);
+ if (err instanceof RateLimitError) {
+ await handleRateLimitError(err.response, t);
+ return;
+ }
+ toast.error(t("customFields.deleteFailed"));
+ },
+ onSettled: invalidate,
+ });
+
+ const reorderMutation = useMutation<void, Error, string[], MutationContext>({
+ mutationFn: (fieldIds) => reorderFieldsApi(calendarId, fieldIds),
+ onMutate: async (fieldIds) => {
+ await queryClient.cancelQueries({ queryKey });
+ const previous = queryClient.getQueryData<CustomFieldDefinition[]>(queryKey);
+ queryClient.setQueryData<CustomFieldDefinition[]>(queryKey, (old = []) => {
+ const byId = new Map(old.map((f) => [f.id, f]));
+ return fieldIds
+ .map((id, index) => {
+ const field = byId.get(id);
+ return field ? { ...field, order: index } : null;
+ })
+ .filter((f): f is CustomFieldDefinition => f !== null);
+ });
+ return { previous };
+ },
+ onError: async (err, _fieldIds, context) => {
+ rollback(context);
+ console.error("Failed to reorder custom fields:", err);
+ if (err instanceof RateLimitError) {
+ await handleRateLimitError(err.response, t);
+ return;
+ }
+ toast.error(t("customFields.saveFailed"));
+ },
+ onSettled: invalidate,
+ });
+
+ return {
+ // "key-in-use" is distinguished so the form can mark the key field inline without
+ // relying on state from a later render — see the fix-round-1 note in the task report.
+ createField: async (
+ input: CreateCustomFieldInput
+ ): Promise<"ok" | "key-in-use" | "error"> => {
+ try {
+ await createMutation.mutateAsync(input);
+ return "ok";
+ } catch (err) {
+ return isKeyInUse(err) ? "key-in-use" : "error";
+ }
+ },
+ updateField: async (fieldId: string, input: UpdateCustomFieldInput) => {
+ try {
+ await updateMutation.mutateAsync({ fieldId, input });
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ deleteField: async (fieldId: string) => {
+ try {
+ await deleteMutation.mutateAsync(fieldId);
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ reorderFields: async (fieldIds: string[]) => {
+ try {
+ await reorderMutation.mutateAsync(fieldIds);
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ };
+}
diff --git a/hooks/useCustomFieldForm.ts b/hooks/useCustomFieldForm.ts
new file mode 100644
index 0000000..1c64821
--- /dev/null
+++ b/hooks/useCustomFieldForm.ts
@@ -0,0 +1,162 @@
+import { useState } from "react";
+import {
+ normalizeKey,
+ type CustomFieldDefinition,
+ type CustomFieldOption,
+ type CustomFieldType,
+} from "@/lib/custom-fields";
+
+export interface CustomFieldFormData {
+ key: string;
+ label: string;
+ type: CustomFieldType;
+ options: CustomFieldOption[];
+ required: boolean;
+ showInCalendar: boolean;
+}
+
+const EMPTY_FORM: CustomFieldFormData = {
+ key: "",
+ label: "",
+ type: "text",
+ options: [],
+ required: false,
+ showInCalendar: false,
+};
+
+function definitionToForm(definition: CustomFieldDefinition): CustomFieldFormData {
+ return {
+ key: definition.key,
+ label: definition.label,
+ type: definition.type,
+ options: definition.options ?? [],
+ required: definition.required,
+ showInCalendar: definition.showInCalendar,
+ };
+}
+
+function sameForm(a: CustomFieldFormData, b: CustomFieldFormData): boolean {
+ return (
+ a.key === b.key &&
+ a.label === b.label &&
+ a.type === b.type &&
+ a.required === b.required &&
+ a.showInCalendar === b.showInCalendar &&
+ JSON.stringify(a.options) === JSON.stringify(b.options)
+ );
+}
+
+// Not derived from the label (which can be edited freely afterwards): stable and
+// always pattern-valid, unlike a raw generateTempId() which may start with a digit.
+function generateOptionId(): string {
+ return `opt_${Math.random().toString(36).slice(2, 10)}`;
+}
+
+/**
+ * Holds the field definition being created or edited in the catalog sheet.
+ * Follows hooks/useShiftForm.ts's shape: form state plus the transforms the
+ * sheet needs, kept out of the component itself.
+ */
+export function useCustomFieldForm() {
+ const [editing, setEditing] = useState<CustomFieldDefinition | null>(null);
+ const [formData, setFormData] = useState<CustomFieldFormData>(EMPTY_FORM);
+ const [baseline, setBaseline] = useState<CustomFieldFormData>(EMPTY_FORM);
+ const [keyEditedByUser, setKeyEditedByUser] = useState(false);
+ const [keyInUse, setKeyInUse] = useState(false);
+
+ const isNew = editing === null;
+ const isDirty = !sameForm(formData, baseline);
+
+ const startCreate = () => {
+ setEditing(null);
+ setFormData(EMPTY_FORM);
+ setBaseline(EMPTY_FORM);
+ setKeyEditedByUser(false);
+ setKeyInUse(false);
+ };
+
+ const startEdit = (definition: CustomFieldDefinition) => {
+ const data = definitionToForm(definition);
+ setEditing(definition);
+ setFormData(data);
+ setBaseline(data);
+ setKeyEditedByUser(true); // the key input is disabled once a definition exists anyway
+ setKeyInUse(false);
+ };
+
+ const reset = () => {
+ setEditing(null);
+ setFormData(EMPTY_FORM);
+ setBaseline(EMPTY_FORM);
+ setKeyEditedByUser(false);
+ setKeyInUse(false);
+ };
+
+ const setLabel = (label: string) => {
+ setFormData((current) => ({
+ ...current,
+ label,
+ // Auto-derive the key from the label until the user types one themselves.
+ key: isNew && !keyEditedByUser ? normalizeKey(label) ?? "" : current.key,
+ }));
+ setKeyInUse(false);
+ };
+
+ const setKey = (key: string) => {
+ setKeyEditedByUser(true);
+ setFormData((current) => ({ ...current, key }));
+ setKeyInUse(false);
+ };
+
+ const setType = (type: CustomFieldType) => {
+ setFormData((current) => ({
+ ...current,
+ type,
+ options: type === "select" ? current.options : [],
+ }));
+ };
+
+ const setRequired = (required: boolean) =>
+ setFormData((current) => ({ ...current, required }));
+
+ const setShowInCalendar = (showInCalendar: boolean) =>
+ setFormData((current) => ({ ...current, showInCalendar }));
+
+ const addOption = () =>
+ setFormData((current) => ({
+ ...current,
+ options: [...current.options, { id: generateOptionId(), label: "" }],
+ }));
+
+ const setOptionLabel = (index: number, label: string) =>
+ setFormData((current) => ({
+ ...current,
+ options: current.options.map((option, i) => (i === index ? { ...option, label } : option)),
+ }));
+
+ const removeOption = (index: number) =>
+ setFormData((current) => ({
+ ...current,
+ options: current.options.filter((_, i) => i !== index),
+ }));
+
+ return {
+ editing,
+ isNew,
+ formData,
+ isDirty,
+ keyInUse,
+ setKeyInUse,
+ startCreate,
+ startEdit,
+ reset,
+ setLabel,
+ setKey,
+ setType,
+ setRequired,
+ setShowInCalendar,
+ addOption,
+ setOptionLabel,
+ removeOption,
+ };
+}
diff --git a/hooks/useCustomFields.ts b/hooks/useCustomFields.ts
new file mode 100644
index 0000000..89092cc
--- /dev/null
+++ b/hooks/useCustomFields.ts
@@ -0,0 +1,21 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import { queryKeys } from "@/lib/query-keys";
+import type { CustomFieldDefinition } from "@/lib/custom-fields";
+
+async function fetchCustomFields(calendarId: string): Promise<CustomFieldDefinition[]> {
+ const response = await fetch(`/api/calendars/${calendarId}/custom-fields`);
+ if (!response.ok) throw new Error("Failed to fetch custom fields");
+ return response.json();
+}
+
+export function useCustomFields(calendarId: string | null) {
+ const { data, isLoading } = useQuery({
+ queryKey: queryKeys.customFields.byCalendar(calendarId ?? ""),
+ queryFn: () => fetchCustomFields(calendarId as string),
+ enabled: !!calendarId,
+ });
+
+ return { customFields: data ?? [], isLoading };
+}
diff --git a/hooks/usePresets.ts b/hooks/usePresets.ts
index da44736..f084f87 100644
--- a/hooks/usePresets.ts
+++ b/hooks/usePresets.ts
@@ -7,6 +7,7 @@ import { ApiError } from "@/lib/api-error";
import { generateTempId } from "@/lib/utils";
import { useIsCalendarAccessible } from "@/hooks/useCalendars";
import type { TimeRange } from "@/lib/time-ranges";
+import type { CustomFieldInputValue } from "@/lib/custom-fields";
// Form data interface
export interface PresetFormData {
@@ -21,10 +22,20 @@ export interface PresetFormData {
hideFromStats: boolean;
defaultSignupCapacity?: number | null;
segments: TimeRange[];
+ customFields?: Record<string, CustomFieldInputValue>;
}
+/**
+ * A preset row as the API actually returns it: segments and custom field
+ * values are attached at read time and aren't real ShiftPreset columns.
+ */
+export type ShiftPresetWithValues = ShiftPreset & {
+ segments?: TimeRange[];
+ customFields?: Record<string, CustomFieldInputValue>;
+};
+
// API functions
-async function fetchPresetsApi(calendarId: string): Promise<ShiftPreset[]> {
+async function fetchPresetsApi(calendarId: string): Promise<ShiftPresetWithValues[]> {
const params = new URLSearchParams({ calendarId });
const response = await fetch(`/api/presets?${params}`);
@@ -38,7 +49,7 @@ async function fetchPresetsApi(calendarId: string): Promise<ShiftPreset[]> {
async function createPresetApi(
calendarId: string,
formData: PresetFormData
-): Promise<ShiftPreset> {
+): Promise<ShiftPresetWithValues> {
const response = await fetch("/api/presets", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -56,7 +67,7 @@ async function createPresetApi(
async function updatePresetApi(
presetId: string,
formData: PresetFormData
-): Promise<ShiftPreset> {
+): Promise<ShiftPresetWithValues> {
const response = await fetch(`/api/presets/${presetId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
@@ -104,7 +115,7 @@ async function reorderPresetsApi(
function createOptimisticPreset(
calendarId: string,
formData: PresetFormData
-): ShiftPreset & { segments: TimeRange[] } {
+): ShiftPresetWithValues {
return {
id: `temp-${generateTempId()}`,
calendarId,
@@ -119,6 +130,7 @@ function createOptimisticPreset(
hideFromStats: formData.hideFromStats,
defaultSignupCapacity: formData.defaultSignupCapacity ?? null,
segments: formData.segments,
+ customFields: formData.customFields ?? {},
order: 999, // Will be corrected by server
createdBy: null,
createdAt: new Date(),
@@ -158,7 +170,7 @@ export function usePresets(calendarId: string | undefined) {
const optimisticPreset = createOptimisticPreset(calendarId!, formData);
queryClient.setQueryData(
queryKeys.presets.byCalendar(calendarId!),
- (old: ShiftPreset[] = []) => [...old, optimisticPreset]
+ (old: ShiftPresetWithValues[] = []) => [...old, optimisticPreset]
);
return { previous };
},
@@ -201,7 +213,7 @@ export function usePresets(calendarId: string | undefined) {
);
queryClient.setQueryData(
queryKeys.presets.byCalendar(calendarId!),
- (old: ShiftPreset[] = []) =>
+ (old: ShiftPresetWithValues[] = []) =>
old.map((p) =>
p.id === presetId
? {
@@ -247,7 +259,7 @@ export function usePresets(calendarId: string | undefined) {
);
queryClient.setQueryData(
queryKeys.presets.byCalendar(calendarId!),
- (old: ShiftPreset[] = []) => old.filter((p) => p.id !== presetId)
+ (old: ShiftPresetWithValues[] = []) => old.filter((p) => p.id !== presetId)
);
return { previous };
},
@@ -286,7 +298,7 @@ export function usePresets(calendarId: string | undefined) {
// Optimistically reorder
queryClient.setQueryData(
queryKeys.presets.byCalendar(calendarId!),
- (old: ShiftPreset[] = []) => {
+ (old: ShiftPresetWithValues[] = []) => {
const orderMap = new Map(presetOrders.map((po) => [po.id, po.order]));
return [...old].sort((a, b) => {
const orderA = orderMap.get(a.id) ?? a.order;
diff --git a/hooks/useShiftForm.ts b/hooks/useShiftForm.ts
index aa20b8d..42846f1 100644
--- a/hooks/useShiftForm.ts
+++ b/hooks/useShiftForm.ts
@@ -1,11 +1,9 @@
import { useState, useEffect, useRef } from "react";
import { ShiftFormData } from "@/components/shift-sheet";
-import { ShiftPreset } from "@/lib/db/schema";
import { ShiftWithCalendar } from "@/lib/types";
import { formatDateToLocal } from "@/lib/date-utils";
-import { usePresets } from "@/hooks/usePresets";
+import { usePresets, type ShiftPresetWithValues } from "@/hooks/usePresets";
import { DEFAULT_COLOR } from "@/lib/constants";
-import type { TimeRange } from "@/lib/time-ranges";
interface UseShiftFormOptions {
open: boolean;
@@ -35,6 +33,7 @@ export function useShiftForm({
isAllDay: false,
signupCapacity: shift?.signupCapacity ?? null,
segments: shift?.segments ?? [],
+ customFields: shift?.customFields ?? {},
});
const { presets, createPreset } = usePresets(calendarId);
@@ -56,12 +55,13 @@ export function useShiftForm({
isSecondary: false,
hideFromStats: false,
segments: shiftData.segments ?? [],
+ customFields: shiftData.customFields ?? {},
});
return success;
};
- const applyPreset = (preset: ShiftPreset & { segments?: TimeRange[] }) => {
+ const applyPreset = (preset: ShiftPresetWithValues) => {
setFormData({
...formData,
startTime: preset.startTime,
@@ -72,6 +72,9 @@ export function useShiftForm({
isAllDay: preset.isAllDay || false,
signupCapacity: preset.defaultSignupCapacity ?? null,
segments: preset.segments ?? [],
+ // Copied at creation time only — editing the preset afterwards must not
+ // affect shifts already created from it.
+ customFields: preset.customFields ?? {},
});
};
@@ -87,6 +90,7 @@ export function useShiftForm({
isAllDay: false,
signupCapacity: null,
segments: [],
+ customFields: {},
});
};
@@ -103,6 +107,7 @@ export function useShiftForm({
isAllDay: false,
signupCapacity: null,
segments: [],
+ customFields: {},
});
setPresetName("");
setSaveAsPreset(false);
@@ -132,6 +137,7 @@ export function useShiftForm({
isAllDay: shift?.isAllDay || false,
signupCapacity: shift?.signupCapacity ?? null,
segments: shift?.segments ?? [],
+ customFields: shift?.customFields ?? {},
};
// Compare form data fields directly
@@ -145,7 +151,9 @@ export function useShiftForm({
formDataRef.current.isAllDay !== newFormData.isAllDay ||
formDataRef.current.signupCapacity !== newFormData.signupCapacity ||
JSON.stringify(formDataRef.current.segments ?? []) !==
- JSON.stringify(newFormData.segments ?? []);
+ JSON.stringify(newFormData.segments ?? []) ||
+ JSON.stringify(formDataRef.current.customFields ?? {}) !==
+ JSON.stringify(newFormData.customFields ?? {});
if (needsUpdate) {
setFormData(newFormData);
diff --git a/hooks/useShifts.ts b/hooks/useShifts.ts
index 459f024..cb05606 100644
--- a/hooks/useShifts.ts
+++ b/hooks/useShifts.ts
@@ -50,10 +50,8 @@ async function createShiftApi(
});
if (!response.ok) {
- const errorText = await response.text();
- throw new Error(
- `Failed to create shift: ${response.status} ${response.statusText} - ${errorText}`
- );
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || "Failed to create shift");
}
const data = await response.json();
@@ -66,10 +64,8 @@ async function deleteShiftApi(id: string): Promise<void> {
});
if (!response.ok) {
- const errorText = await response.text();
- throw new Error(
- `Failed to delete shift: ${response.status} ${response.statusText} - ${errorText}`
- );
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || "Failed to delete shift");
}
}
@@ -84,10 +80,8 @@ async function updateShiftApi(
});
if (!response.ok) {
- const errorText = await response.text();
- throw new Error(
- `Failed to update shift: ${response.status} ${response.statusText} - ${errorText}`
- );
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || "Failed to update shift");
}
const data = await response.json();
@@ -156,6 +150,7 @@ export function useShifts(calendarId: string | undefined) {
notes: formData.notes || null,
isAllDay: formData.isAllDay || false,
presetId: formData.presetId || null,
+ customFields: formData.customFields ?? {},
calendarId: calendarId!,
createdAt: new Date(),
updatedAt: new Date(),
@@ -178,7 +173,11 @@ export function useShifts(calendarId: string | undefined) {
);
}
console.error("Failed to create shift:", err);
- toast.error(t("common.createError", { item: t("shift.shift_one") }));
+ toast.error(
+ err instanceof Error
+ ? err.message
+ : t("common.createError", { item: t("shift.shift_one") })
+ );
},
onSuccess: () => {
toast.success(t("common.created", { item: t("shift.shift_one") }));
@@ -219,7 +218,11 @@ export function useShifts(calendarId: string | undefined) {
);
}
console.error("Failed to delete shift:", err);
- toast.error(t("common.deleteError", { item: t("shift.shift_one") }));
+ toast.error(
+ err instanceof Error
+ ? err.message
+ : t("common.deleteError", { item: t("shift.shift_one") })
+ );
},
onSuccess: () => {
toast.success(t("common.deleted", { item: t("shift.shift_one") }));
@@ -266,6 +269,7 @@ export function useShifts(calendarId: string | undefined) {
isAllDay: formData.isAllDay || false,
// The edit form never carries presetId — keep the shift's existing value
presetId: formData.presetId ?? s.presetId,
+ customFields: formData.customFields ?? s.customFields,
updatedAt: new Date(),
}
: s
@@ -282,7 +286,11 @@ export function useShifts(calendarId: string | undefined) {
);
}
console.error("Failed to update shift:", err);
- toast.error(t("common.updateError", { item: t("shift.shift_one") }));
+ toast.error(
+ err instanceof Error
+ ? err.message
+ : t("common.updateError", { item: t("shift.shift_one") })
+ );
},
onSuccess: () => {
toast.success(t("common.updated", { item: t("shift.shift_one") }));
diff --git a/lib/audit-log.ts b/lib/audit-log.ts
index 6b7872c..8f859d9 100644
--- a/lib/audit-log.ts
+++ b/lib/audit-log.ts
@@ -193,6 +193,30 @@ export interface CalendarBundleDeletedMetadata {
bundleName: string;
}
+export interface CustomFieldCreatedMetadata {
+ calendarId: string;
+ calendarName: string;
+ fieldKey: string;
+ fieldLabel: string;
+ fieldType: string;
+}
+
+export interface CustomFieldUpdatedMetadata {
+ calendarId: string;
+ calendarName: string;
+ fieldKey: string;
+ fieldLabel: string;
+}
+
+export interface CustomFieldDeletedMetadata {
+ calendarId: string;
+ calendarName: string;
+ fieldKey: string;
+ fieldLabel: string;
+ affectedShifts: number;
+ affectedPresets: number;
+}
+
// Union type for all metadata
export type AuditLogMetadata =
| LoginFailedMetadata
@@ -220,7 +244,10 @@ export type AuditLogMetadata =
| CalendarBundleCreatedMetadata
| CalendarBundleUpdatedMetadata
| CalendarBundleClonedMetadata
- | CalendarBundleDeletedMetadata;
+ | CalendarBundleDeletedMetadata
+ | CustomFieldCreatedMetadata
+ | CustomFieldUpdatedMetadata
+ | CustomFieldDeletedMetadata;
// =====================================================
// Audit Log Types
diff --git a/lib/auth/permissions.ts b/lib/auth/permissions.ts
index d784303..b34f7bc 100644
--- a/lib/auth/permissions.ts
+++ b/lib/auth/permissions.ts
@@ -162,7 +162,8 @@ export interface CalendarAccess {
/**
* Applies the hard ceiling that keeps guest/link access from ever reaching
* administrative capabilities (manageShares, manageGuestAccess,
- * manageCalendarSettings, manageExternalSync, deleteSyncLogs), even if a
+ * manageCalendarSettings, manageExternalSync, deleteSyncLogs,
+ * manageCustomFields), even if a
* bundle was somehow misconfigured to include them — the actual security
* boundary behind GUEST_INELIGIBLE in lib/permission-bundles.ts. Owners get
* every capability; a "share" source is never ceilinged (invited users may
diff --git a/lib/custom-fields.ts b/lib/custom-fields.ts
new file mode 100644
index 0000000..b77c0d4
--- /dev/null
+++ b/lib/custom-fields.ts
@@ -0,0 +1,208 @@
+import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";
+
+export const CUSTOM_FIELD_TYPES = ["text", "number", "date", "checkbox", "select"] as const;
+export type CustomFieldType = (typeof CUSTOM_FIELD_TYPES)[number];
+
+const TYPE_SET: ReadonlySet<string> = new Set(CUSTOM_FIELD_TYPES);
+
+export interface CustomFieldOption {
+ id: string;
+ label: string;
+}
+
+export interface CustomFieldDefinition {
+ id: string;
+ calendarId: string;
+ key: string;
+ label: string;
+ type: CustomFieldType;
+ options: CustomFieldOption[] | null;
+ required: boolean;
+ showInCalendar: boolean;
+ order: number;
+}
+
+export type CustomFieldInputValue = string | number | boolean | null;
+
+export const CUSTOM_FIELD_KEY_MAX = 40;
+export const CUSTOM_FIELD_LABEL_MAX = 60;
+export const CUSTOM_FIELD_TEXT_MAX = 500;
+export const CUSTOM_FIELD_OPTIONS_MAX = 50;
+
+const KEY_PATTERN = /^[a-z][a-z0-9_]*$/;
+const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
+
+/** Lowercases and strips a user-typed key down to [a-z][a-z0-9_]*; null when nothing usable remains. */
+export function normalizeKey(input: unknown): string | null {
+ if (typeof input !== "string") return null;
+ const key = input
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "_")
+ .replace(/^_+|_+$/g, "")
+ .slice(0, CUSTOM_FIELD_KEY_MAX);
+ return KEY_PATTERN.test(key) ? key : null;
+}
+
+/** Converts a client value into the single TEXT column representation; null means "no value". */
+export function serializeValue(type: CustomFieldType, input: unknown): string | null {
+ if (input === null || input === undefined) return null;
+
+ switch (type) {
+ case "text": {
+ if (typeof input !== "string") return null;
+ const text = input.trim().slice(0, CUSTOM_FIELD_TEXT_MAX);
+ return text === "" ? null : text;
+ }
+ case "number": {
+ if (typeof input === "number") {
+ return Number.isFinite(input) ? String(input) : null;
+ }
+ const trimmed = String(input).trim();
+ // Number("") is 0, which would silently satisfy a required field — treat blank as absent.
+ if (trimmed === "") return null;
+ const n = Number(trimmed);
+ return Number.isFinite(n) ? String(n) : null;
+ }
+ case "date": {
+ if (input instanceof Date) return formatDateToLocal(input);
+ if (typeof input !== "string") return null;
+ const date = input.trim();
+ if (!DATE_PATTERN.test(date)) return null;
+ // Round-trip through the local parser so an impossible date (2026-02-31) is rejected.
+ try {
+ return formatDateToLocal(parseLocalDate(date)) === date ? date : null;
+ } catch {
+ return null;
+ }
+ }
+ case "checkbox":
+ if (typeof input === "boolean") return input ? "true" : "false";
+ if (input === "true" || input === "false") return input;
+ return null;
+ case "select": {
+ if (typeof input !== "string") return null;
+ const id = input.trim();
+ return id === "" ? null : id;
+ }
+ }
+}
+
+/** Inverse of serializeValue, for handing a stored value back to a form control. */
+export function parseValue(type: CustomFieldType, raw: string): CustomFieldInputValue {
+ switch (type) {
+ case "number": {
+ const n = Number(raw);
+ return Number.isFinite(n) ? n : null;
+ }
+ case "checkbox":
+ return raw === "true";
+ case "text":
+ case "date":
+ case "select":
+ return raw;
+ }
+}
+
+export function validateFieldValue(
+ definition: CustomFieldDefinition,
+ input: unknown
+): { ok: true; value: string | null } | { ok: false; error: string } {
+ const value = serializeValue(definition.type, input);
+
+ if (value === null) {
+ // A checkbox is never "missing": an unchecked box is a valid answer, not required-empty, and stores no row.
+ if (definition.type === "checkbox") return { ok: true, value: null };
+ if (definition.required) {
+ return { ok: false, error: `Field "${definition.key}" is required` };
+ }
+ return { ok: true, value: null };
+ }
+
+ if (definition.type === "select") {
+ const known = (definition.options ?? []).some((o) => o.id === value);
+ if (!known) {
+ // An option removed from the definition after the value was stored — drop it like an
+ // unknown key, unless the field is required, in which case the gap is a genuine error.
+ if (definition.required) {
+ return { ok: false, error: `Unknown option for field "${definition.key}"` };
+ }
+ return { ok: true, value: null };
+ }
+ }
+
+ return { ok: true, value };
+}
+
+function sanitizeOptions(input: unknown): CustomFieldOption[] | null {
+ if (!Array.isArray(input)) return null;
+ const seen = new Set<string>();
+ const options: CustomFieldOption[] = [];
+ for (const entry of input.slice(0, CUSTOM_FIELD_OPTIONS_MAX)) {
+ if (typeof entry !== "object" || entry === null) continue;
+ const { id, label } = entry as Record<string, unknown>;
+ const optionId = normalizeKey(id);
+ if (!optionId || seen.has(optionId)) continue;
+ if (typeof label !== "string" || label.trim() === "") continue;
+ seen.add(optionId);
+ options.push({ id: optionId, label: label.trim().slice(0, CUSTOM_FIELD_LABEL_MAX) });
+ }
+ return options.length > 0 ? options : null;
+}
+
+/**
+ * Whitelists a definition body from the network. `key` is only returned when
+ * present and valid — PATCH callers must drop it, since key and type are
+ * immutable after creation.
+ */
+export function sanitizeDefinitionInput(input: unknown): {
+ key?: string;
+ label: string;
+ type: CustomFieldType;
+ options: CustomFieldOption[] | null;
+ required: boolean;
+ showInCalendar: boolean;
+} | null {
+ if (typeof input !== "object" || input === null) return null;
+ const src = input as Record<string, unknown>;
+
+ if (typeof src.type !== "string" || !TYPE_SET.has(src.type)) return null;
+ const type = src.type as CustomFieldType;
+
+ if (typeof src.label !== "string") return null;
+ const label = src.label.trim().slice(0, CUSTOM_FIELD_LABEL_MAX);
+ if (label === "") return null;
+
+ const options = type === "select" ? sanitizeOptions(src.options) : null;
+ if (type === "select" && options === null) return null;
+
+ const key = normalizeKey(src.key);
+
+ return {
+ ...(key ? { key } : {}),
+ label,
+ type,
+ options,
+ required: src.required === true,
+ showInCalendar: src.showInCalendar === true,
+ };
+}
+
+/** Human-readable value for read-only surfaces (day detail, grid cells, exports). */
+export function formatValueForDisplay(
+ definition: CustomFieldDefinition,
+ raw: string,
+ locale: string
+): string {
+ switch (definition.type) {
+ case "checkbox":
+ return raw === "true" ? "✓" : "";
+ case "select":
+ return (definition.options ?? []).find((o) => o.id === raw)?.label ?? raw;
+ case "number":
+ return new Intl.NumberFormat(locale).format(Number(raw));
+ case "date":
+ case "text":
+ return raw;
+ }
+}
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 3da6ca1..b769d7b 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -11,6 +11,7 @@ import type {
PersonalViewSettings,
} from "../view-settings";
import type { Capability } from "../permission-bundles";
+import type { CustomFieldOption, CustomFieldType } from "../custom-fields";
// =====================================================
// Better Auth Tables (generated by @better-auth/cli)
@@ -435,6 +436,94 @@ export const presetTimeSegments = sqliteTable(
(table) => [index("preset_time_segments_presetId_idx").on(table.presetId)]
);
+export const calendarCustomFields = sqliteTable(
+ "calendar_custom_fields",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ calendarId: text("calendar_id")
+ .notNull()
+ .references(() => calendars.id, { onDelete: "cascade" }),
+ // Stable API identifier: `shift.customFields[key]`. Immutable once created,
+ // because renaming it would break every consumer reading that key.
+ key: text("key").notNull(),
+ label: text("label").notNull(),
+ type: text("type").notNull().$type<CustomFieldType>(),
+ // Only set for type "select"; null for every other type.
+ options: text("options", { mode: "json" }).$type<CustomFieldOption[]>(),
+ required: integer("required", { mode: "boolean" }).notNull().default(false),
+ showInCalendar: integer("show_in_calendar", { mode: "boolean" })
+ .notNull()
+ .default(false),
+ order: integer("order").notNull().default(0),
+ // null = no known creator, see shifts.createdBy above.
+ createdBy: text("created_by").references(() => user.id, {
+ onDelete: "set null",
+ }),
+ createdAt: integer("created_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ updatedAt: integer("updated_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`)
+ .$onUpdate(() => new Date()),
+ },
+ (table) => [
+ index("calendar_custom_fields_calendarId_idx").on(table.calendarId),
+ uniqueIndex("calendar_custom_fields_calendarId_key_idx").on(
+ table.calendarId,
+ table.key
+ ),
+ ]
+);
+
+export const shiftCustomFieldValues = sqliteTable(
+ "shift_custom_field_values",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ shiftId: text("shift_id")
+ .notNull()
+ .references(() => shifts.id, { onDelete: "cascade" }),
+ fieldId: text("field_id")
+ .notNull()
+ .references(() => calendarCustomFields.id, { onDelete: "cascade" }),
+ value: text("value").notNull(),
+ },
+ (table) => [
+ index("shift_custom_field_values_shiftId_idx").on(table.shiftId),
+ uniqueIndex("shift_custom_field_values_shiftId_fieldId_idx").on(
+ table.shiftId,
+ table.fieldId
+ ),
+ ]
+);
+
+export const presetCustomFieldValues = sqliteTable(
+ "preset_custom_field_values",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ presetId: text("preset_id")
+ .notNull()
+ .references(() => shiftPresets.id, { onDelete: "cascade" }),
+ fieldId: text("field_id")
+ .notNull()
+ .references(() => calendarCustomFields.id, { onDelete: "cascade" }),
+ value: text("value").notNull(),
+ },
+ (table) => [
+ index("preset_custom_field_values_presetId_idx").on(table.presetId),
+ uniqueIndex("preset_custom_field_values_presetId_fieldId_idx").on(
+ table.presetId,
+ table.fieldId
+ ),
+ ]
+);
+
export const calendarNotes = sqliteTable("calendar_notes", {
id: text("id")
.primaryKey()
diff --git a/lib/permission-bundles.ts b/lib/permission-bundles.ts
index a7238f6..9b75d29 100644
--- a/lib/permission-bundles.ts
+++ b/lib/permission-bundles.ts
@@ -36,6 +36,7 @@ export const CAPABILITIES = [
"manageShares",
"manageGuestAccess",
"manageCalendarSettings",
+ "manageCustomFields",
] as const;
export type Capability = (typeof CAPABILITIES)[number];
@@ -72,7 +73,12 @@ export const CAPABILITY_GROUPS: ReadonlyArray<{
{ key: "externalSync", capabilities: ["manageExternalSync", "deleteSyncLogs"] },
{
key: "administration",
- capabilities: ["manageShares", "manageGuestAccess", "manageCalendarSettings"],
+ capabilities: [
+ "manageShares",
+ "manageGuestAccess",
+ "manageCalendarSettings",
+ "manageCustomFields",
+ ],
},
];
@@ -93,6 +99,7 @@ const GUEST_INELIGIBLE: ReadonlySet<Capability> = new Set([
"manageCalendarSettings",
"manageExternalSync",
"deleteSyncLogs",
+ "manageCustomFields",
]);
export function isGuestEligible(capabilities: readonly Capability[]): boolean {
@@ -249,6 +256,7 @@ const ADMIN_BASE: Capability[] = [
"manageShares",
"manageGuestAccess",
"manageCalendarSettings",
+ "manageCustomFields",
];
/**
diff --git a/lib/query-keys.ts b/lib/query-keys.ts
index 1fab139..d5550c4 100644
--- a/lib/query-keys.ts
+++ b/lib/query-keys.ts
@@ -27,6 +27,10 @@ export const queryKeys = {
all: ["presets"] as const,
byCalendar: (calendarId: string) => ["presets", calendarId] as const,
},
+ customFields: {
+ all: ["custom-fields"] as const,
+ byCalendar: (calendarId: string) => ["custom-fields", calendarId] as const,
+ },
notes: {
all: ["notes"] as const,
byCalendar: (calendarId: string) => ["notes", calendarId] as const,
diff --git a/lib/rate-limiter.ts b/lib/rate-limiter.ts
index bc93a35..d6bc2fe 100644
--- a/lib/rate-limiter.ts
+++ b/lib/rate-limiter.ts
@@ -191,6 +191,17 @@ const config = {
parseInt(process.env.RATE_LIMIT_BUNDLE_MUTATIONS_WINDOW || "3600", 10) *
1000, // 1 hour
},
+ // Custom field definition create/update/delete/reorder, keyed per calendar
+ // like bundleMutations — catalog edits are bursty but bounded.
+ customFieldMutations: {
+ requests: parseInt(
+ process.env.RATE_LIMIT_CUSTOM_FIELD_MUTATIONS_REQUESTS || "30",
+ 10
+ ),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_CUSTOM_FIELD_MUTATIONS_WINDOW || "3600", 10) *
+ 1000, // 1 hour
+ },
};
/**
@@ -218,6 +229,7 @@ const limitsByType = {
"admin-bulk-operations": config.adminBulkOperations,
"admin-calendar-mutations": config.adminCalendarMutations,
"bundle-mutations": config.bundleMutations,
+ "custom-field-mutations": config.customFieldMutations,
} as const;
export type RateLimitType = keyof typeof limitsByType;
@@ -423,7 +435,8 @@ export function rateLimit(
if (
(type === "token-creation" ||
type === "external-sync" ||
- type === "bundle-mutations") &&
+ type === "bundle-mutations" ||
+ type === "custom-field-mutations") &&
resourceId
) {
identifier = `calendar:${resourceId}`;
diff --git a/lib/shift-custom-fields.ts b/lib/shift-custom-fields.ts
new file mode 100644
index 0000000..efe0abf
--- /dev/null
+++ b/lib/shift-custom-fields.ts
@@ -0,0 +1,180 @@
+import { db } from "@/lib/db";
+import {
+ calendarCustomFields,
+ shiftCustomFieldValues,
+ presetCustomFieldValues,
+} from "@/lib/db/schema";
+import { asc, eq, inArray } from "drizzle-orm";
+import {
+ parseValue,
+ validateFieldValue,
+ type CustomFieldDefinition,
+ type CustomFieldInputValue,
+} from "@/lib/custom-fields";
+
+type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
+
+export interface CustomFieldValueRow {
+ fieldId: string;
+ value: string;
+}
+
+export async function getCalendarCustomFields(
+ calendarId: string
+): Promise<CustomFieldDefinition[]> {
+ const rows = await db
+ .select()
+ .from(calendarCustomFields)
+ .where(eq(calendarCustomFields.calendarId, calendarId))
+ .orderBy(asc(calendarCustomFields.order));
+
+ return rows.map((row) => ({
+ id: row.id,
+ calendarId: row.calendarId,
+ key: row.key,
+ label: row.label,
+ type: row.type,
+ options: row.options ?? null,
+ required: row.required,
+ showInCalendar: row.showInCalendar,
+ order: row.order,
+ }));
+}
+
+function groupByOwner(
+ rows: { fieldId: string; value: string }[],
+ ownerOf: (row: (typeof rows)[number]) => string,
+ definitions: CustomFieldDefinition[]
+): Map<string, Record<string, CustomFieldInputValue>> {
+ const byId = new Map(definitions.map((d) => [d.id, d]));
+ const result = new Map<string, Record<string, CustomFieldInputValue>>();
+ for (const row of rows) {
+ const definition = byId.get(row.fieldId);
+ if (!definition) continue;
+ const owner = ownerOf(row);
+ const bucket = result.get(owner) ?? {};
+ bucket[definition.key] = parseValue(definition.type, row.value);
+ result.set(owner, bucket);
+ }
+ return result;
+}
+
+/** Attaches each shift's custom field values without N+1 queries. */
+export async function withShiftCustomFields<T extends { id: string }>(
+ rows: T[],
+ definitions: CustomFieldDefinition[]
+): Promise<(T & { customFields: Record<string, CustomFieldInputValue> })[]> {
+ if (rows.length === 0) return [];
+ if (definitions.length === 0) {
+ return rows.map((row) => ({ ...row, customFields: {} }));
+ }
+
+ const values = await db
+ .select()
+ .from(shiftCustomFieldValues)
+ .where(
+ inArray(
+ shiftCustomFieldValues.shiftId,
+ rows.map((r) => r.id)
+ )
+ );
+
+ const byShiftId = groupByOwner(
+ values,
+ (v) => (v as unknown as { shiftId: string }).shiftId,
+ definitions
+ );
+ return rows.map((row) => ({ ...row, customFields: byShiftId.get(row.id) ?? {} }));
+}
+
+/** Attaches each preset's custom field values without N+1 queries. */
+export async function withPresetCustomFields<T extends { id: string }>(
+ rows: T[],
+ definitions: CustomFieldDefinition[]
+): Promise<(T & { customFields: Record<string, CustomFieldInputValue> })[]> {
+ if (rows.length === 0) return [];
+ if (definitions.length === 0) {
+ return rows.map((row) => ({ ...row, customFields: {} }));
+ }
+
+ const values = await db
+ .select()
+ .from(presetCustomFieldValues)
+ .where(
+ inArray(
+ presetCustomFieldValues.presetId,
+ rows.map((r) => r.id)
+ )
+ );
+
+ const byPresetId = groupByOwner(
+ values,
+ (v) => (v as unknown as { presetId: string }).presetId,
+ definitions
+ );
+ return rows.map((row) => ({ ...row, customFields: byPresetId.get(row.id) ?? {} }));
+}
+
+/**
+ * Turns a `{ key: value }` body into rows to persist. Unknown keys are dropped
+ * rather than rejected, so a client holding a stale catalog can still save.
+ * Returns an error only for a value that fails its own definition.
+ */
+export function resolveCustomFieldValues(
+ definitions: CustomFieldDefinition[],
+ input: unknown
+): { values: CustomFieldValueRow[] } | { error: string } {
+ const src =
+ typeof input === "object" && input !== null && !Array.isArray(input)
+ ? (input as Record<string, unknown>)
+ : {};
+
+ const values: CustomFieldValueRow[] = [];
+ for (const definition of definitions) {
+ const result = validateFieldValue(definition, src[definition.key]);
+ if (!result.ok) return { error: result.error };
+ if (result.value !== null) {
+ values.push({ fieldId: definition.id, value: result.value });
+ }
+ }
+ return { values };
+}
+
+/** Replaces every custom field value of one shift (delete-then-insert), inside an existing transaction. */
+export function replaceShiftCustomFieldValues(
+ tx: Tx,
+ shiftId: string,
+ values: CustomFieldValueRow[]
+): void {
+ tx.delete(shiftCustomFieldValues).where(eq(shiftCustomFieldValues.shiftId, shiftId)).run();
+ if (values.length > 0) {
+ tx.insert(shiftCustomFieldValues)
+ .values(values.map((v) => ({ shiftId, fieldId: v.fieldId, value: v.value })))
+ .run();
+ }
+}
+
+/** Replaces every custom field value of one preset (delete-then-insert), inside an existing transaction. */
+export function replacePresetCustomFieldValues(
+ tx: Tx,
+ presetId: string,
+ values: CustomFieldValueRow[]
+): void {
+ tx.delete(presetCustomFieldValues).where(eq(presetCustomFieldValues.presetId, presetId)).run();
+ if (values.length > 0) {
+ tx.insert(presetCustomFieldValues)
+ .values(values.map((v) => ({ presetId, fieldId: v.fieldId, value: v.value })))
+ .run();
+ }
+}
+
+/** Raw values of one preset, for the stampPreset path that must not trust the request body. */
+export async function readPresetCustomFieldValues(
+ presetId: string
+): Promise<CustomFieldValueRow[]> {
+ const rows = await db
+ .select()
+ .from(presetCustomFieldValues)
+ .where(eq(presetCustomFieldValues.presetId, presetId));
+ return rows.map((row) => ({ fieldId: row.fieldId, value: row.value }));
+}
diff --git a/lib/types.ts b/lib/types.ts
index 5997df9..d311211 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -1,5 +1,6 @@
import type { CalendarViewSettings } from "./view-settings";
import type { BundleRef, Capability } from "./permission-bundles";
+import type { CustomFieldInputValue } from "./custom-fields";
// Re-export types from Drizzle schema
export type { Calendar, Shift, ExternalSync } from "./db/schema";
@@ -52,6 +53,8 @@ export interface ShiftWithCalendar {
signups?: ShiftSignupUser[];
/** Additional time ranges beyond startTime/endTime (split shifts). Empty/undefined for a normal shift. */
segments?: { startTime: string; endTime: string }[];
+ /** Values for this calendar's custom fields, keyed by the definition's `key`. Absent when the calendar defines none. */
+ customFields?: Record<string, CustomFieldInputValue>;
// 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 7bdb061..9cd3309 100644
--- a/messages/cs.json
+++ b/messages/cs.json
@@ -1185,7 +1185,8 @@
"deleteSyncLogs": "Mazat protokoly synchronizace",
"manageShares": "Spravovat sdílení",
"manageGuestAccess": "Spravovat hostovský přístup a odkazy",
- "manageCalendarSettings": "Spravovat nastavení kalendáře"
+ "manageCalendarSettings": "Spravovat nastavení kalendáře",
+ "manageCustomFields": "Spravovat vlastní pole"
},
"capabilityHints": {
"viewShifts": "Vidět kalendář a jeho směny",
@@ -1208,7 +1209,37 @@
"deleteSyncLogs": "Mazat záznamy protokolu externí synchronizace",
"manageShares": "Rozhodovat, kdo má přístup ke kalendáři",
"manageGuestAccess": "Řídit veřejný přístup a přístupové odkazy",
- "manageCalendarSettings": "Měnit název, barvu a další nastavení"
+ "manageCalendarSettings": "Měnit název, barvu a další nastavení",
+ "manageCustomFields": "Vytvářet a upravovat další pole pro směny a předvolby"
}
+ },
+ "customFields": {
+ "title": "Vlastní pole",
+ "description": "Další pole pro směny a předlohy tohoto kalendáře",
+ "empty": "Zatím nejsou vytvořena žádná vlastní pole",
+ "addButton": "Přidat pole",
+ "labelLabel": "Popisek",
+ "keyLabel": "Klíč",
+ "keyHint": "Používá se v API a později jej nelze změnit",
+ "keyInUse": "Tento klíč se již používá",
+ "typeLabel": "Typ",
+ "typeImmutableHint": "Typ nelze po vytvoření pole změnit",
+ "typeText": "Text",
+ "typeNumber": "Číslo",
+ "typeDate": "Datum",
+ "typeCheckbox": "Ano/Ne",
+ "typeSelect": "Výběr",
+ "selectNone": "Bez výběru",
+ "optionsLabel": "Možnosti",
+ "optionsHint": "Zadejte alespoň jednu možnost",
+ "addOption": "Přidat možnost",
+ "requiredLabel": "Povinné pole",
+ "requiredHint": "Musí být vyplněno při ukládání směny",
+ "showInCalendarLabel": "Zobrazit v zobrazení kalendáře",
+ "showInCalendarHint": "Zobrazí se ve sloupci dne a kompaktně v buňkách měsíce a týdne",
+ "presetDefaultsTitle": "Výchozí hodnoty",
+ "deleteConfirm": "Toto pole bude smazáno. Hodnoty v {shifts} směnách a {presets} předlohách budou ztraceny.",
+ "saveFailed": "Pole se nepodařilo uložit",
+ "deleteFailed": "Pole se nepodařilo smazat"
}
}
diff --git a/messages/de.json b/messages/de.json
index e258094..c7f2612 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -1185,7 +1185,8 @@
"deleteSyncLogs": "Sync-Protokolle löschen",
"manageShares": "Freigaben verwalten",
"manageGuestAccess": "Gastzugang & Links verwalten",
- "manageCalendarSettings": "Kalendereinstellungen verwalten"
+ "manageCalendarSettings": "Kalendereinstellungen verwalten",
+ "manageCustomFields": "Eigene Felder verwalten"
},
"capabilityHints": {
"viewShifts": "Kalender und Schichten sehen",
@@ -1208,7 +1209,37 @@
"deleteSyncLogs": "Protokolleinträge des externen Syncs löschen",
"manageShares": "Festlegen, wer Zugriff auf den Kalender hat",
"manageGuestAccess": "Öffentlichen Zugriff und Zugangslinks steuern",
- "manageCalendarSettings": "Name, Farbe und weitere Einstellungen ändern"
+ "manageCalendarSettings": "Name, Farbe und weitere Einstellungen ändern",
+ "manageCustomFields": "Zusätzliche Felder für Schichten und Presets anlegen und ändern"
}
+ },
+ "customFields": {
+ "title": "Eigene Felder",
+ "description": "Zusätzliche Felder für Schichten und Presets dieses Kalenders",
+ "empty": "Noch keine eigenen Felder angelegt",
+ "addButton": "Feld hinzufügen",
+ "labelLabel": "Bezeichnung",
+ "keyLabel": "Schlüssel",
+ "keyHint": "Wird in der API verwendet und kann später nicht geändert werden",
+ "keyInUse": "Dieser Schlüssel wird bereits verwendet",
+ "typeLabel": "Typ",
+ "typeImmutableHint": "Der Typ kann nach dem Anlegen nicht mehr geändert werden",
+ "typeText": "Text",
+ "typeNumber": "Zahl",
+ "typeDate": "Datum",
+ "typeCheckbox": "Ja/Nein",
+ "typeSelect": "Auswahl",
+ "selectNone": "Keine Auswahl",
+ "optionsLabel": "Optionen",
+ "optionsHint": "Mindestens eine Option angeben",
+ "addOption": "Option hinzufügen",
+ "requiredLabel": "Pflichtfeld",
+ "requiredHint": "Muss beim Speichern einer Schicht ausgefüllt sein",
+ "showInCalendarLabel": "In der Kalenderansicht anzeigen",
+ "showInCalendarHint": "Erscheint in der Tagesspalte und kompakt in den Monats- und Wochenzellen",
+ "presetDefaultsTitle": "Standardwerte",
+ "deleteConfirm": "Dieses Feld wird gelöscht. Werte in {shifts} Schichten und {presets} Presets gehen dabei verloren.",
+ "saveFailed": "Feld konnte nicht gespeichert werden",
+ "deleteFailed": "Feld konnte nicht gelöscht werden"
}
}
diff --git a/messages/en.json b/messages/en.json
index 971e862..0cfea9c 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -1185,7 +1185,8 @@
"deleteSyncLogs": "Delete sync logs",
"manageShares": "Manage sharing",
"manageGuestAccess": "Manage guest access & links",
- "manageCalendarSettings": "Manage calendar settings"
+ "manageCalendarSettings": "Manage calendar settings",
+ "manageCustomFields": "Manage custom fields"
},
"capabilityHints": {
"viewShifts": "See the calendar and its shifts",
@@ -1208,7 +1209,37 @@
"deleteSyncLogs": "Delete external sync log entries",
"manageShares": "Decide who has access to the calendar",
"manageGuestAccess": "Control public access and access links",
- "manageCalendarSettings": "Change the name, color and other settings"
+ "manageCalendarSettings": "Change the name, color and other settings",
+ "manageCustomFields": "Create and change extra fields for shifts and presets"
}
+ },
+ "customFields": {
+ "title": "Custom fields",
+ "description": "Additional fields for shifts and presets in this calendar",
+ "empty": "No custom fields yet",
+ "addButton": "Add field",
+ "labelLabel": "Label",
+ "keyLabel": "Key",
+ "keyHint": "Used in the API and cannot be changed later",
+ "keyInUse": "This key is already in use",
+ "typeLabel": "Type",
+ "typeImmutableHint": "The type cannot be changed once the field is created",
+ "typeText": "Text",
+ "typeNumber": "Number",
+ "typeDate": "Date",
+ "typeCheckbox": "Yes/No",
+ "typeSelect": "Choice",
+ "selectNone": "No selection",
+ "optionsLabel": "Options",
+ "optionsHint": "Enter at least one option",
+ "addOption": "Add option",
+ "requiredLabel": "Required field",
+ "requiredHint": "Must be filled in when saving a shift",
+ "showInCalendarLabel": "Show in calendar view",
+ "showInCalendarHint": "Appears in the day column and compactly in month and week cells",
+ "presetDefaultsTitle": "Default values",
+ "deleteConfirm": "This field will be deleted. Values in {shifts} shifts and {presets} presets will be lost.",
+ "saveFailed": "Failed to save field",
+ "deleteFailed": "Failed to delete field"
}
}
diff --git a/messages/es.json b/messages/es.json
index 1a4153a..9b6a221 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -1185,7 +1185,8 @@
"deleteSyncLogs": "Eliminar registros de sincronización",
"manageShares": "Gestionar comparticiones",
"manageGuestAccess": "Gestionar acceso de invitados y enlaces",
- "manageCalendarSettings": "Gestionar ajustes del calendario"
+ "manageCalendarSettings": "Gestionar ajustes del calendario",
+ "manageCustomFields": "Gestionar campos personalizados"
},
"capabilityHints": {
"viewShifts": "Ver el calendario y sus turnos",
@@ -1208,7 +1209,37 @@
"deleteSyncLogs": "Eliminar entradas del registro de sincronización externa",
"manageShares": "Decidir quién tiene acceso al calendario",
"manageGuestAccess": "Controlar el acceso público y los enlaces de acceso",
- "manageCalendarSettings": "Cambiar el nombre, color y otros ajustes"
+ "manageCalendarSettings": "Cambiar el nombre, color y otros ajustes",
+ "manageCustomFields": "Crear y modificar campos adicionales para turnos y ajustes preestablecidos"
}
+ },
+ "customFields": {
+ "title": "Campos personalizados",
+ "description": "Campos adicionales para turnos y plantillas de este calendario",
+ "empty": "Aún no hay campos personalizados",
+ "addButton": "Añadir campo",
+ "labelLabel": "Etiqueta",
+ "keyLabel": "Clave",
+ "keyHint": "Se usa en la API y no se puede cambiar más tarde",
+ "keyInUse": "Esta clave ya está en uso",
+ "typeLabel": "Tipo",
+ "typeImmutableHint": "El tipo no se puede cambiar una vez creado el campo",
+ "typeText": "Texto",
+ "typeNumber": "Número",
+ "typeDate": "Fecha",
+ "typeCheckbox": "Sí/No",
+ "typeSelect": "Selección",
+ "selectNone": "Sin selección",
+ "optionsLabel": "Opciones",
+ "optionsHint": "Introduce al menos una opción",
+ "addOption": "Añadir opción",
+ "requiredLabel": "Campo obligatorio",
+ "requiredHint": "Debe completarse al guardar un turno",
+ "showInCalendarLabel": "Mostrar en la vista del calendario",
+ "showInCalendarHint": "Aparece en la columna del día y de forma compacta en las celdas de mes y semana",
+ "presetDefaultsTitle": "Valores predeterminados",
+ "deleteConfirm": "Este campo se eliminará. Se perderán los valores en {shifts} turnos y {presets} plantillas.",
+ "saveFailed": "No se pudo guardar el campo",
+ "deleteFailed": "No se pudo eliminar el campo"
}
}
diff --git a/messages/fr.json b/messages/fr.json
index 3486f55..42ab293 100755
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -1185,7 +1185,8 @@
"deleteSyncLogs": "Supprimer les journaux de synchronisation",
"manageShares": "Gérer les partages",
"manageGuestAccess": "Gérer l'accès invité et les liens",
- "manageCalendarSettings": "Gérer les paramètres du calendrier"
+ "manageCalendarSettings": "Gérer les paramètres du calendrier",
+ "manageCustomFields": "Gérer les champs personnalisés"
},
"capabilityHints": {
"viewShifts": "Voir le calendrier et ses créneaux",
@@ -1208,7 +1209,37 @@
"deleteSyncLogs": "Supprimer les entrées du journal de synchronisation externe",
"manageShares": "Décider qui a accès au calendrier",
"manageGuestAccess": "Contrôler l'accès public et les liens d'accès",
- "manageCalendarSettings": "Modifier le nom, la couleur et d'autres paramètres"
+ "manageCalendarSettings": "Modifier le nom, la couleur et d'autres paramètres",
+ "manageCustomFields": "Créer et modifier des champs supplémentaires pour les services et les préréglages"
}
+ },
+ "customFields": {
+ "title": "Champs personnalisés",
+ "description": "Champs supplémentaires pour les créneaux et modèles de ce calendrier",
+ "empty": "Aucun champ personnalisé pour l'instant",
+ "addButton": "Ajouter un champ",
+ "labelLabel": "Libellé",
+ "keyLabel": "Clé",
+ "keyHint": "Utilisée dans l'API et ne peut plus être modifiée par la suite",
+ "keyInUse": "Cette clé est déjà utilisée",
+ "typeLabel": "Type",
+ "typeImmutableHint": "Le type ne peut plus être modifié une fois le champ créé",
+ "typeText": "Texte",
+ "typeNumber": "Nombre",
+ "typeDate": "Date",
+ "typeCheckbox": "Oui/Non",
+ "typeSelect": "Choix",
+ "selectNone": "Aucune sélection",
+ "optionsLabel": "Options",
+ "optionsHint": "Indiquez au moins une option",
+ "addOption": "Ajouter une option",
+ "requiredLabel": "Champ obligatoire",
+ "requiredHint": "Doit être rempli lors de l'enregistrement d'un créneau",
+ "showInCalendarLabel": "Afficher dans la vue du calendrier",
+ "showInCalendarHint": "Apparaît dans la colonne du jour et de façon compacte dans les cellules du mois et de la semaine",
+ "presetDefaultsTitle": "Valeurs par défaut",
+ "deleteConfirm": "Ce champ va être supprimé. Les valeurs de {shifts} créneaux et {presets} modèles seront perdues.",
+ "saveFailed": "Impossible d'enregistrer le champ",
+ "deleteFailed": "Impossible de supprimer le champ"
}
}
diff --git a/messages/it.json b/messages/it.json
index 31382f7..972cead 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -1185,7 +1185,8 @@
"deleteSyncLogs": "Eliminare i log di sync",
"manageShares": "Gestire le condivisioni",
"manageGuestAccess": "Gestire accesso ospite e link",
- "manageCalendarSettings": "Gestire le impostazioni del calendario"
+ "manageCalendarSettings": "Gestire le impostazioni del calendario",
+ "manageCustomFields": "Gestisci campi personalizzati"
},
"capabilityHints": {
"viewShifts": "Vedere il calendario e i suoi turni",
@@ -1208,7 +1209,37 @@
"deleteSyncLogs": "Eliminare le voci di log del sync esterno",
"manageShares": "Decidere chi ha accesso al calendario",
"manageGuestAccess": "Controllare l'accesso pubblico e i link di accesso",
- "manageCalendarSettings": "Modificare nome, colore e altre impostazioni"
+ "manageCalendarSettings": "Modificare nome, colore e altre impostazioni",
+ "manageCustomFields": "Creare e modificare campi aggiuntivi per turni e preset"
}
+ },
+ "customFields": {
+ "title": "Campi personalizzati",
+ "description": "Campi aggiuntivi per turni e modelli di questo calendario",
+ "empty": "Nessun campo personalizzato ancora",
+ "addButton": "Aggiungi campo",
+ "labelLabel": "Etichetta",
+ "keyLabel": "Chiave",
+ "keyHint": "Usata nell'API e non può essere modificata in seguito",
+ "keyInUse": "Questa chiave è già in uso",
+ "typeLabel": "Tipo",
+ "typeImmutableHint": "Il tipo non può più essere modificato dopo la creazione del campo",
+ "typeText": "Testo",
+ "typeNumber": "Numero",
+ "typeDate": "Data",
+ "typeCheckbox": "Sì/No",
+ "typeSelect": "Selezione",
+ "selectNone": "Nessuna selezione",
+ "optionsLabel": "Opzioni",
+ "optionsHint": "Inserisci almeno un'opzione",
+ "addOption": "Aggiungi opzione",
+ "requiredLabel": "Campo obbligatorio",
+ "requiredHint": "Deve essere compilato al salvataggio di un turno",
+ "showInCalendarLabel": "Mostra nella vista calendario",
+ "showInCalendarHint": "Compare nella colonna del giorno e in forma compatta nelle celle di mese e settimana",
+ "presetDefaultsTitle": "Valori predefiniti",
+ "deleteConfirm": "Questo campo verrà eliminato. I valori in {shifts} turni e {presets} modelli andranno persi.",
+ "saveFailed": "Impossibile salvare il campo",
+ "deleteFailed": "Impossibile eliminare il campo"
}
}