Your favorite shift management application!
feat: replace calendar permission ladder with capability bundles (#199)
panteLaacb84be8806
diff --git a/.env.example b/.env.exampleindex 9f9c53f..df58e07 100644--- a/.env.example+++ b/.env.example@@ -231,6 +231,10 @@ ALLOW_USER_REGISTRATION=true # Enable/disable new user signups# RATE_LIMIT_TOKEN_CREATION_REQUESTS=10 # Per calendar# RATE_LIMIT_TOKEN_CREATION_WINDOW=3600 # 1 hour+# Permission Bundles (per calendar)+# RATE_LIMIT_BUNDLE_MUTATIONS_REQUESTS=30 # Bundle create/update/delete/clone+# RATE_LIMIT_BUNDLE_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 minutediff --git a/CLAUDE.md b/CLAUDE.mdindex 99ff891..2ee775a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -60,13 +60,13 @@ View preferences (shifts per day, sorting, note visibility, day highlighting) coTwo independent questions, easy to conflate:-**May the user do X?** `getUserCalendarPermission()` in `lib/auth/permissions.ts` resolves, in priority order: owner → `calendarShares` row → access-token cookie → `calendar.guestPermission`. That last step is not unconditional for a signed-in user: it applies only when a `userCalendarSubscriptions` row with `status: "subscribed"` exists, so a public calendar someone dismissed grants them nothing until they re-subscribe. Guests reach `guestPermission` without that check. In routes call the wrappers `canViewCalendar` / `canEditCalendar` / `canManageCalendar` / `canDeleteCalendar` instead of touching the tables.+**May the user do X?** `resolveCalendarAccess()` in `lib/auth/permissions.ts` resolves, in priority order: owner → `calendarShares` row → access-token cookie → `calendars.guestBundleId`. There's no fixed read/write/admin ladder — every non-owner branch resolves to a **permission bundle** (`calendarPermissionBundles`, an owner-defined per-calendar set of ticked capabilities; catalog, dependencies and defaults live in `lib/permission-bundles.ts`, full design in `docs/PERMISSIONS.md`). The guest-bundle step is not unconditional for a signed-in user: it applies only when a `userCalendarSubscriptions` row with `status: "subscribed"` exists, so a public calendar someone dismissed grants them nothing until they re-subscribe. Guests reach `guestBundleId` without that check. Whatever the resolved bundle contains, a token or guest-bundle source additionally has `manageShares`/`manageGuestAccess`/`manageCalendarSettings`/`manageExternalSync`/`deleteSyncLogs` filtered out — the hard guest lockout (`GUEST_INELIGIBLE`/`isGuestEligible()` in `lib/permission-bundles.ts`), re-enforced here regardless of what a bundle's saved contents claim. Call `getCalendarAccess(userId, calendarId)` once per request for `can(capability)` / `canOwned(own, any, createdBy)`; `hasCapability()` / `hasOwnedCapability()` are single-check wrappers around it. `canOwned()` treats a resource with no known creator (legacy data, a deleted user, an anonymous guest's entry) as owned by anyone holding the matching own-capability. In routes, `canViewCalendar` (any access at all) and `canDeleteCalendar` (owner-only) remain as wrappers — there's no `canEditCalendar`/`canManageCalendar` anymore, since a coarse level can't express a specific capability or an own/any check; call `hasCapability()`/`hasOwnedCapability()` for the capability the action actually needs.-**Does the calendar show up in their list?** `getUserAccessibleCalendars()` applies `userCalendarSubscriptions` across the board, not just on the guest-permission branch above. Shared and publicly visible calendars can be dismissed by a user (`status: "dismissed"`), the calendar-discovery sheet lets them re-subscribe, and owned calendars can never be hidden. A permission check alone therefore does not tell you whether a calendar is visible.+**Does the calendar show up in their list?** `getUserAccessibleCalendars()` applies `userCalendarSubscriptions` across the board, not just on the guest-bundle branch above. Shared and publicly visible calendars can be dismissed by a user (`status: "dismissed"`), the calendar-discovery sheet lets them re-subscribe, and owned calendars can never be hidden. A capability check alone therefore does not tell you whether a calendar is visible.`AUTH_ENABLED=false` short-circuits both: every calendar becomes `owner` for everyone. Gate on `isAuthEnabled()` / `allowGuestAccess()` from `lib/auth/feature-flags.ts` rather than assuming a session exists.-Access tokens (`calendarAccessTokens`) are shareable links. `lib/auth/token-auth.ts` validates them and stores grants in a cookie that both the middleware and the API routes read back.+Access tokens (`calendarAccessTokens`) are shareable links, each carrying a `bundleId` (guest-eligible bundles only — checked at assignment time). `lib/auth/token-auth.ts` validates them and stores grants in a cookie that both the middleware and the API routes read back.### Admindiff --git a/app/api/activity-logs/route.ts b/app/api/activity-logs/route.tsindex 6efab09..0b67a29 100644--- a/app/api/activity-logs/route.ts+++ b/app/api/activity-logs/route.ts@@ -2,10 +2,7 @@ import { NextRequest, NextResponse } from "next/server";import { db } from "@/lib/db";import { auditLogs, syncLogs } from "@/lib/db/schema";import { getSessionUser } from "@/lib/auth/sessions";-import {- getUserAccessibleCalendars,- type CalendarPermission,-} from "@/lib/auth/permissions";+import { getUserAccessibleCalendars } from "@/lib/auth/permissions";import { eq, and, desc, gte, lte, inArray, sql } from "drizzle-orm";import { parseLocalDate } from "@/lib/date-utils";@@ -266,16 +263,33 @@ export async function DELETE(request: NextRequest) {// history. That matches what write access already allows (editing and// deleting the shifts those logs describe), but it is a deliberate// boundary rather than a per-user delete.- const editablePermissions: CalendarPermission[] = [- "owner",- "admin",- "write",- ];const accessibleCalendars = await getUserAccessibleCalendars(user.id);- const calendarIds = accessibleCalendars- .filter((cal) => editablePermissions.includes(cal.permission))+ const accessibleIds = new Set(accessibleCalendars.map((cal) => cal.id));+ const ownerCalendarIds = accessibleCalendars+ .filter((cal) => cal.isOwner).map((cal) => cal.id);+ // deleteSyncLogs is guest-ineligible (GUEST_INELIGIBLE in+ // lib/permission-bundles.ts), so only owner and share sources can ever+ // grant it — batch the share/bundle lookup instead of resolving access+ // per calendar.+ const shareRows = await db.query.calendarShares.findMany({+ where: (shares, { eq: eqOp }) => eqOp(shares.userId, user.id),+ columns: { calendarId: true },+ with: { bundle: { columns: { capabilities: true } } },+ });+ const shareCalendarIds = shareRows+ .filter(+ (share) =>+ accessibleIds.has(share.calendarId) &&+ share.bundle.capabilities.includes("deleteSyncLogs")+ )+ .map((share) => share.calendarId);++ const calendarIds = Array.from(+ new Set([...ownerCalendarIds, ...shareCalendarIds])+ );+if (calendarIds.length > 0) {await db.delete(syncLogs)diff --git a/app/api/admin/calendars/[id]/bundles/route.ts b/app/api/admin/calendars/[id]/bundles/route.tsnew file mode 100644index 0000000..d347915--- /dev/null+++ b/app/api/admin/calendars/[id]/bundles/route.ts@@ -0,0 +1,62 @@+import { NextRequest, NextResponse } from "next/server";+import { requireAdmin, siteAdminCanEditCalendar } from "@/lib/auth/admin";+import {+ getValidatedAdminUser,+ isErrorResponse,+} from "@/lib/auth/admin-helpers";+import { listBundlesWithUsage } from "@/lib/auth/permission-bundles-service";++interface RouteParams {+ params: Promise<{+ id: string;+ }>;+}++/**+ * GET /api/admin/calendars/[id]/bundles+ *+ * Lists a calendar's permission bundles for the admin panel's guest-access+ * picker (Paket 6 of .LOCAL/calendar-permission-bundles-plan.md). Read-only —+ * bundle content editing stays exclusive to the owner-facing panel, so this+ * is gated on site-admin edit rights rather than the owner-facing+ * `manageShares` capability, which a site admin managing someone else's+ * calendar generally won't have.+ *+ * Permission: Admin or Superadmin only+ */+export async function GET(+ request: NextRequest,+ { params }: RouteParams+): Promise<NextResponse> {+ try {+ const { id: calendarId } = await params;+ const currentUser = await getValidatedAdminUser(request);+ if (isErrorResponse(currentUser)) return currentUser;++ requireAdmin(currentUser);++ if (!siteAdminCanEditCalendar(currentUser)) {+ return NextResponse.json(+ { error: "Insufficient permissions" },+ { status: 403 }+ );+ }++ const bundles = await listBundlesWithUsage(calendarId);+ return NextResponse.json(bundles);+ } catch (error) {+ console.error("[Admin Calendar Bundles API] Error:", error);++ if (error instanceof Error && error.message === "Admin access required") {+ return NextResponse.json(+ { error: "Admin access required" },+ { status: 403 }+ );+ }++ return NextResponse.json(+ { error: "Failed to fetch permission bundles" },+ { status: 500 }+ );+ }+}diff --git a/app/api/admin/calendars/[id]/route.ts b/app/api/admin/calendars/[id]/route.tsindex 50c9ee3..4f016be 100644--- a/app/api/admin/calendars/[id]/route.ts+++ b/app/api/admin/calendars/[id]/route.ts@@ -16,8 +16,8 @@ import { eq, sql } from "drizzle-orm";import {requireAdmin,requireSuperAdmin,- canEditCalendar,- canDeleteCalendar,+ siteAdminCanEditCalendar,+ siteAdminCanDeleteCalendar,} from "@/lib/auth/admin";import { logAuditEvent } from "@/lib/audit-log";import { rateLimit } from "@/lib/rate-limiter";@@ -25,6 +25,10 @@ import {getValidatedAdminUser,isErrorResponse,} from "@/lib/auth/admin-helpers";+import {+ getBundleForCalendar,+ resolveGuestEligibleBundle,+} from "@/lib/auth/permission-bundles-service";/*** Admin Calendar Detail API@@ -33,7 +37,7 @@ import {* Returns detailed information about a specific calendar.** PATCH /api/admin/calendars/[id]- * Updates calendar information (name, color, guestPermission).+ * Updates calendar information (name, color, guestBundleId).* - Admin & Superadmin: Can update calendars* - Cannot change ownerId via PATCH (use transfer endpoint)*@@ -68,7 +72,7 @@ export async function GET(name: calendarsTable.name,color: calendarsTable.color,ownerId: calendarsTable.ownerId,- guestPermission: calendarsTable.guestPermission,+ guestBundleId: calendarsTable.guestBundleId,createdAt: sql<string>`${calendarsTable.createdAt}`,updatedAt: sql<string>`${calendarsTable.updatedAt}`,ownerName: userTable.name,@@ -112,7 +116,7 @@ export async function GET(.select({id: calendarSharesTable.id,userId: calendarSharesTable.userId,- permission: calendarSharesTable.permission,+ bundleId: calendarSharesTable.bundleId,createdAt: calendarSharesTable.createdAt,userName: userTable.name,userEmail: userTable.email,@@ -127,7 +131,7 @@ export async function GET(.select({id: tokensTable.id,name: tokensTable.name,- permission: tokensTable.permission,+ bundleId: tokensTable.bundleId,createdAt: sql<string>`${tokensTable.createdAt}`,}).from(tokensTable)@@ -174,6 +178,28 @@ export async function GET(.from(externalSyncsTable).where(eq(externalSyncsTable.calendarId, calendarId));+ // Batch-resolve every bundle involved (guest, shares, tokens) to its+ // {id, name, seedKey} for display — the admin panel now shows the+ // owner-defined bundle directly instead of a collapsed read/write/admin+ // tier (Paket 6). Shares/tokens always resolve (bundleId is a restrict+ // FK); a guest bundle can be orphaned (no FK, see 4.2 in the plan) and+ // then correctly falls back to null, i.e. "no guest access".+ const bundleIds = new Set<string>();+ if (calendar.guestBundleId) bundleIds.add(calendar.guestBundleId);+ for (const s of shares) bundleIds.add(s.bundleId);+ for (const t of shareTokens) bundleIds.add(t.bundleId);+ const bundleRows =+ bundleIds.size > 0+ ? await db.query.calendarPermissionBundles.findMany({+ where: (b, { inArray }) => inArray(b.id, Array.from(bundleIds)),+ columns: { id: true, name: true, seedKey: true },+ })+ : [];+ const bundleById = new Map(bundleRows.map((b) => [b.id, b]));+ const guestBundle = calendar.guestBundleId+ ? (bundleById.get(calendar.guestBundleId) ?? null)+ : null;+return NextResponse.json({id: calendar.id,name: calendar.name,@@ -186,7 +212,7 @@ export async function GET(image: calendar.ownerImage,}: null,- guestPermission: calendar.guestPermission,+ guestBundle,createdAt: calendar.createdAt ? new Date(calendar.createdAt) : new Date(),updatedAt: calendar.updatedAt ? new Date(calendar.updatedAt) : new Date(),shiftsCount: Number(shiftCount?.count || 0),@@ -200,12 +226,12 @@ export async function GET(userName: s.userName || "",userEmail: s.userEmail || "",userImage: s.userImage,- permission: s.permission,+ bundle: bundleById.get(s.bundleId) ?? { id: s.bundleId, name: "?", seedKey: null },})),shareTokens: shareTokens.map((t) => ({id: t.id,name: t.name,- permission: t.permission,+ bundle: bundleById.get(t.bundleId) ?? { id: t.bundleId, name: "?", seedKey: null },createdAt: t.createdAt ? new Date(t.createdAt) : new Date(),})),externalSyncs: externalSyncsWithLastSync,@@ -246,7 +272,7 @@ export async function PATCH();if (rateLimitResponse) return rateLimitResponse;- if (!canEditCalendar(currentUser)) {+ if (!siteAdminCanEditCalendar(currentUser)) {return NextResponse.json({ error: "Insufficient permissions" },{ status: 403 }@@ -270,8 +296,9 @@ export async function PATCH(const updates: {name?: string;color?: string;- guestPermission?: "none" | "read" | "write";+ guestBundleId?: string | null;} = {};+ const changes: string[] = [];// Validate and collect allowed updatesif (body.name !== undefined) {@@ -282,6 +309,7 @@ export async function PATCH();}updates.name = body.name.trim();+ changes.push("name");}if (body.color !== undefined) {@@ -292,16 +320,29 @@ export async function PATCH();}updates.color = body.color;+ changes.push("color");}- if (body.guestPermission !== undefined) {- if (!["none", "read", "write"].includes(body.guestPermission)) {+ let newGuestBundle: Awaited<ReturnType<typeof resolveGuestEligibleBundle>> | null =+ null;+ if (body.guestBundleId !== undefined) {+ if (body.guestBundleId === null) {+ updates.guestBundleId = null;+ } else if (typeof body.guestBundleId === "string") {+ newGuestBundle = await resolveGuestEligibleBundle(+ calendarId,+ body.guestBundleId,+ "Bundle contains capabilities that cannot be granted to guests"+ );+ if (newGuestBundle instanceof NextResponse) return newGuestBundle;+ updates.guestBundleId = body.guestBundleId;+ } else {return NextResponse.json(- { error: "Invalid guest permission" },+ { error: "Invalid guestBundleId" },{ status: 400 });}- updates.guestPermission = body.guestPermission;+ changes.push("guestBundleId");}// Don't allow ownerId changes via PATCH (use transfer endpoint)@@ -327,7 +368,6 @@ export async function PATCH(.returning();// Audit log- const changes = Object.keys(updates);await logAuditEvent({request,action: "admin.calendar.update",@@ -340,14 +380,30 @@ export async function PATCH(oldValues: {name: calendar.name,color: calendar.color,- guestPermission: calendar.guestPermission,+ guestBundleId: calendar.guestBundleId,},newValues: updates,updatedBy: currentUser.email,},});- return NextResponse.json(updatedCalendar);+ // Reuse the already-validated bundle when this request set it, instead+ // of re-fetching the same row.+ let guestBundle: { id: string; name: string; seedKey: string | null } | null = null;+ if (newGuestBundle) {+ guestBundle = {+ id: newGuestBundle.id,+ name: newGuestBundle.name,+ seedKey: newGuestBundle.seedKey,+ };+ } else if (updatedCalendar.guestBundleId) {+ const bundle = await getBundleForCalendar(calendarId, updatedCalendar.guestBundleId);+ guestBundle = bundle ? { id: bundle.id, name: bundle.name, seedKey: bundle.seedKey } : null;+ }++ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- dropping guestBundleId in favor of the guestBundle object below+ const { guestBundleId: _guestBundleId, ...calendarResponse } = updatedCalendar;+ return NextResponse.json({ ...calendarResponse, guestBundle });} catch (error) {console.error("[Admin Calendar Update API] Error:", error);@@ -392,7 +448,7 @@ export async function DELETE();if (rateLimitResponse) return rateLimitResponse;- if (!canDeleteCalendar(currentUser)) {+ if (!siteAdminCanDeleteCalendar(currentUser)) {return NextResponse.json({ error: "Insufficient permissions" },{ status: 403 }diff --git a/app/api/admin/calendars/bulk-delete/route.ts b/app/api/admin/calendars/bulk-delete/route.tsindex 752ffce..7142fb2 100644--- a/app/api/admin/calendars/bulk-delete/route.ts+++ b/app/api/admin/calendars/bulk-delete/route.ts@@ -12,7 +12,10 @@ import {calendarAccessTokens as tokensTable,} from "@/lib/db/schema";import { inArray, sql } from "drizzle-orm";-import { requireSuperAdmin, canDeleteCalendar } from "@/lib/auth/admin";+import {+ requireSuperAdmin,+ siteAdminCanDeleteCalendar,+} from "@/lib/auth/admin";import { logAuditEvent } from "@/lib/audit-log";import { rateLimit } from "@/lib/rate-limiter";import {@@ -47,7 +50,7 @@ export async function POST(request: NextRequest): Promise<NextResponse> {);if (rateLimitResponse) return rateLimitResponse;- if (!canDeleteCalendar(currentUser)) {+ if (!siteAdminCanDeleteCalendar(currentUser)) {return NextResponse.json({ error: "Insufficient permissions" },{ status: 403 }diff --git a/app/api/admin/calendars/route.ts b/app/api/admin/calendars/route.tsindex 6307c92..4d91818 100644--- a/app/api/admin/calendars/route.ts+++ b/app/api/admin/calendars/route.ts@@ -8,10 +8,15 @@ import {shiftPresets,calendarShares,calendarAccessTokens,+ calendarPermissionBundles,externalSyncs,} from "@/lib/db/schema";import { and, asc, count, desc, eq, or, sql, type SQL } from "drizzle-orm";-import type { SQLiteColumn, SQLiteTable } from "drizzle-orm/sqlite-core";+import {+ alias,+ type SQLiteColumn,+ type SQLiteTable,+} from "drizzle-orm/sqlite-core";import { isAdmin } from "@/lib/auth/admin";import {getValidatedAdminUser,@@ -36,6 +41,13 @@ const hasTokens = sql`exists (select 1 from ${calendarAccessTokens} where ${caleconst hasSyncs = sql`exists (select 1 from ${externalSyncs} where ${externalSyncs.calendarId} = ${calendars.id})`;const isShared = sql`(${hasUserShares} or ${hasTokens})`;+// The admin panel shows the guest bundle's actual name/seedKey instead of+// collapsing it to a read/write tier. The join also doubles as the "has+// guest access" check for sorting/filtering — an orphaned guestBundleId+// (pointing at a deleted bundle) produces a null row here, which correctly+// counts as no guest access, same as getUserAccessibleCalendars() elsewhere.+const guestBundleTable = alias(calendarPermissionBundles, "guest_bundle");+/** Timestamps defaulted by SQLite are "YYYY-MM-DD HH:MM:SS" text in UTC; app-written ones are unix seconds. */function toDate(value: unknown): Date {if (typeof value === "number") return new Date(value * 1000);@@ -62,7 +74,7 @@ function countFor(table: SQLiteTable, column: SQLiteColumn) {* - search: Calendar name, owner name or owner email contains (case-insensitive)* - content: all | shared | synced (default: all; shared = user shares or share links)* - owner: all | orphaned | with-owner (default: all)- * - sort: name | createdAt | owner | shiftsCount | sharesCount | externalSyncsCount | guestPermission (default: createdAt)+ * - sort: name | createdAt | owner | shiftsCount | sharesCount | externalSyncsCount | guestBundle (default: createdAt)* - order: asc | desc (default: desc)* - page: 1-based page, clamped to the last page (default: 1)* - limit: Page size (default: 25, max: 100)@@ -118,7 +130,7 @@ export async function GET(request: NextRequest) {shiftsCount: sql`(select count(*) from ${shifts} where ${shifts.calendarId} = ${calendars.id})`,sharesCount: sql`((select count(*) from ${calendarShares} where ${calendarShares.calendarId} = ${calendars.id}) + (select count(*) from ${calendarAccessTokens} where ${calendarAccessTokens.calendarId} = ${calendars.id}))`,externalSyncsCount: sql`(select count(*) from ${externalSyncs} where ${externalSyncs.calendarId} = ${calendars.id})`,- guestPermission: sql`case ${calendars.guestPermission} when 'write' then 2 when 'read' then 1 else 0 end`,+ guestBundle: sql`case when ${guestBundleTable.id} is null then 0 else 1 end`,};const direction = order === "asc" ? asc : desc;@@ -148,7 +160,9 @@ export async function GET(request: NextRequest) {name: calendars.name,color: calendars.color,ownerId: calendars.ownerId,- guestPermission: calendars.guestPermission,+ guestBundleRowId: guestBundleTable.id,+ guestBundleName: guestBundleTable.name,+ guestBundleSeedKey: guestBundleTable.seedKey,// Raw values: rows created with the SQL default hold text, not unix secondscreatedAt: sql<unknown>`${calendars.createdAt}`,updatedAt: sql<unknown>`${calendars.updatedAt}`,@@ -165,6 +179,7 @@ export async function GET(request: NextRequest) {}).from(calendars).leftJoin(user, eq(calendars.ownerId, user.id))+ .leftJoin(guestBundleTable, eq(calendars.guestBundleId, guestBundleTable.id)).where(where).orderBy(asc(sql`case when ${orphaned} then 0 else 1 end`),@@ -182,7 +197,9 @@ export async function GET(request: NextRequest) {owner: row.ownerUserId? { name: row.ownerName, email: row.ownerEmail, image: row.ownerImage }: null,- guestPermission: row.guestPermission,+ guestBundle: row.guestBundleRowId+ ? { id: row.guestBundleRowId, name: row.guestBundleName!, seedKey: row.guestBundleSeedKey }+ : null,createdAt: toDate(row.createdAt),updatedAt: toDate(row.updatedAt),shiftsCount: Number(row.shiftsCount),diff --git a/app/api/admin/users/[id]/route.ts b/app/api/admin/users/[id]/route.tsindex 86a7909..af9f518 100644--- a/app/api/admin/users/[id]/route.ts+++ b/app/api/admin/users/[id]/route.ts@@ -75,21 +75,20 @@ export async function GET(.from(calendarsTable).where(eq(calendarsTable.ownerId, targetUserId));- // Get shared calendars (with calendar name and permission)- const sharedCalendars = await db- .select({- id: calendarSharesTable.id,- calendarId: calendarSharesTable.calendarId,- name: calendarsTable.name,- permission: calendarSharesTable.permission,- createdAt: calendarSharesTable.createdAt,- })- .from(calendarSharesTable)- .innerJoin(- calendarsTable,- eq(calendarSharesTable.calendarId, calendarsTable.id)- )- .where(eq(calendarSharesTable.userId, targetUserId));+ // Get shared calendars (with calendar name and bundle)+ const shareRows = await db.query.calendarShares.findMany({+ where: (shares, { eq: eqOp }) => eqOp(shares.userId, targetUserId),+ columns: { calendarId: true },+ with: {+ calendar: { columns: { name: true } },+ bundle: { columns: { id: true, name: true, seedKey: true } },+ },+ });+ const sharedCalendars = shareRows.map((share) => ({+ id: share.calendarId,+ name: share.calendar.name,+ bundle: share.bundle,+ }));const sharesCount = sharedCalendars.length;@@ -126,11 +125,7 @@ export async function GET(updatedAt: targetUser.updatedAt,},calendars: ownedCalendars,- sharedCalendars: sharedCalendars.map((share) => ({- id: share.calendarId,- name: share.name,- permission: share.permission,- })),+ sharedCalendars,sharesCount: sharesCount,accounts,sessionsCount: Number(sessionsCount?.count || 0),diff --git a/app/api/calendars/[id]/bundles/[bundleId]/clone/route.ts b/app/api/calendars/[id]/bundles/[bundleId]/clone/route.tsnew file mode 100644index 0000000..1a7d0ea--- /dev/null+++ b/app/api/calendars/[id]/bundles/[bundleId]/clone/route.ts@@ -0,0 +1,57 @@+import { NextRequest, NextResponse } from "next/server";+import {+ clonePermissionBundle,+ getBundleForCalendar,+ getCalendarName,+ handleBundleServiceError,+ requireManageSharesOrGuestAccess,+} from "@/lib/auth/permission-bundles-service";+import { rateLimit } from "@/lib/rate-limiter";+import { logUserAction, type CalendarBundleClonedMetadata } from "@/lib/audit-log";++export async function POST(+ request: NextRequest,+ { params }: { params: Promise<{ id: string; bundleId: string }> }+) {+ try {+ const { id: calendarId, bundleId } = await params;+ const auth = await requireManageSharesOrGuestAccess(request, calendarId);+ if (auth instanceof NextResponse) return auth;++ const rateLimitResponse = rateLimit(+ request,+ auth.userId,+ "bundle-mutations",+ calendarId+ );+ if (rateLimitResponse) return rateLimitResponse;++ const source = await getBundleForCalendar(calendarId, bundleId);+ if (!source) {+ return NextResponse.json({ error: "Bundle not found" }, { status: 404 });+ }++ const body = await request.json();+ const { name } = body;+ if (typeof name !== "string") {+ return NextResponse.json({ error: "Invalid name" }, { status: 400 });+ }++ const clone = await clonePermissionBundle(calendarId, bundleId, name);++ await logUserAction<CalendarBundleClonedMetadata>({+ userId: auth.userId,+ action: "calendar.bundle.cloned",+ request,+ metadata: {+ calendarName: await getCalendarName(calendarId),+ sourceBundleName: source.name,+ newBundleName: clone.name,+ },+ });++ return NextResponse.json(clone, { status: 201 });+ } catch (error) {+ return handleBundleServiceError(error, "Failed to clone permission bundle");+ }+}diff --git a/app/api/calendars/[id]/bundles/[bundleId]/route.ts b/app/api/calendars/[id]/bundles/[bundleId]/route.tsnew file mode 100644index 0000000..d0fdad3--- /dev/null+++ b/app/api/calendars/[id]/bundles/[bundleId]/route.ts@@ -0,0 +1,119 @@+import { NextRequest, NextResponse } from "next/server";+import {+ deletePermissionBundle,+ getBundleForCalendar,+ getCalendarName,+ updatePermissionBundle,+ handleBundleServiceError,+ requireManageSharesOrGuestAccess,+} from "@/lib/auth/permission-bundles-service";+import { rateLimit } from "@/lib/rate-limiter";+import {+ logUserAction,+ type CalendarBundleUpdatedMetadata,+ type CalendarBundleDeletedMetadata,+} from "@/lib/audit-log";++export async function PATCH(+ request: NextRequest,+ { params }: { params: Promise<{ id: string; bundleId: string }> }+) {+ try {+ const { id: calendarId, bundleId } = await params;+ const auth = await requireManageSharesOrGuestAccess(request, calendarId);+ if (auth instanceof NextResponse) return auth;++ const rateLimitResponse = rateLimit(+ request,+ auth.userId,+ "bundle-mutations",+ calendarId+ );+ if (rateLimitResponse) return rateLimitResponse;++ const existing = await getBundleForCalendar(calendarId, bundleId);+ if (!existing) {+ return NextResponse.json({ error: "Bundle not found" }, { status: 404 });+ }++ const body = await request.json();+ const { name, capabilities } = body;++ if (name !== undefined && typeof name !== "string") {+ return NextResponse.json({ error: "Invalid name" }, { status: 400 });+ }++ const updated = await updatePermissionBundle(+ calendarId,+ bundleId,+ { name, capabilities },+ auth.access+ );++ const before = new Set(existing.capabilities);+ const after = new Set(updated.capabilities);+ const addedCapabilities = updated.capabilities.filter((c) => !before.has(c));+ const removedCapabilities = existing.capabilities.filter(+ (c) => !after.has(c)+ );++ await logUserAction<CalendarBundleUpdatedMetadata>({+ userId: auth.userId,+ action: "calendar.bundle.updated",+ request,+ metadata: {+ calendarName: await getCalendarName(calendarId),+ bundleName: updated.name,+ addedCapabilities,+ removedCapabilities,+ ...(updated.name !== existing.name+ ? { renamed: { from: existing.name, to: updated.name } }+ : {}),+ },+ });++ return NextResponse.json(updated);+ } catch (error) {+ return handleBundleServiceError(error, "Failed to update permission bundle");+ }+}++export async function DELETE(+ request: NextRequest,+ { params }: { params: Promise<{ id: string; bundleId: string }> }+) {+ try {+ const { id: calendarId, bundleId } = await params;+ const auth = await requireManageSharesOrGuestAccess(request, calendarId);+ if (auth instanceof NextResponse) return auth;++ const rateLimitResponse = rateLimit(+ request,+ auth.userId,+ "bundle-mutations",+ calendarId+ );+ if (rateLimitResponse) return rateLimitResponse;++ const existing = await getBundleForCalendar(calendarId, bundleId);+ if (!existing) {+ return NextResponse.json({ error: "Bundle not found" }, { status: 404 });+ }++ await deletePermissionBundle(calendarId, bundleId);++ await logUserAction<CalendarBundleDeletedMetadata>({+ userId: auth.userId,+ action: "calendar.bundle.deleted",+ request,+ metadata: {+ calendarName: await getCalendarName(calendarId),+ bundleName: existing.name,+ },+ });++ return NextResponse.json({ success: true });+ } catch (error) {+ return handleBundleServiceError(error, "Failed to delete permission bundle");+ }+}diff --git a/app/api/calendars/[id]/bundles/route.ts b/app/api/calendars/[id]/bundles/route.tsnew file mode 100644index 0000000..66dfcbd--- /dev/null+++ b/app/api/calendars/[id]/bundles/route.ts@@ -0,0 +1,77 @@+import { NextRequest, NextResponse } from "next/server";+import {+ createPermissionBundle,+ getCalendarName,+ listBundlesWithUsage,+ handleBundleServiceError,+ requireManageSharesOrGuestAccess,+} from "@/lib/auth/permission-bundles-service";+import { rateLimit } from "@/lib/rate-limiter";+import { logUserAction, type CalendarBundleCreatedMetadata } from "@/lib/audit-log";++export async function GET(+ request: NextRequest,+ { params }: { params: Promise<{ id: string }> }+) {+ try {+ const { id: calendarId } = await params;+ const auth = await requireManageSharesOrGuestAccess(request, calendarId);+ if (auth instanceof NextResponse) return auth;++ const bundles = await listBundlesWithUsage(calendarId);+ return NextResponse.json(bundles);+ } catch (error) {+ console.error("Failed to fetch permission bundles:", error);+ return NextResponse.json(+ { error: "Failed to fetch permission bundles" },+ { status: 500 }+ );+ }+}++export async function POST(+ request: NextRequest,+ { params }: { params: Promise<{ id: string }> }+) {+ try {+ const { id: calendarId } = await params;+ const auth = await requireManageSharesOrGuestAccess(request, calendarId);+ if (auth instanceof NextResponse) return auth;++ const rateLimitResponse = rateLimit(+ request,+ auth.userId,+ "bundle-mutations",+ calendarId+ );+ if (rateLimitResponse) return rateLimitResponse;++ const body = await request.json();+ const { name, capabilities } = body;++ if (typeof name !== "string") {+ return NextResponse.json({ error: "Invalid name" }, { status: 400 });+ }++ const bundle = await createPermissionBundle(+ calendarId,+ { name, capabilities },+ auth.access+ );++ await logUserAction<CalendarBundleCreatedMetadata>({+ userId: auth.userId,+ action: "calendar.bundle.created",+ request,+ metadata: {+ calendarName: await getCalendarName(calendarId),+ bundleName: bundle.name,+ capabilities: bundle.capabilities,+ },+ });++ return NextResponse.json(bundle, { status: 201 });+ } catch (error) {+ return handleBundleServiceError(error, "Failed to create permission bundle");+ }+}diff --git a/app/api/calendars/[id]/members/route.ts b/app/api/calendars/[id]/members/route.tsindex dc8beaa..6041654 100644--- a/app/api/calendars/[id]/members/route.ts+++ b/app/api/calendars/[id]/members/route.ts@@ -1,6 +1,6 @@import { NextRequest, NextResponse } from "next/server";import { getSessionUser } from "@/lib/auth/sessions";-import { canEditCalendar, getCalendarMembers } from "@/lib/auth/permissions";+import { hasCapability, getCalendarMembers } from "@/lib/auth/permissions";// GET minimal member list (owner + shares) for a calendar.// Used to pick who to add to a shift's signup list — deliberately narrower@@ -13,10 +13,10 @@ export async function GET(const { id: calendarId } = await params;const user = await getSessionUser(request.headers);- const hasAccess = await canEditCalendar(user?.id, calendarId);+ const hasAccess = await hasCapability(user?.id, calendarId, "signUpOthers");if (!hasAccess) {return NextResponse.json(- { error: "Insufficient permissions. Write access required." },+ { error: "Insufficient permissions. Sign up others access required." },{ status: 403 });}diff --git a/app/api/calendars/[id]/route.ts b/app/api/calendars/[id]/route.tsindex 4f83757..5c3c8ad 100644--- a/app/api/calendars/[id]/route.ts+++ b/app/api/calendars/[id]/route.ts@@ -5,14 +5,20 @@ import {shifts,shiftPresets,calendarNotes,+ calendarPermissionBundles,} from "@/lib/db/schema";import { eq, sql } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";import {canViewCalendar,- canManageCalendar,canDeleteCalendar,+ getCalendarAccess,} from "@/lib/auth/permissions";+import {+ assertBundleWithinCallerCapabilities,+ handleBundleServiceError,+ resolveGuestEligibleBundle,+} from "@/lib/auth/permission-bundles-service";import {calendarViewSettingsEqual,sanitizeCalendarViewSettings,@@ -21,7 +27,7 @@ import {logUserAction,type CalendarUpdatedMetadata,type CalendarDeletedMetadata,- type CalendarGuestPermissionChangedMetadata,+ type CalendarGuestBundleChangedMetadata,} from "@/lib/audit-log";// GET single calendar@@ -79,14 +85,7 @@ export async function PATCH(const { id } = await params;const user = await getSessionUser(request.headers);const body = await request.json();- const {- name,- color,- guestPermission,- viewSettings,- allowSelfSignup,- signupsEnabled,- } = body;+ const { name, color, guestBundleId, viewSettings, signupsEnabled } = body;if (viewSettings !== undefined &&@@ -112,19 +111,37 @@ export async function PATCH();}- // Check admin permission (works for both authenticated users and guests)- const hasAccess = await canManageCalendar(user?.id, id);- if (!hasAccess) {- return NextResponse.json(+ // guestBundleId is gated separately from the rest of the calendar's+ // settings — a bundle can hold manageCalendarSettings without+ // manageGuestAccess, or vice versa.+ const wantsGuestChange = guestBundleId !== undefined;+ const wantsGeneralChange =+ name !== undefined ||+ color !== undefined ||+ viewSettings !== undefined ||+ typeof signupsEnabled === "boolean";++ const access = await getCalendarAccess(user?.id, id);+ const deny = () =>+ NextResponse.json({ error: "Insufficient permissions. Admin access required." },{ status: 403 });+ if (+ (wantsGeneralChange || !wantsGuestChange) &&+ !access?.can("manageCalendarSettings")+ ) {+ return deny();+ }+ if (wantsGuestChange && !access?.can("manageGuestAccess")) {+ return deny();}const updateData: Partial<typeof calendars.$inferInsert> = {};const changes: string[] = [];- let guestPermissionChanged = false;- let oldGuestPermission: string | undefined;+ let guestBundleChanged = false;+ let oldGuestBundleId: string | null = null;+ let newGuestBundleId: string | null = null;let viewSettingsChange: CalendarUpdatedMetadata["viewSettings"];if (name && name !== existingCalendar.name) {@@ -135,25 +152,40 @@ export async function PATCH(updateData.color = color;changes.push("color");}- if (- guestPermission !== undefined &&- guestPermission !== existingCalendar.guestPermission- ) {- // Validate guest permission value- if (["none", "read", "write"].includes(guestPermission)) {- updateData.guestPermission = guestPermission;- changes.push("guestPermission");- guestPermissionChanged = true;- oldGuestPermission = existingCalendar.guestPermission;+ if (wantsGuestChange) {+ if (guestBundleId === null) {+ if (existingCalendar.guestBundleId !== null) {+ updateData.guestBundleId = null;+ changes.push("guestBundleId");+ guestBundleChanged = true;+ oldGuestBundleId = existingCalendar.guestBundleId;+ newGuestBundleId = null;+ }+ } else if (typeof guestBundleId === "string") {+ const bundle = await resolveGuestEligibleBundle(+ id,+ guestBundleId,+ "Bundle contains capabilities that cannot be granted to guests"+ );+ if (bundle instanceof NextResponse) return bundle;+ // A non-owner manageGuestAccess holder may only assign a bundle+ // whose capabilities are a subset of their own — closes the+ // self-escalation path a fixed cap used to guard against pre-PR.+ assertBundleWithinCallerCapabilities(access!, bundle.capabilities);+ if (guestBundleId !== existingCalendar.guestBundleId) {+ updateData.guestBundleId = guestBundleId;+ changes.push("guestBundleId");+ guestBundleChanged = true;+ oldGuestBundleId = existingCalendar.guestBundleId;+ newGuestBundleId = guestBundleId;+ }+ } else {+ return NextResponse.json(+ { error: "Invalid guestBundleId" },+ { status: 400 }+ );}}- if (- typeof allowSelfSignup === "boolean" &&- allowSelfSignup !== existingCalendar.allowSelfSignup- ) {- updateData.allowSelfSignup = allowSelfSignup;- changes.push("allowSelfSignup");- }if (typeof signupsEnabled === "boolean" &&signupsEnabled !== existingCalendar.signupsEnabled@@ -207,23 +239,33 @@ export async function PATCH(request,});- // Log separate event for guest permission changes- if (guestPermissionChanged) {- await logUserAction<CalendarGuestPermissionChangedMetadata>({+ // Log separate event for guest bundle changes+ if (guestBundleChanged) {+ const [oldBundle, newBundle] = await Promise.all([+ oldGuestBundleId+ ? db.query.calendarPermissionBundles.findFirst({+ where: eq(calendarPermissionBundles.id, oldGuestBundleId),+ columns: { name: true },+ })+ : null,+ newGuestBundleId+ ? db.query.calendarPermissionBundles.findFirst({+ where: eq(calendarPermissionBundles.id, newGuestBundleId),+ columns: { name: true },+ })+ : null,+ ]);+ await logUserAction<CalendarGuestBundleChangedMetadata>({action: "calendar.guest_permission.changed",userId: user.id,resourceType: "calendar",resourceId: calendar.id,metadata: {calendarName: calendar.name,- oldPermission: (oldGuestPermission || "none") as- | "none"- | "read"- | "write",- newPermission: calendar.guestPermission as- | "none"- | "read"- | "write",+ oldBundleId: oldGuestBundleId,+ oldBundleName: oldBundle?.name ?? null,+ newBundleId: newGuestBundleId,+ newBundleName: newBundle?.name ?? null,},request,});@@ -232,11 +274,7 @@ export async function PATCH(return NextResponse.json(calendar);} catch (error) {- console.error("Failed to update calendar:", error);- return NextResponse.json(- { error: "Failed to update calendar" },- { status: 500 }- );+ return handleBundleServiceError(error, "Failed to update calendar");}}diff --git a/app/api/calendars/[id]/shares/[shareId]/route.ts b/app/api/calendars/[id]/shares/[shareId]/route.tsindex c484efe..14b4725 100644--- a/app/api/calendars/[id]/shares/[shareId]/route.ts+++ b/app/api/calendars/[id]/shares/[shareId]/route.ts@@ -2,9 +2,17 @@ import { NextRequest, NextResponse } from "next/server";import { db } from "@/lib/db";import { calendarShares, calendars } from "@/lib/db/schema";import { getSessionUser } from "@/lib/auth/sessions";-import { checkPermission } from "@/lib/auth/permissions";+import { getCalendarAccess, hasCapability } from "@/lib/auth/permissions";+import {+ assertBundleWithinCallerCapabilities,+ getBundleForCalendar,+ handleBundleServiceError,+} from "@/lib/auth/permission-bundles-service";import { eq, and } from "drizzle-orm";-import { logAuditEvent } from "@/lib/audit-log";+import {+ logAuditEvent,+ type CalendarPermissionChangedMetadata,+} from "@/lib/audit-log";export async function PUT(request: NextRequest,@@ -19,8 +27,8 @@ export async function PUT(}// Check if user has admin/owner permission- const hasPermission = await checkPermission(user.id, calendarId, "admin");- if (!hasPermission) {+ const access = await getCalendarAccess(user.id, calendarId);+ if (!access?.can("manageShares")) {return NextResponse.json({ error: "Insufficient permissions" },{ status: 403 }@@ -28,28 +36,20 @@ export async function PUT(}const body = await request.json();- const { permission } = body;+ const { bundleId } = body;- // Validate permission value. "owner" is intentionally excluded — ownership- // transfer is not a share concept and only happens through admin routes.- const validPermissions = ["admin", "write", "read"];- if (!validPermissions.includes(permission)) {- return NextResponse.json(- { error: "Invalid permission value" },- { status: 400 }- );+ // Validate the bundle: must exist and belong to this calendar.+ if (!bundleId || typeof bundleId !== "string") {+ return NextResponse.json({ error: "Invalid bundle id" }, { status: 400 });}-- // Only owner can set/change admin permissions- if (permission === "admin") {- const isOwner = await checkPermission(user.id, calendarId, "owner");- if (!isOwner) {- return NextResponse.json(- { error: "Only the owner can grant admin permissions" },- { status: 403 }- );- }+ const newBundle = await getBundleForCalendar(calendarId, bundleId);+ if (!newBundle) {+ return NextResponse.json({ error: "Bundle not found" }, { status: 404 });}+ // A non-owner manageShares holder may only reassign to a bundle whose+ // capabilities are a subset of their own — closes the self-escalation+ // path a fixed cap used to guard against pre-PR.+ assertBundleWithinCallerCapabilities(access, newBundle.capabilities);// Fetch existing shareconst existingShare = await db.query.calendarShares.findFirst({@@ -64,6 +64,9 @@ export async function PUT(name: true,},},+ bundle: {+ columns: { id: true, name: true },+ },},});@@ -71,30 +74,10 @@ export async function PUT(return NextResponse.json({ error: "Share not found" }, { status: 404 });}- // Only owner can modify admin permissions, and only owner can modify a- // legacy "owner" share (ownership grants are no longer issued via shares).- // Cast for the "owner" comparison: the schema's enum type no longer- // includes it, but pre-existing rows in the database may still carry it.- if (- existingShare.permission === "admin" ||- (existingShare.permission as string) === "owner"- ) {- const isOwner = await checkPermission(user.id, calendarId, "owner");- if (!isOwner) {- return NextResponse.json(- { error: "Only the owner can modify admin permissions" },- { status: 403 }- );- }- }-- // Store old permission for audit log- const oldPermission = existingShare.permission;-// Update share permissionawait db.update(calendarShares)- .set({ permission })+ .set({ bundleId: newBundle.id }).where(eq(calendarShares.id, shareId));// Fetch calendar name for audit log@@ -104,20 +87,23 @@ export async function PUT(});// Log audit event- await logAuditEvent({+ await logAuditEvent<CalendarPermissionChangedMetadata>({userId: user.id,action: "calendar.permission.changed",+ resourceType: "calendar",+ resourceId: calendarId,severity: "info",request,metadata: {- calendarId,calendarName: calendar?.name || "Unknown",user:existingShare.user.email ||existingShare.user.name ||existingShare.userId,- oldPermission,- newPermission: permission,+ oldBundleId: existingShare.bundle.id,+ oldBundleName: existingShare.bundle.name,+ newBundleId: newBundle.id,+ newBundleName: newBundle.name,},});@@ -140,16 +126,15 @@ export async function PUT(email: true,},},+ bundle: {+ columns: { id: true, name: true, seedKey: true },+ },},});return NextResponse.json(shareWithUser);} catch (error) {- console.error("Failed to update calendar share:", error);- return NextResponse.json(- { error: "Failed to update share" },- { status: 500 }- );+ return handleBundleServiceError(error, "Failed to update share");}}@@ -185,23 +170,16 @@ export async function DELETE(return NextResponse.json({ error: "Share not found" }, { status: 404 });}- // Check permissions: owner can remove any share, admin can remove non-admin shares, users can remove their own- const hasAdminPermission = await checkPermission(+ // Check permissions: manageShares holder can remove any share (S1/S2 —+ // that includes admin-capable ones, no owner-only carve-out), users can+ // remove their own.+ const hasAdminPermission = await hasCapability(user.id,calendarId,- "admin"+ "manageShares");- const isOwner = await checkPermission(user.id, calendarId, "owner");const isSelf = share.userId === user.id;- // Only owner can remove admin shares- if (share.permission === "admin" && !isOwner) {- return NextResponse.json(- { error: "Only the owner can remove admin shares" },- { status: 403 }- );- }-if (!hasAdminPermission && !isSelf) {return NextResponse.json({ error: "Insufficient permissions" },diff --git a/app/api/calendars/[id]/shares/route.ts b/app/api/calendars/[id]/shares/route.tsindex 8e1748b..93b254f 100644--- a/app/api/calendars/[id]/shares/route.ts+++ b/app/api/calendars/[id]/shares/route.ts@@ -6,9 +6,14 @@ import {userCalendarSubscriptions,} from "@/lib/db/schema";import { getSessionUser } from "@/lib/auth/sessions";-import { checkPermission } from "@/lib/auth/permissions";+import { getCalendarAccess, hasCapability } from "@/lib/auth/permissions";+import {+ assertBundleWithinCallerCapabilities,+ getBundleForCalendar,+ handleBundleServiceError,+} from "@/lib/auth/permission-bundles-service";import { eq, and } from "drizzle-orm";-import { logAuditEvent } from "@/lib/audit-log";+import { logAuditEvent, type CalendarSharedMetadata } from "@/lib/audit-log";export async function GET(request: NextRequest,@@ -19,7 +24,11 @@ export async function GET(const user = await getSessionUser(request.headers);// Check if user has admin/owner permission- const hasPermission = await checkPermission(user?.id, calendarId, "admin");+ const hasPermission = await hasCapability(+ user?.id,+ calendarId,+ "manageShares"+ );if (!hasPermission) {return NextResponse.json({ error: "Insufficient permissions" },@@ -46,6 +55,13 @@ export async function GET(email: true,},},+ bundle: {+ columns: {+ id: true,+ name: true,+ seedKey: true,+ },+ },},orderBy: (shares, { desc }) => [desc(shares.createdAt)],});@@ -73,8 +89,8 @@ export async function POST(}// Check if user has admin/owner permission- const hasPermission = await checkPermission(user.id, calendarId, "admin");- if (!hasPermission) {+ const access = await getCalendarAccess(user.id, calendarId);+ if (!access?.can("manageShares")) {return NextResponse.json({ error: "Insufficient permissions" },{ status: 403 }@@ -82,7 +98,7 @@ export async function POST(}const body = await request.json();- const { userId: targetUserId, permission } = body;+ const { userId: targetUserId, bundleId } = body;// Validate target user idif (!targetUserId || typeof targetUserId !== "string") {@@ -92,26 +108,18 @@ export async function POST();}- // Validate permission value. "owner" is intentionally excluded — ownership- // transfer is not a share concept and only happens through admin routes.- const validPermissions = ["admin", "write", "read"];- if (!validPermissions.includes(permission)) {- return NextResponse.json(- { error: "Invalid permission value" },- { status: 400 }- );+ // Validate the bundle: must exist and belong to this calendar.+ if (!bundleId || typeof bundleId !== "string") {+ return NextResponse.json({ error: "Invalid bundle id" }, { status: 400 });}-- // Only owner can grant admin permissions- if (permission === "admin") {- const isOwner = await checkPermission(user.id, calendarId, "owner");- if (!isOwner) {- return NextResponse.json(- { error: "Only the owner can grant admin permissions" },- { status: 403 }- );- }+ const bundle = await getBundleForCalendar(calendarId, bundleId);+ if (!bundle) {+ return NextResponse.json({ error: "Bundle not found" }, { status: 404 });}+ // A non-owner manageShares holder may only grant a bundle whose+ // capabilities are a subset of their own — closes the self-escalation+ // path a fixed cap used to guard against pre-PR.+ assertBundleWithinCallerCapabilities(access, bundle.capabilities);// Ensure the target user actually existsconst targetUserExists = await db.query.user.findFirst({@@ -188,23 +196,25 @@ export async function POST(id: crypto.randomUUID(),calendarId,userId: targetUserId,- permission,+ bundleId: bundle.id,sharedBy: user.id,createdAt: new Date(),}).returning();// Log audit event- await logAuditEvent({+ await logAuditEvent<CalendarSharedMetadata>({userId: user.id,action: "calendar.shared",+ resourceType: "calendar",+ resourceId: calendarId,severity: "info",request,metadata: {- calendarId,calendarName: calendar?.name || "Unknown",sharedWith: targetUser?.email || targetUser?.name || targetUserId,- permission,+ bundleId: bundle.id,+ bundleName: bundle.name,},});@@ -227,15 +237,14 @@ export async function POST(email: true,},},+ bundle: {+ columns: { id: true, name: true, seedKey: true },+ },},});return NextResponse.json(shareWithUser, { status: 201 });} catch (error) {- console.error("Failed to create calendar share:", error);- return NextResponse.json(- { error: "Failed to create share" },- { status: 500 }- );+ return handleBundleServiceError(error, "Failed to create share");}}diff --git a/app/api/calendars/[id]/tokens/[tokenId]/route.ts b/app/api/calendars/[id]/tokens/[tokenId]/route.tsindex 1e5027a..6c1b946 100644--- a/app/api/calendars/[id]/tokens/[tokenId]/route.ts+++ b/app/api/calendars/[id]/tokens/[tokenId]/route.ts@@ -3,7 +3,12 @@ import { db } from "@/lib/db";import { calendarAccessTokens, calendars } from "@/lib/db/schema";import { eq, and } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { checkPermission } from "@/lib/auth/permissions";+import { getCalendarAccess, hasCapability } from "@/lib/auth/permissions";+import {+ assertBundleWithinCallerCapabilities,+ handleBundleServiceError,+ resolveGuestEligibleBundle,+} from "@/lib/auth/permission-bundles-service";import { logAuditEvent } from "@/lib/audit-log";/**@@ -27,12 +32,10 @@ export async function PATCH();}- // Check permissions (admin or owner only)- const canManage =- (await checkPermission(user.id, calendarId, "admin")) ||- (await checkPermission(user.id, calendarId, "owner"));+ // Check permissions+ const access = await getCalendarAccess(user.id, calendarId);- if (!canManage) {+ if (!access?.can("manageGuestAccess")) {return NextResponse.json({ error: "Insufficient permissions" },{ status: 403 }@@ -58,22 +61,37 @@ export async function PATCH(const body = await request.json();const {name,- permission,+ bundleId,expiresAt,isActive,}: {name?: string;- permission?: "read" | "write";+ bundleId?: string;expiresAt?: string | null;isActive?: boolean;} = body;- // Validate permission if provided- if (permission && permission !== "read" && permission !== "write") {- return NextResponse.json(- { error: "Permission must be 'read' or 'write'" },- { status: 400 }+ // Validate the new bundle if provided: must exist, belong to this+ // calendar, and be guest-eligible (E7) — a link is always a guest/link source.+ let newBundle: Awaited<ReturnType<typeof resolveGuestEligibleBundle>> | null =+ null;+ if (bundleId !== undefined) {+ if (typeof bundleId !== "string") {+ return NextResponse.json(+ { error: "Invalid bundle id" },+ { status: 400 }+ );+ }+ newBundle = await resolveGuestEligibleBundle(+ calendarId,+ bundleId,+ "Bundle contains capabilities that cannot be granted via a link");+ if (newBundle instanceof NextResponse) return newBundle;+ // A non-owner manageGuestAccess holder may only assign a bundle whose+ // capabilities are a subset of their own — closes the self-escalation+ // path a fixed cap used to guard against pre-PR.+ assertBundleWithinCallerCapabilities(access, newBundle.capabilities);}// Validate expiration date if provided@@ -101,7 +119,7 @@ export async function PATCH(// Build update objectconst updates: Partial<typeof calendarAccessTokens.$inferInsert> = {};if (name !== undefined) updates.name = name;- if (permission !== undefined) updates.permission = permission;+ if (newBundle) updates.bundleId = newBundle.id;if (expiresAtDate !== undefined) updates.expiresAt = expiresAtDate;if (isActive !== undefined) updates.isActive = isActive;@@ -136,21 +154,25 @@ export async function PATCH(isUserVisible: true,});+ // Resolve the token's bundle identity for the response — reuse the+ // already-validated bundle instead of re-fetching it when it was part+ // of this request.+ const updatedBundle = newBundle+ ? { id: newBundle.id, name: newBundle.name, seedKey: newBundle.seedKey }+ : await db.query.calendarPermissionBundles.findFirst({+ where: (b, { eq: eqOp }) => eqOp(b.id, updatedToken.bundleId),+ columns: { id: true, name: true, seedKey: true },+ });+// Return sanitized token (no full token)return NextResponse.json({...updatedToken,+ bundle: updatedBundle ?? null,tokenPreview: `${updatedToken.token.slice(0, 6)}...`,token: undefined,});} catch (error) {- console.error(- "[API] PATCH /api/calendars/[id]/tokens/[tokenId] error:",- error- );- return NextResponse.json(- { error: "Failed to update access token" },- { status: 500 }- );+ return handleBundleServiceError(error, "Failed to update access token");}}@@ -174,10 +196,12 @@ export async function DELETE();}- // Check permissions (admin or owner only)- const canManage =- (await checkPermission(user.id, calendarId, "admin")) ||- (await checkPermission(user.id, calendarId, "owner"));+ // Check permissions+ const canManage = await hasCapability(+ user.id,+ calendarId,+ "manageGuestAccess"+ );if (!canManage) {return NextResponse.json(@@ -224,7 +248,7 @@ export async function DELETE(tokenId,tokenName: token.name || "Unnamed",calendarName: calendar?.name || "Unknown",- permission: token.permission,+ bundleId: token.bundleId,usageCount: token.usageCount,},request,diff --git a/app/api/calendars/[id]/tokens/route.ts b/app/api/calendars/[id]/tokens/route.tsindex c1f43a3..74de878 100644--- a/app/api/calendars/[id]/tokens/route.ts+++ b/app/api/calendars/[id]/tokens/route.ts@@ -3,9 +3,14 @@ import { db } from "@/lib/db";import { calendarAccessTokens, calendars } from "@/lib/db/schema";import { eq, desc } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { checkPermission } from "@/lib/auth/permissions";+import { getCalendarAccess, hasCapability } from "@/lib/auth/permissions";+import {+ assertBundleWithinCallerCapabilities,+ handleBundleServiceError,+ resolveGuestEligibleBundle,+} from "@/lib/auth/permission-bundles-service";import { generateAccessToken } from "@/lib/auth/token-auth";-import { logAuditEvent } from "@/lib/audit-log";+import { logAuditEvent, type CalendarTokenCreatedMetadata } from "@/lib/audit-log";import { rateLimit } from "@/lib/rate-limiter";/**@@ -21,10 +26,12 @@ export async function GET(const { id: calendarId } = await params;const user = await getSessionUser(request.headers);- // Check permissions (admin or owner only)- const canManage =- (await checkPermission(user?.id, calendarId, "admin")) ||- (await checkPermission(user?.id, calendarId, "owner"));+ // Check permissions+ const canManage = await hasCapability(+ user?.id,+ calendarId,+ "manageGuestAccess"+ );if (!canManage) {return NextResponse.json(@@ -39,7 +46,7 @@ export async function GET(id: calendarAccessTokens.id,token: calendarAccessTokens.token,name: calendarAccessTokens.name,- permission: calendarAccessTokens.permission,+ bundleId: calendarAccessTokens.bundleId,expiresAt: calendarAccessTokens.expiresAt,createdBy: calendarAccessTokens.createdBy,createdAt: calendarAccessTokens.createdAt,@@ -51,9 +58,22 @@ export async function GET(.where(eq(calendarAccessTokens.calendarId, calendarId)).orderBy(desc(calendarAccessTokens.createdAt));+ // Resolve each token's bundleId to its identity for the response+ const distinctBundleIds = Array.from(+ new Set(tokens.map((token) => token.bundleId))+ );+ const bundles = distinctBundleIds.length+ ? await db.query.calendarPermissionBundles.findMany({+ where: (b, { inArray }) => inArray(b.id, distinctBundleIds),+ columns: { id: true, name: true, seedKey: true },+ })+ : [];+ const bundleById = new Map(bundles.map((bundle) => [bundle.id, bundle]));+// Return partial tokens (first 6 chars) for securityconst sanitizedTokens = tokens.map((token) => ({...token,+ bundle: bundleById.get(token.bundleId) ?? null,tokenPreview: `${token.token.slice(0, 6)}...`,token: undefined, // Remove full token from response}));@@ -97,12 +117,10 @@ export async function POST();if (rateLimitResponse) return rateLimitResponse;- // Check permissions (admin or owner only)- const canManage =- (await checkPermission(user.id, calendarId, "admin")) ||- (await checkPermission(user.id, calendarId, "owner"));+ // Check permissions+ const access = await getCalendarAccess(user.id, calendarId);- if (!canManage) {+ if (!access?.can("manageGuestAccess")) {return NextResponse.json({ error: "Insufficient permissions" },{ status: 403 }@@ -112,21 +130,29 @@ export async function POST(const body = await request.json();const {name,- permission = "read",+ bundleId,expiresAt,}: {name?: string;- permission?: "read" | "write";+ bundleId?: string;expiresAt?: string | null;} = body;- // Validate permission- if (permission !== "read" && permission !== "write") {- return NextResponse.json(- { error: "Permission must be 'read' or 'write'" },- { status: 400 }- );+ // Validate the bundle: must exist, belong to this calendar, and be+ // guest-eligible (E7) — a link is always a guest/link source.+ if (!bundleId || typeof bundleId !== "string") {+ return NextResponse.json({ error: "Invalid bundle id" }, { status: 400 });}+ const bundle = await resolveGuestEligibleBundle(+ calendarId,+ bundleId,+ "Bundle contains capabilities that cannot be granted via a link"+ );+ if (bundle instanceof NextResponse) return bundle;+ // A non-owner manageGuestAccess holder may only assign a bundle whose+ // capabilities are a subset of their own — closes the self-escalation+ // path a fixed cap used to guard against pre-PR.+ assertBundleWithinCallerCapabilities(access, bundle.capabilities);// Validate expiration date (if provided)let expiresAtDate: Date | null = null;@@ -163,14 +189,14 @@ export async function POST(calendarId,token,name: name || null,- permission,+ bundleId: bundle.id,expiresAt: expiresAtDate,createdBy: user.id,}).returning();// Audit log- void logAuditEvent({+ void logAuditEvent<CalendarTokenCreatedMetadata>({userId: user.id,action: "calendar_token_created",resourceType: "calendar",@@ -179,7 +205,8 @@ export async function POST(tokenId: newToken.id,tokenName: name || "Unnamed",calendarName: calendar?.name || "Unknown",- permission,+ bundleId: bundle.id,+ bundleName: bundle.name,expiresAt: expiresAt || null,},request,@@ -191,16 +218,13 @@ export async function POST(return NextResponse.json({...newToken,+ bundle: { id: bundle.id, name: bundle.name, seedKey: bundle.seedKey },token, // Full token returned ONLY on creationtokenPreview: `${token.slice(0, 6)}...`,},{ status: 201 });} catch (error) {- console.error("[API] POST /api/calendars/[id]/tokens error:", error);- return NextResponse.json(- { error: "Failed to create access token" },- { status: 500 }- );+ return handleBundleServiceError(error, "Failed to create access token");}}diff --git a/app/api/calendars/route.ts b/app/api/calendars/route.tsindex e37be6c..da6eb71 100644--- a/app/api/calendars/route.ts+++ b/app/api/calendars/route.ts@@ -7,8 +7,11 @@ import {userCalendarSubscriptions,} from "@/lib/db/schema";import { sql, eq, or, and } from "drizzle-orm";+import {+ getUserAccessibleCalendars,+ seedPermissionBundles,+} from "@/lib/auth/permissions";import { getSessionUser } from "@/lib/auth/sessions";-import { getUserAccessibleCalendars } from "@/lib/auth/permissions";import { isAuthEnabled } from "@/lib/auth/feature-flags";import { rateLimit } from "@/lib/rate-limiter";import { logUserAction, type CalendarCreatedMetadata } from "@/lib/audit-log";@@ -16,6 +19,14 @@ import {getTokensFromCookie,validateAccessToken,} from "@/lib/auth/token-auth";+import {+ applyGuestCeiling,+ CAPABILITIES,+ defaultBundleDefinitionsForNewCalendar,+ sanitizeCapabilities,+ type Capability,+} from "@/lib/permission-bundles";+import type { CalendarBundleRef } from "@/lib/types";// GET all calendars (only those accessible to the user)export async function GET(request: Request) {@@ -37,8 +48,7 @@ export async function GET(request: Request) {name: calendars.name,color: calendars.color,ownerId: calendars.ownerId,- guestPermission: calendars.guestPermission,- allowSelfSignup: calendars.allowSelfSignup,+ guestBundleId: calendars.guestBundleId,signupsEnabled: calendars.signupsEnabled,viewSettings: calendars.viewSettings,createdAt: calendars.createdAt,@@ -55,16 +65,17 @@ export async function GET(request: Request) {// If user is authenticated, fetch additional metadatalet subscriptions: Map<string, { status: string; source: string }> =new Map();- let shares: Map<string, string> = new Map();- const tokens: Map<string, "read" | "write"> = new Map();+ let shares: Map<string, string> = new Map(); // calendarId -> bundleId- // Get token permissions (works for both guests and authenticated users)+ // Get token bundles (works for both guests and authenticated users)+ const tokens: Map<string, string> = new Map(); // calendarId -> bundleIdconst userTokens = await getTokensFromCookie();for (const tokenData of userTokens) {- // Validate token is still valid+ // Validate token is still valid — use the freshly validated bundle,+ // not the cookie's own (possibly stale) copyconst validation = await validateAccessToken(tokenData.token);if (validation && validation.calendarId === tokenData.calendarId) {- tokens.set(tokenData.calendarId, tokenData.permission);+ tokens.set(tokenData.calendarId, validation.bundleId);}}@@ -87,27 +98,93 @@ export async function GET(request: Request) {const userShares = await db.query.calendarShares.findMany({where: eq(sql`${calendarShares.userId}`, user.id),});- shares = new Map(userShares.map((s) => [s.calendarId, s.permission]));+ shares = new Map(userShares.map((s) => [s.calendarId, s.bundleId]));+ }++ // Batch-resolve every bundle involved (guest, share, token) to its+ // capabilities + identity, so the per-calendar enrichment below is a+ // plain in-memory lookup instead of one resolveCalendarAccess() per+ // calendar (which would re-run the calendar/share/token/subscription+ // lookups already done above, once per row).+ const bundleIds = new Set<string>();+ for (const cal of userCalendars) {+ if (cal.guestBundleId) bundleIds.add(cal.guestBundleId);}+ for (const bundleId of shares.values()) bundleIds.add(bundleId);+ for (const bundleId of tokens.values()) bundleIds.add(bundleId);+ const bundleRows =+ bundleIds.size > 0+ ? await db.query.calendarPermissionBundles.findMany({+ where: (b, { inArray }) => inArray(b.id, Array.from(bundleIds)),+ columns: { id: true, name: true, seedKey: true, capabilities: true },+ })+ : [];+ const capabilitiesByBundleId = new Map(+ bundleRows.map((row) => [row.id, sanitizeCapabilities(row.capabilities)])+ );+ const bundleRefById = new Map<string, CalendarBundleRef>(+ bundleRows.map((row) => [+ row.id,+ { id: row.id, name: row.name, seedKey: row.seedKey },+ ])+ );- // Enrich calendars with permission metadata+ // Enrich calendars with the caller's effective capabilities for that+ // calendar (share > token > subscribed guest bundle for authenticated+ // users; token > guest bundle for guests), matching the priority in+ // resolveCalendarAccess() — computed here in-memory from the batched+ // lookups above instead of re-resolving per calendar.const enrichedCalendars = userCalendars.map((cal) => {- const share = shares.get(cal.id);+ const shareBundleId = shares.get(cal.id);const subscription = subscriptions.get(cal.id);- const token = tokens.get(cal.id);+ const tokenBundleId = tokens.get(cal.id);+ const isOwnerRow = !isAuthEnabled() || cal.ownerId === user?.id;++ let capabilities: Capability[];+ let bundle: CalendarBundleRef | null;+ if (isOwnerRow) {+ capabilities = [...CAPABILITIES];+ bundle = null;+ } else if (shareBundleId) {+ // Invited users (source "share") are never ceilinged — see 5.2.+ capabilities = capabilitiesByBundleId.get(shareBundleId) ?? [];+ bundle = bundleRefById.get(shareBundleId) ?? null;+ } else if (tokenBundleId) {+ capabilities = applyGuestCeiling(capabilitiesByBundleId.get(tokenBundleId) ?? []);+ bundle = bundleRefById.get(tokenBundleId) ?? null;+ } else if (cal.guestBundleId && (!user || subscription)) {+ capabilities = applyGuestCeiling(+ capabilitiesByBundleId.get(cal.guestBundleId) ?? []+ );+ bundle = bundleRefById.get(cal.guestBundleId) ?? null;+ } else {+ capabilities = [];+ bundle = null;+ }// Determine subscription sourcelet subscriptionSource: "guest" | "shared" | "token" | undefined =subscription?.source as "guest" | "shared" | undefined;- if (token && !share && !subscription) {+ if (tokenBundleId && !shareBundleId && !subscription) {subscriptionSource = "token";}+ // Mirrors getShiftSignupPermission() using the capabilities already+ // resolved above, instead of a second resolveCalendarAccess() per row.+ const canSignUp = (capability: "signUpSelf" | "signUpOthers"): boolean => {+ if (!cal.signupsEnabled) return false;+ if (isOwnerRow) return true;+ if (!user?.id) return false;+ return capabilities.includes(capability);+ };+return {...cal,- sharePermission: share || undefined,- tokenPermission: token || undefined,- isSubscribed: !!subscription || !!token,+ capabilities,+ bundle,+ canSignUpSelf: canSignUp("signUpSelf"),+ canSignUpOthers: canSignUp("signUpOthers"),+ isSubscribed: !!subscription || !!tokenBundleId,subscriptionSource,};});@@ -140,7 +217,7 @@ export async function POST(request: NextRequest) {}const body = await request.json();- const { name, color, guestPermission } = body;+ const { name, color } = body;if (!name) {return NextResponse.json(@@ -149,15 +226,35 @@ export async function POST(request: NextRequest) {);}- const [calendar] = await db- .insert(calendars)- .values({- name,- color: color || "#3b82f6",- ownerId: user?.id || null, // Set current user as owner (or null if auth disabled)- guestPermission: guestPermission || "none",- })- .returning();+ // Insert and bundle-seeding happen atomically: a calendar must never+ // exist even briefly without its four recommended bundles, since every+ // permission check assumes they're already there. better-sqlite3+ // transactions must be synchronous (no async/await inside), see+ // seedPermissionBundles().+ const calendar = db.transaction((tx) => {+ const calendar = tx+ .insert(calendars)+ .values({+ name,+ color: color || "#3b82f6",+ ownerId: user?.id || null, // Set current user as owner (or null if auth disabled)+ })+ .returning()+ .get();++ // Every calendar always ships with the four recommended bundles, so+ // it's never "configured from nothing" — see lib/permission-bundles.ts.+ seedPermissionBundles(+ calendar.id,+ defaultBundleDefinitionsForNewCalendar(),+ tx+ );++ return calendar;+ });++ // Guest access is not configurable at creation time — set it afterwards+ // via PATCH /api/calendars/[id], same as any other bundle assignment.// Log calendar creation eventif (user) {diff --git a/app/api/calendars/subscriptions/route.ts b/app/api/calendars/subscriptions/route.tsindex 1e047cb..0a28248 100644--- a/app/api/calendars/subscriptions/route.ts+++ b/app/api/calendars/subscriptions/route.ts@@ -6,8 +6,27 @@ import {userCalendarSubscriptions,} from "@/lib/db/schema";import { getSessionUser } from "@/lib/auth/sessions";-import { eq, and, or, ne, isNull } from "drizzle-orm";+import { eq, and, or, ne, isNotNull, isNull, inArray } from "drizzle-orm";import { undismissCalendar } from "@/lib/auth/permissions";+import {+ applyGuestCeiling,+ sanitizeCapabilities,+ type Capability,+} from "@/lib/permission-bundles";+import type { CalendarBundleRef } from "@/lib/types";++/**+ * A guest bundle's capabilities, ceiling-filtered like every other guest/link+ * source (5.2). Used for "what would I get" previews of a public calendar's+ * guest access — deliberately NOT resolveCalendarAccess()/+ * getEffectiveAccessSummary(), which require an active "subscribed"+ * subscription and would return no access at all for a calendar the caller+ * hasn't subscribed to (or has dismissed) yet, exactly the two cases this+ * preview needs to cover.+ */+function previewGuestCapabilities(capabilities: unknown) {+ return applyGuestCeiling(sanitizeCapabilities(capabilities));+}/*** GET /api/calendars/subscriptions@@ -24,10 +43,10 @@ export async function GET(request: NextRequest) {}try {- // Get all public calendars (guestPermission != "none", not owned by user)+ // Get all public calendars (guestBundleId set, not owned by user)const allPublicCalendars = await db.query.calendars.findMany({where: and(- ne(calendars.guestPermission, "none"),+ isNotNull(calendars.guestBundleId),or(isNull(calendars.ownerId), ne(calendars.ownerId, user.id))),with: {@@ -38,6 +57,9 @@ export async function GET(request: NextRequest) {email: true,},},+ guestBundle: {+ columns: { id: true, name: true, seedKey: true, capabilities: true },+ },},});@@ -62,6 +84,9 @@ export async function GET(request: NextRequest) {const userShares = await db.query.calendarShares.findMany({where: eq(calendarShares.userId, user.id),with: {+ bundle: {+ columns: { id: true, name: true, seedKey: true, capabilities: true },+ },calendar: {with: {owner: {@@ -70,11 +95,28 @@ export async function GET(request: NextRequest) {name: true,},},+ guestBundle: {+ columns: { id: true, name: true, seedKey: true },+ },},},},});+ // A share's capabilities come straight from its bundle — shares are never+ // ceilinged (5.2) — so this avoids a getEffectiveAccessSummary() /+ // resolveCalendarAccess() re-fetch of the same share row per calendar.+ const shareAccess = (+ share: (typeof userShares)[number]+ ): { capabilities: Capability[]; bundle: CalendarBundleRef } => ({+ capabilities: sanitizeCapabilities(share.bundle.capabilities),+ bundle: {+ id: share.bundle.id,+ name: share.bundle.name,+ seedKey: share.bundle.seedKey,+ },+ });+const dismissedIds = new Set(dismissedSubs.map((sub) => sub.calendarId));// Filter out dismissed shares from userShares before building sharedIds@@ -94,7 +136,10 @@ export async function GET(request: NextRequest) {id: cal.id,name: cal.name,color: cal.color,- guestPermission: cal.guestPermission,+ capabilities: cal.guestBundle+ ? previewGuestCapabilities(cal.guestBundle.capabilities)+ : [],+ bundle: cal.guestBundle ?? null,owner: cal.owner? {id: cal.owner.id,@@ -105,61 +150,97 @@ export async function GET(request: NextRequest) {source: "guest" as const,}));- // Add shared calendars to available list (already filtered for dismissed in activeShares)- const sharedCalendars = activeShares.map((share) => ({- id: share.calendar.id,- name: share.calendar.name,- color: share.calendar.color,- permission: share.permission, // User's share permission level- guestPermission: share.calendar.guestPermission, // Calendar's guest permission (for reference)- owner: share.calendar.owner- ? {- id: share.calendar.owner.id,- name: share.calendar.owner.name,- }- : null,- isSubscribed: subscribedIds.has(share.calendarId),- source: "shared" as const,- }));+ // Add shared calendars to available list (already filtered for dismissed+ // in activeShares). A share is unaffected by subscription/dismissal+ // status, so its bundle always applies.+ const sharedCalendars = activeShares.map((share) => {+ const access = shareAccess(share);+ return {+ id: share.calendar.id,+ name: share.calendar.name,+ color: share.calendar.color,+ capabilities: access.capabilities,+ bundle: access.bundle,+ guestBundle: share.calendar.guestBundle ?? null, // for reference+ owner: share.calendar.owner+ ? {+ id: share.calendar.owner.id,+ name: share.calendar.owner.name,+ }+ : null,+ isSubscribed: subscribedIds.has(share.calendarId),+ source: "shared" as const,+ };+ });const availableCalendars = [...publicCalendars, ...sharedCalendars];- // Build dismissed calendars list (both shared and guest-subscribed)- const dismissedCalendars = await Promise.all(- dismissedSubs.map(async (sub) => {- const calendar = await db.query.calendars.findFirst({- where: eq(calendars.id, sub.calendarId),- with: {- owner: {- columns: {- id: true,- name: true,+ // Build dismissed calendars list (both shared and guest-subscribed). A+ // share-backed one uses its bundle directly, same as sharedCalendars+ // above; a guest-only one previews the guest bundle directly, since+ // dismissing sets status to "dismissed" and resolveCalendarAccess()+ // would otherwise report no access at all for it.+ // Batched (one query for every dismissed calendar) rather than one+ // findFirst per row — this list scales with how many calendars a user+ // has dismissed over time, not just their currently-visible ones.+ const dismissedCalendarIds = dismissedSubs.map((sub) => sub.calendarId);+ const dismissedCalendarRows =+ dismissedCalendarIds.length > 0+ ? await db.query.calendars.findMany({+ where: inArray(calendars.id, dismissedCalendarIds),+ with: {+ owner: {+ columns: {+ id: true,+ name: true,+ },+ },+ guestBundle: {+ columns: {+ id: true,+ name: true,+ seedKey: true,+ capabilities: true,+ },},},- },- });-- if (!calendar) return null;-- // Check if it's also a shared calendar- const share = userShares.find((s) => s.calendarId === sub.calendarId);-- return {- id: calendar.id,- name: calendar.name,- color: calendar.color,- permission: share ? share.permission : calendar.guestPermission,- owner: calendar.owner- ? {- id: calendar.owner.id,- name: calendar.owner.name,- }- : null,- source: sub.source,- };- })+ })+ : [];+ const dismissedCalendarById = new Map(+ dismissedCalendarRows.map((cal) => [cal.id, cal]));+ const dismissedCalendars = dismissedSubs.map((sub) => {+ const calendar = dismissedCalendarById.get(sub.calendarId);+ if (!calendar) return null;++ // Check if it's also a shared calendar+ const share = userShares.find((s) => s.calendarId === sub.calendarId);+ const access = share ? shareAccess(share) : null;++ const capabilities = access+ ? access.capabilities+ : calendar.guestBundle+ ? previewGuestCapabilities(calendar.guestBundle.capabilities)+ : [];+ const bundle = access ? access.bundle : (calendar.guestBundle ?? null);++ return {+ id: calendar.id,+ name: calendar.name,+ color: calendar.color,+ capabilities,+ bundle,+ owner: calendar.owner+ ? {+ id: calendar.owner.id,+ name: calendar.owner.name,+ }+ : null,+ source: sub.source,+ };+ });+// Filter out nullsconst validDismissedCalendars = dismissedCalendars.filter((cal): cal is NonNullable<typeof cal> => cal !== nulldiff --git a/app/api/export/ics/route.ts b/app/api/export/ics/route.tsindex fc4c07d..bd32d30 100644--- a/app/api/export/ics/route.ts+++ b/app/api/export/ics/route.ts@@ -4,7 +4,7 @@ import { calendars, shifts } from "@/lib/db/schema";import { inArray } from "drizzle-orm";import ICAL from "ical.js";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar } from "@/lib/auth/permissions";+import { hasCapability } from "@/lib/auth/permissions";import { getServerTimezone, formatDateToLocal } from "@/lib/date-utils";import { rateLimit } from "@/lib/rate-limiter";@@ -38,13 +38,14 @@ export async function POST(request: NextRequest) {}// Filter calendars by permission - only include calendars user can view- const accessibleCalendars = [];- for (const calendar of requestedCalendars) {- const hasAccess = await canViewCalendar(user?.id, calendar.id);- if (hasAccess) {- accessibleCalendars.push(calendar);- }- }+ const accessFlags = await Promise.all(+ requestedCalendars.map((calendar) =>+ hasCapability(user?.id, calendar.id, "viewShifts")+ )+ );+ const accessibleCalendars = requestedCalendars.filter(+ (_, i) => accessFlags[i]+ );if (accessibleCalendars.length === 0) {return NextResponse.json(diff --git a/app/api/export/pdf/route.ts b/app/api/export/pdf/route.tsindex 26236c4..51f9cf0 100644--- a/app/api/export/pdf/route.ts+++ b/app/api/export/pdf/route.ts@@ -4,7 +4,7 @@ import { calendars, shifts } from "@/lib/db/schema";import { inArray } from "drizzle-orm";import { jsPDF } from "jspdf";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar } from "@/lib/auth/permissions";+import { hasCapability } from "@/lib/auth/permissions";import { rateLimit } from "@/lib/rate-limiter";import { formatDateToLocal } from "@/lib/date-utils";@@ -43,13 +43,14 @@ export async function POST(request: NextRequest) {}// Filter calendars by permission - only include calendars user can view- const accessibleCalendars = [];- for (const calendar of requestedCalendars) {- const hasAccess = await canViewCalendar(user?.id, calendar.id);- if (hasAccess) {- accessibleCalendars.push(calendar);- }- }+ const accessFlags = await Promise.all(+ requestedCalendars.map((calendar) =>+ hasCapability(user?.id, calendar.id, "viewShifts")+ )+ );+ const accessibleCalendars = requestedCalendars.filter(+ (_, i) => accessFlags[i]+ );if (accessibleCalendars.length === 0) {return NextResponse.json(diff --git a/app/api/external-syncs/[id]/route.ts b/app/api/external-syncs/[id]/route.tsindex 480845b..c5136ed 100644--- a/app/api/external-syncs/[id]/route.ts+++ b/app/api/external-syncs/[id]/route.ts@@ -3,7 +3,7 @@ import { db } from "@/lib/db";import { externalSyncs, shifts, calendars } from "@/lib/db/schema";import { eq } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";+import { hasCapability } from "@/lib/auth/permissions";import {isValidCalendarUrl,type CalendarSyncType,@@ -46,7 +46,11 @@ export async function GET(// Check view permissions (works for both authenticated users and guests)const user = await getSessionUser(request.headers);- const hasAccess = await canViewCalendar(user?.id, externalSync.calendarId);+ const hasAccess = await hasCapability(+ user?.id,+ externalSync.calendarId,+ "viewShifts"+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions. Read access required." },@@ -111,7 +115,11 @@ export async function PATCH(// Check edit permissions (works for both authenticated users and guests)const user = await getSessionUser(request.headers);- const hasAccess = await canEditCalendar(user?.id, existingSync.calendarId);+ const hasAccess = await hasCapability(+ user?.id,+ existingSync.calendarId,+ "manageExternalSync"+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions. Write access required." },@@ -237,7 +245,11 @@ export async function DELETE(// Check edit permissions (works for both authenticated users and guests)const user = await getSessionUser(request.headers);- const hasAccess = await canEditCalendar(user?.id, existingSync.calendarId);+ const hasAccess = await hasCapability(+ user?.id,+ existingSync.calendarId,+ "manageExternalSync"+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions. Write access required." },diff --git a/app/api/external-syncs/[id]/sync/route.ts b/app/api/external-syncs/[id]/sync/route.tsindex b09f0f6..ddba704 100644--- a/app/api/external-syncs/[id]/sync/route.ts+++ b/app/api/external-syncs/[id]/sync/route.ts@@ -4,7 +4,7 @@ import { externalSyncs, shifts, syncLogs, calendars } from "@/lib/db/schema";import { eq, inArray } from "drizzle-orm";import ICAL from "ical.js";import { getSessionUser } from "@/lib/auth/sessions";-import { canEditCalendar } from "@/lib/auth/permissions";+import { hasCapability } from "@/lib/auth/permissions";import {expandRecurringEvents,splitMultiDayEvent,@@ -490,7 +490,11 @@ export async function POST(}// Check edit permissions (works for both authenticated users and guests)- const hasAccess = await canEditCalendar(user?.id, externalSync.calendarId);+ const hasAccess = await hasCapability(+ user?.id,+ externalSync.calendarId,+ "manageExternalSync"+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions. Write access required." },diff --git a/app/api/external-syncs/route.ts b/app/api/external-syncs/route.tsindex 102a4dc..020ff5a 100644--- a/app/api/external-syncs/route.ts+++ b/app/api/external-syncs/route.ts@@ -3,7 +3,7 @@ import { db } from "@/lib/db";import { externalSyncs, calendars } from "@/lib/db/schema";import { eq, desc } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";+import { hasCapability } from "@/lib/auth/permissions";import {isValidCalendarUrl,detectCalendarSyncType,@@ -40,7 +40,7 @@ export async function GET(request: NextRequest) {// Check view permissions (works for both authenticated users and guests)const user = await getSessionUser(request.headers);- const hasAccess = await canViewCalendar(user?.id, calendarId);+ const hasAccess = await hasCapability(user?.id, calendarId, "viewShifts");if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions. Read access required." },@@ -104,7 +104,11 @@ export async function POST(request: NextRequest) {// Check edit permissions (works for both authenticated users and guests)const user = await getSessionUser(request.headers);- const hasAccess = await canEditCalendar(user?.id, calendarId);+ const hasAccess = await hasCapability(+ user?.id,+ calendarId,+ "manageExternalSync"+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions. Write access required." },diff --git a/app/api/notes/[id]/route.ts b/app/api/notes/[id]/route.tsindex 7a88593..0ce1343 100644--- a/app/api/notes/[id]/route.ts+++ b/app/api/notes/[id]/route.ts@@ -3,7 +3,7 @@ import { db } from "@/lib/db";import { calendarNotes, calendars } from "@/lib/db/schema";import { eq } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";+import { hasCapability, hasOwnedCapability } from "@/lib/auth/permissions";// GET single calendar noteexport async function GET(@@ -40,7 +40,11 @@ export async function GET(// Check permissions (works for both authenticated users and guests)const user = await getSessionUser(request.headers);- const hasAccess = await canViewCalendar(user?.id, calendar.id);+ const hasAccess = await hasCapability(+ user?.id,+ calendar.id,+ "viewNotesEvents"+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },@@ -100,7 +104,13 @@ export async function PUT(// Check permissions (works for both authenticated users and guests)const user = await getSessionUser(request.headers);- const hasAccess = await canEditCalendar(user?.id, calendar.id);+ const hasAccess = await hasOwnedCapability(+ user?.id,+ calendar.id,+ "manageOwnNotesEvents",+ "manageAnyNotesEvents",+ existingNote.createdBy+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },@@ -193,7 +203,13 @@ export async function DELETE(// Check permissions (works for both authenticated users and guests)const user = await getSessionUser(request.headers);- const hasAccess = await canEditCalendar(user?.id, calendar.id);+ const hasAccess = await hasOwnedCapability(+ user?.id,+ calendar.id,+ "manageOwnNotesEvents",+ "manageAnyNotesEvents",+ existingNote.createdBy+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },diff --git a/app/api/notes/route.ts b/app/api/notes/route.tsindex 1f5dc6e..f12492d 100644--- a/app/api/notes/route.ts+++ b/app/api/notes/route.ts@@ -3,7 +3,7 @@ import { db } from "@/lib/db";import { calendarNotes, calendars } from "@/lib/db/schema";import { eq, and, gte, lte } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";+import { hasCapability, hasOwnedCapability } from "@/lib/auth/permissions";import { parseLocalDate } from "@/lib/date-utils";// GET calendar notes for a calendar (with optional date filter)@@ -35,7 +35,7 @@ export async function GET(request: Request) {// Check permissions (works for both authenticated users and guests)const user = await getSessionUser(request.headers);- const hasAccess = await canViewCalendar(user?.id, calendar.id);+ const hasAccess = await hasCapability(user?.id, calendar.id, "viewNotesEvents");if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },@@ -129,9 +129,18 @@ export async function POST(request: Request) {);}- // Check permissions (works for both authenticated users and guests)+ // Check permissions (works for both authenticated users and guests).+ // Creating needs either capability — own vs. any only matters once the+ // note exists, for editing/deleting it. The caller is the note's future+ // creator, so passing their id as createdBy folds that check in too.const user = await getSessionUser(request.headers);- const hasAccess = await canEditCalendar(user?.id, calendar.id);+ const hasAccess = await hasOwnedCapability(+ user?.id,+ calendar.id,+ "manageOwnNotesEvents",+ "manageAnyNotesEvents",+ user?.id ?? null+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },@@ -159,6 +168,7 @@ export async function POST(request: Request) {color: color || null,recurringPattern: recurringPattern || "none",recurringInterval: recurringInterval || null,+ createdBy: user?.id ?? null,}).returning();diff --git a/app/api/presets/[id]/route.ts b/app/api/presets/[id]/route.tsindex 70daeef..24ea855 100644--- a/app/api/presets/[id]/route.ts+++ b/app/api/presets/[id]/route.ts@@ -1,9 +1,9 @@import { NextRequest, NextResponse } from "next/server";import { db } from "@/lib/db";import { shiftPresets, shifts, calendars } from "@/lib/db/schema";-import { eq } from "drizzle-orm";+import { and, eq } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";+import { hasCapability, hasOwnedCapability } from "@/lib/auth/permissions";import { trimOrNull } from "@/lib/utils";// GET single preset@@ -38,7 +38,11 @@ export async function GET(}// Check read permission (works for both authenticated users and guests)- const hasAccess = await canViewCalendar(user?.id, preset.calendarId);+ const hasAccess = await hasCapability(+ user?.id,+ preset.calendarId,+ "viewShifts"+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },@@ -114,9 +118,12 @@ export async function PATCH(}// Check edit permission (works for both authenticated users and guests)- const hasAccess = await canEditCalendar(+ const hasAccess = await hasOwnedCapability(user?.id,- existingPreset.calendarId+ existingPreset.calendarId,+ "manageOwnPresets",+ "manageAnyPresets",+ existingPreset.createdBy);if (!hasAccess) {return NextResponse.json(@@ -158,7 +165,12 @@ export async function PATCH(isAllDay: isAllDay !== undefined ? isAllDay : undefined,updatedAt: new Date(),})- .where(eq(shifts.presetId, id));+ .where(+ and(+ eq(shifts.presetId, id),+ eq(shifts.calendarId, existingPreset.calendarId)+ )+ );return NextResponse.json(updatedPreset);} catch (error) {@@ -203,7 +215,13 @@ export async function DELETE(}// Check edit permission (works for both authenticated users and guests)- const hasAccess = await canEditCalendar(user?.id, preset.calendarId);+ const hasAccess = await hasOwnedCapability(+ user?.id,+ preset.calendarId,+ "manageOwnPresets",+ "manageAnyPresets",+ preset.createdBy+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },@@ -212,7 +230,11 @@ export async function DELETE(}// Delete all shifts that were created from this preset- await db.delete(shifts).where(eq(shifts.presetId, id));+ await db+ .delete(shifts)+ .where(+ and(eq(shifts.presetId, id), eq(shifts.calendarId, preset.calendarId))+ );// Delete the presetawait db.delete(shiftPresets).where(eq(shiftPresets.id, id));diff --git a/app/api/presets/reorder/route.ts b/app/api/presets/reorder/route.tsindex b5ebbb8..84b6d28 100644--- a/app/api/presets/reorder/route.ts+++ b/app/api/presets/reorder/route.ts@@ -3,7 +3,7 @@ import { db } from "@/lib/db";import { shiftPresets, calendars } from "@/lib/db/schema";import { eq } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { canEditCalendar } from "@/lib/auth/permissions";+import { hasCapability } from "@/lib/auth/permissions";// PATCH reorder presetsexport async function PATCH(request: NextRequest) {@@ -49,8 +49,14 @@ export async function PATCH(request: NextRequest) {);}- // Check edit permission (works for both authenticated users and guests)- const hasAccess = await canEditCalendar(user?.id, calendarId);+ // Check edit permission (works for both authenticated users and guests).+ // Reordering changes the shared order for everyone, so it always needs+ // manageAnyPresets — manageOwnPresets alone isn't enough (5.1).+ const hasAccess = await hasCapability(+ user?.id,+ calendarId,+ "manageAnyPresets"+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },diff --git a/app/api/presets/route.ts b/app/api/presets/route.tsindex 687eb62..7ec5add 100644--- a/app/api/presets/route.ts+++ b/app/api/presets/route.ts@@ -3,7 +3,7 @@ import { db } from "@/lib/db";import { shiftPresets, calendars } from "@/lib/db/schema";import { eq, asc } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";+import { hasCapability } from "@/lib/auth/permissions";import { trimOrNull } from "@/lib/utils";// GET all presets for a calendar@@ -35,7 +35,7 @@ export async function GET(request: NextRequest) {}// Check read permission (works for both authenticated users and guests)- const hasAccess = await canViewCalendar(user?.id, calendarId);+ const hasAccess = await hasCapability(user?.id, calendarId, "viewShifts");if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },@@ -98,8 +98,8 @@ export async function POST(request: NextRequest) {);}- // Check edit permission (works for both authenticated users and guests)- const hasAccess = await canEditCalendar(user?.id, calendarId);+ // Check create permission (works for both authenticated users and guests)+ const hasAccess = await hasCapability(user?.id, calendarId, "createPreset");if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },@@ -136,6 +136,7 @@ export async function POST(request: NextRequest) {? defaultSignupCapacity: null,order: maxOrder + 1,+ createdBy: user?.id ?? null,}).returning();diff --git a/app/api/shifts/[id]/route.ts b/app/api/shifts/[id]/route.tsindex 9311361..e2882b2 100644--- a/app/api/shifts/[id]/route.ts+++ b/app/api/shifts/[id]/route.ts@@ -1,9 +1,9 @@import { NextResponse } from "next/server";import { db } from "@/lib/db";-import { calendars, shifts } from "@/lib/db/schema";-import { eq } from "drizzle-orm";+import { calendars, shiftPresets, shifts } from "@/lib/db/schema";+import { and, eq } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";+import { hasCapability, hasOwnedCapability } from "@/lib/auth/permissions";import { parseLocalDate } from "@/lib/date-utils";// GET single shift@@ -45,7 +45,11 @@ export async function GET(}// Check read permission (works for both authenticated users and guests)- const hasAccess = await canViewCalendar(user?.id, result[0].calendarId);+ const hasAccess = await hasCapability(+ user?.id,+ result[0].calendarId,+ "viewShifts"+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },@@ -80,7 +84,13 @@ export async function DELETE(}// Check write permission (works for both authenticated users and guests)- const hasAccess = await canEditCalendar(user?.id, shift.calendarId);+ const hasAccess = await hasOwnedCapability(+ user?.id,+ shift.calendarId,+ "deleteOwnShift",+ "deleteAnyShift",+ shift.createdBy+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions. Write access required." },@@ -126,7 +136,13 @@ export async function PUT(}// Check write permission (works for both authenticated users and guests)- const hasAccess = await canEditCalendar(user?.id, existingShift.calendarId);+ const hasAccess = await hasOwnedCapability(+ user?.id,+ existingShift.calendarId,+ "editOwnShift",+ "editAnyShift",+ existingShift.createdBy+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions. Write access required." },@@ -154,6 +170,26 @@ export async function PUT(}}+ // A client-submitted presetId must belong to the shift's own calendar,+ // otherwise a shift could get silently linked to another calendar's preset.+ if (body.presetId && body.presetId !== existingShift.presetId) {+ const [preset] = await db+ .select()+ .from(shiftPresets)+ .where(+ and(+ eq(shiftPresets.id, body.presetId),+ eq(shiftPresets.calendarId, existingShift.calendarId)+ )+ );+ if (!preset) {+ return NextResponse.json(+ { error: "Preset not found" },+ { status: 404 }+ );+ }+ }+// Update the shiftconst [updatedShift] = await db.update(shifts)diff --git a/app/api/shifts/[id]/signups/route.ts b/app/api/shifts/[id]/signups/route.tsindex a13519d..cad801f 100644--- a/app/api/shifts/[id]/signups/route.ts+++ b/app/api/shifts/[id]/signups/route.ts@@ -1,6 +1,6 @@import { NextResponse } from "next/server";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar } from "@/lib/auth/permissions";+import { hasCapability } from "@/lib/auth/permissions";import { addShiftSignup, getShiftOrNull, getShiftSignupUsers } from "@/lib/shift-signups";// GET all signups for a shift@@ -17,7 +17,11 @@ export async function GET(return NextResponse.json({ error: "Shift not found" }, { status: 404 });}- const hasAccess = await canViewCalendar(user?.id, shift.calendarId);+ const hasAccess = await hasCapability(+ user?.id,+ shift.calendarId,+ "viewShifts"+ );if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },diff --git a/app/api/shifts/route.ts b/app/api/shifts/route.tsindex 6cf273f..0f36986 100644--- a/app/api/shifts/route.ts+++ b/app/api/shifts/route.ts@@ -1,9 +1,9 @@import { NextResponse } from "next/server";import { db } from "@/lib/db";-import { calendars, shifts, externalSyncs } from "@/lib/db/schema";+import { calendars, shifts, shiftPresets, externalSyncs } from "@/lib/db/schema";import { eq, and, gte, lte, or, isNull } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";+import { hasCapability, getCalendarAccess } from "@/lib/auth/permissions";import { addShiftSignup, withSignups } from "@/lib/shift-signups";import { parseLocalDate } from "@/lib/date-utils";import type { CalendarMember } from "@/lib/types";@@ -38,7 +38,7 @@ export async function GET(request: Request) {}// Check read permission (works for both authenticated users and guests)- const hasAccess = await canViewCalendar(user?.id, calendarId);+ const hasAccess = await hasCapability(user?.id, calendarId, "viewShifts");if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },@@ -61,6 +61,7 @@ export async function GET(request: Request) {signupCapacity: shifts.signupCapacity,syncedFromExternal: shifts.syncedFromExternal,externalSyncId: shifts.externalSyncId,+ createdBy: shifts.createdBy,createdAt: shifts.createdAt,updatedAt: shifts.updatedAt,calendar: {@@ -158,9 +159,12 @@ export async function POST(request: Request) {);}- // Check write permission (works for both authenticated users and guests)- const hasAccess = await canEditCalendar(user?.id, calendarId);- if (!hasAccess) {+ // A caller needs at least one of the two shift-creation capabilities.+ const access = await getCalendarAccess(user?.id, calendarId);+ if (+ !access ||+ !(access.can("stampPreset") || access.can("createShift"))+ ) {return NextResponse.json({ error: "Insufficient permissions. Write access required." },{ status: 403 }@@ -177,21 +181,88 @@ export async function POST(request: Request) {);}+ // A caller with only stampPreset (no createShift) can only stamp an+ // existing preset as-is — pull title/time/color/notes/isAllDay from the+ // preset record itself instead of trusting client-submitted overrides,+ // otherwise "presets only" is trivially bypassed by sending presetId+ // alongside arbitrary fields.+ let insertValues: {+ title: string;+ startTime: string;+ endTime: string;+ color: string;+ notes: string | null;+ isAllDay: boolean;+ };+ if (access.can("createShift")) {+ if (presetId) {+ const [preset] = await db+ .select()+ .from(shiftPresets)+ .where(+ and(+ eq(shiftPresets.id, presetId),+ eq(shiftPresets.calendarId, calendarId)+ )+ );+ if (!preset) {+ return NextResponse.json(+ { error: "Preset not found" },+ { status: 404 }+ );+ }+ }+ insertValues = {+ title,+ startTime: isAllDay ? "00:00" : startTime,+ endTime: isAllDay ? "23:59" : endTime,+ color: color || "#3b82f6",+ notes: notes || null,+ isAllDay: isAllDay || false,+ };+ } else {+ if (!presetId) {+ return NextResponse.json(+ { error: "presetId is required" },+ { status: 400 }+ );+ }+ const [preset] = await db+ .select()+ .from(shiftPresets)+ .where(+ and(+ eq(shiftPresets.id, presetId),+ eq(shiftPresets.calendarId, calendarId)+ )+ );+ if (!preset) {+ return NextResponse.json(+ { error: "Preset not found" },+ { status: 404 }+ );+ }+ insertValues = {+ title: preset.title,+ startTime: preset.isAllDay ? "00:00" : preset.startTime,+ endTime: preset.isAllDay ? "23:59" : preset.endTime,+ color: preset.color,+ notes: preset.notes,+ isAllDay: preset.isAllDay,+ };+ }+const [shift] = await db.insert(shifts).values({calendarId,presetId: presetId || null,date: parsedDate,- startTime: isAllDay ? "00:00" : startTime,- endTime: isAllDay ? "23:59" : endTime,- title,- color: color || "#3b82f6",- notes: notes || null,- isAllDay: isAllDay || false,+ ...insertValues,isSecondary: isSecondary || false,signupCapacity:typeof signupCapacity === "number" ? signupCapacity : null,+ createdBy: user?.id ?? null,createdAt: new Date(),updatedAt: new Date(),})diff --git a/app/api/shifts/stats/route.ts b/app/api/shifts/stats/route.tsindex 7822d57..c3705c4 100644--- a/app/api/shifts/stats/route.ts+++ b/app/api/shifts/stats/route.ts@@ -8,7 +8,7 @@ import {} from "@/lib/db/schema";import { eq, and, gte, lte, or, isNull } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar } from "@/lib/auth/permissions";+import { hasCapability } from "@/lib/auth/permissions";import {calculateShiftDuration,formatDateToLocal,@@ -54,7 +54,7 @@ export async function GET(request: Request) {}// Check read permission (works for both authenticated users and guests)- const hasAccess = await canViewCalendar(user?.id, calendarId);+ const hasAccess = await hasCapability(user?.id, calendarId, "viewStats");if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },diff --git a/app/api/sync-logs/route.ts b/app/api/sync-logs/route.tsindex 67ba162..b5dc6fe 100644--- a/app/api/sync-logs/route.ts+++ b/app/api/sync-logs/route.ts@@ -3,7 +3,7 @@ import { db } from "@/lib/db";import { syncLogs, calendars } from "@/lib/db/schema";import { eq, desc, and } from "drizzle-orm";import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";+import { hasCapability } from "@/lib/auth/permissions";export async function GET(request: NextRequest) {const searchParams = request.nextUrl.searchParams;@@ -34,7 +34,7 @@ export async function GET(request: NextRequest) {}// Check read permission (works for both authenticated users and guests)- const hasAccess = await canViewCalendar(user?.id, calendarId);+ const hasAccess = await hasCapability(user?.id, calendarId, "viewShifts");if (!hasAccess) {return NextResponse.json({ error: "Insufficient permissions" },@@ -88,7 +88,11 @@ export async function PATCH(request: NextRequest) {}// Check write permission (works for both authenticated users and guests)- const hasWriteAccess = await canEditCalendar(user?.id, calendarId);+ const hasWriteAccess = await hasCapability(+ user?.id,+ calendarId,+ "manageExternalSync"+ );if (!hasWriteAccess) {return NextResponse.json({ error: "Insufficient permissions. Write access required." },@@ -146,7 +150,11 @@ export async function DELETE(request: NextRequest) {}// Check write permission (works for both authenticated users and guests)- const hasWriteAccess = await canEditCalendar(user?.id, calendarId);+ const hasWriteAccess = await hasCapability(+ user?.id,+ calendarId,+ "deleteSyncLogs"+ );if (!hasWriteAccess) {return NextResponse.json({ error: "Insufficient permissions. Write access required." },diff --git a/app/api/users/search/route.ts b/app/api/users/search/route.tsindex b5b1074..7b110d8 100644--- a/app/api/users/search/route.ts+++ b/app/api/users/search/route.ts@@ -1,7 +1,7 @@import { NextRequest, NextResponse } from "next/server";import { db } from "@/lib/db";import { getSessionUser } from "@/lib/auth/sessions";-import { checkPermission } from "@/lib/auth/permissions";+import { hasCapability } from "@/lib/auth/permissions";import { or, and, ne, sql } from "drizzle-orm";import { user as userTable } from "@/lib/db/schema";import { rateLimit } from "@/lib/rate-limiter";@@ -46,10 +46,10 @@ export async function GET(request: NextRequest) {}// Only calendar admins/owners may search for users to share the calendar with- const hasPermission = await checkPermission(+ const hasPermission = await hasCapability(currentUser.id,calendarId,- "admin"+ "manageShares");if (!hasPermission) {return NextResponse.json(diff --git a/app/page.tsx b/app/page.tsxindex f0924ba..7f5a55f 100644--- a/app/page.tsx+++ b/app/page.tsx@@ -81,7 +81,15 @@ function HomeContent() {hasLoadedOnce: presetsLoadedOnce,} = usePresets(selectedCalendar);- const { canEdit, canManage } = useCalendarPermission(selectedCalendar);+ const { can, canOwned } = useCalendarPermission(selectedCalendar);+ // Own/Any precision (Paket 5b): a single calendar-wide boolean can't express who+ // may touch a specific shift, so callers needing per-shift precision get these closures+ // instead of a coarse canEdit — kept in sync with CalendarWorkspace/DialogManager below.+ // Edit and delete are independent capabilities (a bundle can grant one without the other).+ const canEditShift = (shift: ShiftWithCalendar) =>+ canOwned("editOwnShift", "editAnyShift", shift.createdBy ?? null);+ const canDeleteShift = (shift: ShiftWithCalendar) =>+ canOwned("deleteOwnShift", "deleteAnyShift", shift.createdBy ?? null);// Toasts are owned by CalendarWorkspace; this is only the stamping gateconst { isOnline } = useConnectionStatus({ toasts: false });@@ -155,7 +163,7 @@ function HomeContent() {deleteNote: deleteNoteHook,} = useNotes(isCompareMode ? compareNoteCalendarId : selectedCalendar);const { externalSyncs, hasSyncErrors } = useExternalSync(- canManage ? selectedCalendar || null : null+ can("manageExternalSync") ? selectedCalendar || null : null);const viewSettings = useViewSettings();@@ -287,7 +295,7 @@ function HomeContent() {// the dock. Derived here so a day click can never stamp without it on screen.const presetIdSet = new Set(presets.map((p) => p.id));const armedPresetIds =- canEdit && isOnline && calendarView.showStampBar+ can("createShift") && isOnline && calendarView.showStampBar? selectedPresetIds.filter((id) => presetIdSet.has(id)): [];@@ -343,7 +351,8 @@ function HomeContent() {onAddNewNote={handleAddNewNoteFromList}currentDate={currentDate}shifts={shifts}- canEditShifts={canEdit}+ canEditShift={canEditShift}+ canDeleteShift={canDeleteShift}showMonthStatsDialog={dialogStates.showMonthStatsDialog}onMonthStatsDialogChange={dialogStates.setShowMonthStatsDialog}showMonthShiftsDialog={dialogStates.showMonthShiftsDialog}@@ -444,7 +453,7 @@ function HomeContent() {selectedCalendar={selectedCalendar}currentDate={currentDate}hasSyncErrors={hasSyncErrors}- canManageSync={canManage}+ canManageSync={can("manageExternalSync")}onDateChange={handleDateChange}onSelectCalendar={setSelectedCalendar}onCreateCalendar={() => dialogStates.setShowCalendarDialog(true)}@@ -477,7 +486,10 @@ function HomeContent() {showShiftNotes={calendarView.showShiftNotes}highlightedWeekdays={calendarView.highlightedWeekdays}highlightColor={calendarView.highlightColor}- canEdit={canEdit}+ canCreateShift={can("createShift")}+ canAddNote={can("manageOwnNotesEvents")}+ canEditShift={canEditShift}+ canDeleteShift={canDeleteShift}showStampBar={calendarView.showStampBar}selectedPresetIds={armedPresetIds}onSelectPreset={handlePresetSelection}diff --git a/components/admin/calendar-details-sheet.tsx b/components/admin/calendar-details-sheet.tsxindex 591e8ca..0cd6657 100644--- a/components/admin/calendar-details-sheet.tsx+++ b/components/admin/calendar-details-sheet.tsx@@ -3,12 +3,13 @@import { useQuery } from "@tanstack/react-query";import { useLocale, useTranslations } from "next-intl";import { format } from "date-fns";-import { CloudDownload, Eye, EyeOff, Link2, Pencil, Send, SquarePen, Trash2 } from "lucide-react";+import { CloudDownload, Eye, EyeOff, Link2, Pencil, Send, Trash2 } from "lucide-react";import { Button } from "@/components/ui/button";import { ListRow, Pill } from "@/components/form-kit";import { AdminDetailPanel } from "@/components/admin/admin-detail-panel";import { DetailSection, StatTile, UserAvatar } from "@/components/admin/admin-kit";import { isOrphaned, ownerColor } from "@/components/admin/calendar-table";+import { useBundleDisplayName } from "@/components/permission-bundle-picker";import { fetchAdminCalendarDetails } from "@/hooks/useAdminCalendars";import {useCanEditCalendar,@@ -28,13 +29,6 @@ interface CalendarDetailsSheetProps {onDelete: () => void;}-function PermissionPill({ permission }: { permission: string }) {- const t = useTranslations();- if (permission === "admin") return <Pill tone="violet">{t("common.labels.permissions.admin")}</Pill>;- if (permission === "write") return <Pill tone="brand">{t("common.labels.permissions.write")}</Pill>;- return <Pill>{t("common.labels.permissions.read")}</Pill>;-}-export function CalendarDetailsSheet({open,onOpenChange,@@ -55,24 +49,19 @@ export function CalendarDetailsSheet({const canEdit = useCanEditCalendar();const canDelete = useCanDeleteCalendar();const canTransfer = useCanTransferCalendar();+ const displayName = useBundleDisplayName();const date = (value: Date) => format(value, "PP", { locale: dateLocale });const orphaned = calendar ? isOrphaned(calendar) : false;- const guest = calendar?.guestPermission;- const GuestIcon = guest === "write" ? SquarePen : guest === "read" ? Eye : EyeOff;- const guestLabel =- guest === "write"- ? t("common.labels.permissions.write")- : guest === "read"- ? t("common.labels.permissions.read")- : t("common.labels.permissions.none");- const guestHint =- guest === "write"- ? t("adminCalendars.guestWriteHint")- : guest === "read"- ? t("adminCalendars.guestReadHint")- : t("adminCalendars.guestNoneHint");+ const guestBundle = calendar?.guestBundle ?? null;+ const GuestIcon = guestBundle ? Eye : EyeOff;+ const guestLabel = guestBundle+ ? (displayName(guestBundle) ?? "")+ : t("common.labels.permissions.none");+ const guestHint = guestBundle+ ? t("adminCalendars.guestBundleHint")+ : t("adminCalendars.guestNoneHint");const footer = (canEdit || canTransfer || canDelete) && calendar && (<>@@ -196,7 +185,7 @@ export function CalendarDetailsSheet({<div className="truncate text-[13.5px] font-semibold text-fg-strong">{share.userName}</div><div className="truncate text-[12px] text-fg-tertiary">{share.userEmail}</div></div>- <PermissionPill permission={share.permission} />+ <Pill tone="brand">{displayName(share.bundle)}</Pill></ListRow>))}</DetailSection>@@ -213,7 +202,7 @@ export function CalendarDetailsSheet({{t("common.stats.created")} {date(new Date(token.createdAt))}</div></div>- <PermissionPill permission={token.permission} />+ <Pill tone="brand">{displayName(token.bundle)}</Pill></ListRow>))}</DetailSection>diff --git a/components/admin/calendar-edit-sheet.tsx b/components/admin/calendar-edit-sheet.tsxindex e4683a8..0e39d10 100644--- a/components/admin/calendar-edit-sheet.tsx+++ b/components/admin/calendar-edit-sheet.tsx@@ -3,10 +3,14 @@import { useState } from "react";import { useTranslations } from "next-intl";import { Input } from "@/components/ui/input";-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { ColorSwatches, Field, inputClass } from "@/components/form-kit";import { AdminFormPanel } from "@/components/admin/admin-form-panel";-import { useAdminCalendarActions, type AdminCalendar } from "@/hooks/useAdminCalendars";+import { BundlePicker } from "@/components/permission-bundle-picker";+import {+ useAdminCalendarActions,+ useAdminCalendarBundles,+ type AdminCalendar,+} from "@/hooks/useAdminCalendars";import { useCanEditCalendar } from "@/hooks/useAdminAccess";interface CalendarEditSheetProps {@@ -20,16 +24,21 @@ export function CalendarEditSheet({ open, onOpenChange, calendar, onSuccess }: Cconst t = useTranslations();const { updateCalendar, isUpdating } = useAdminCalendarActions();const canEdit = useCanEditCalendar();+ const { data: bundles = [], isLoading: bundlesLoading } = useAdminCalendarBundles(+ calendar.id,+ open,+ );// Resets when the parent remounts this component via its keyconst [name, setName] = useState(calendar.name);const [color, setColor] = useState(calendar.color);- const [guestPermission, setGuestPermission] = useState(calendar.guestPermission);+ const [guestBundleId, setGuestBundleId] = useState(calendar.guestBundle?.id ?? null);+ const currentGuestBundleId = calendar.guestBundle?.id ?? null;const hasChanges =name !== calendar.name ||color !== calendar.color ||- guestPermission !== calendar.guestPermission;+ guestBundleId !== currentGuestBundleId;if (!canEdit) {return null;@@ -40,7 +49,7 @@ export function CalendarEditSheet({ open, onOpenChange, calendar, onSuccess }: Cif (name !== calendar.name) updates.name = name;if (color !== calendar.color) updates.color = color;- if (guestPermission !== calendar.guestPermission) updates.guestPermission = guestPermission;+ if (guestBundleId !== currentGuestBundleId) updates.guestBundleId = guestBundleId;const success = await updateCalendar(calendar.id, updates);if (success) {@@ -76,25 +85,19 @@ export function CalendarEditSheet({ open, onOpenChange, calendar, onSuccess }: C<Fieldlabel={t("admin.calendars.guestPermission")}- htmlFor="admin-calendar-guest"hint={t("admin.calendars.guestPermissionHint")}>- <Select- value={guestPermission}- onValueChange={(value) => setGuestPermission(value as AdminCalendar["guestPermission"])}- >- <SelectTrigger- id="admin-calendar-guest"- className="h-10 w-full rounded-[9px] px-3 text-[14px] data-[size=default]:h-10"- >- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="none">{t("common.labels.permissions.none")}</SelectItem>- <SelectItem value="read">{t("common.labels.permissions.read")}</SelectItem>- <SelectItem value="write">{t("common.labels.permissions.write")}</SelectItem>- </SelectContent>- </Select>+ <BundlePicker+ bundles={bundles}+ value={guestBundleId}+ onChange={setGuestBundleId}+ guestEligibleOnly+ allowNone+ noneLabel={t("common.labels.permissions.none")}+ disabled={bundlesLoading}+ triggerAriaLabel={t("admin.calendars.guestPermission")}+ className="h-10 w-full justify-between px-3 text-[14px]"+ /></Field><Field label={t("admin.calendars.currentOwner")}>diff --git a/components/admin/calendar-table.tsx b/components/admin/calendar-table.tsxindex 65919c2..3e4e3dc 100644--- a/components/admin/calendar-table.tsx+++ b/components/admin/calendar-table.tsx@@ -20,6 +20,7 @@ import {Count,UserAvatar,} from "@/components/admin/admin-kit";+import { useBundleDisplayName } from "@/components/permission-bundle-picker";import {RowActionButton,SortHeader,@@ -82,11 +83,11 @@ export function isOrphaned(calendar: Pick<AdminCalendar, "ownerId" | "owner">) {return !calendar.ownerId || !calendar.owner;}-function GuestPermissionPill({ permission }: { permission: AdminCalendar["guestPermission"] }) {+function GuestBundlePill({ bundle }: { bundle: AdminCalendar["guestBundle"] }) {const t = useTranslations();- if (permission === "write") return <Pill tone="brand">{t("common.labels.permissions.write")}</Pill>;- if (permission === "read") return <Pill>{t("common.labels.permissions.read")}</Pill>;- return <Pill className="text-fg-tertiary">{t("common.labels.permissions.none")}</Pill>;+ const displayName = useBundleDisplayName();+ if (!bundle) return <Pill className="text-fg-tertiary">{t("common.labels.permissions.none")}</Pill>;+ return <Pill tone="brand">{displayName(bundle)}</Pill>;}function CalendarDot({ color, className }: { color: string; className?: string }) {@@ -180,7 +181,7 @@ function CalendarRow({<Count value={calendar.sharesCount} /><Count value={calendar.externalSyncsCount || 0} /><div>- <GuestPermissionPill permission={calendar.guestPermission} />+ <GuestBundlePill bundle={calendar.guestBundle} /></div><divclassName="flex items-center justify-end gap-1.5"@@ -277,7 +278,7 @@ function CalendarCard({<span className="min-w-0 flex-1 truncate text-[15px] font-semibold text-fg-strong">{calendar.name}</span>- <GuestPermissionPill permission={calendar.guestPermission} />+ <GuestBundlePill bundle={calendar.guestBundle} /><ChevronRight className="size-[17px] shrink-0 text-fg-faint" /></div><OwnerCell calendar={calendar} compact />@@ -420,7 +421,7 @@ export function CalendarTable({header("shiftsCount", t("common.labels.shifts")),header("sharesCount", t("common.labels.shares")),header("externalSyncsCount", t("admin.calendars.externalSyncsShort")),- header("guestPermission", t("adminCalendars.guestColumn")),+ header("guestBundle", t("adminCalendars.guestColumn")),<span key="actions" className="block text-right">{t("adminUsers.actions")}</span>,diff --git a/components/admin/user-details-sheet.tsx b/components/admin/user-details-sheet.tsxindex 19d8f34..4892644 100644--- a/components/admin/user-details-sheet.tsx+++ b/components/admin/user-details-sheet.tsx@@ -9,6 +9,7 @@ import { ListRow, Pill } from "@/components/form-kit";import { StatusBanner } from "@/components/status-banner";import { AdminDetailPanel } from "@/components/admin/admin-detail-panel";import { DetailSection, RolePill, StatTile, StatusPill, UserAvatar } from "@/components/admin/admin-kit";+import { useBundleDisplayName } from "@/components/permission-bundle-picker";import { fetchAdminUserDetails } from "@/hooks/useAdminUsers";import { useUserPermissions } from "@/hooks/useAdminAccess";import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";@@ -94,6 +95,7 @@ export function UserDetailsSheet({});const { canEdit, canBan, canDelete, canResetPassword } = useUserPermissions(userDetails);+ const displayName = useBundleDisplayName();const user = userDetails;const date = (value: Date, pattern = "PP") => format(value, pattern, { locale: dateLocale });@@ -223,13 +225,7 @@ export function UserDetailsSheet({<span className="min-w-0 flex-1 truncate text-[13.5px] font-semibold text-fg-strong">{share.name}</span>- <Pill>- {share.permission === "admin"- ? t("common.labels.permissions.admin")- : share.permission === "write"- ? t("common.labels.permissions.write")- : t("common.labels.permissions.read")}- </Pill>+ <Pill>{displayName(share.bundle)}</Pill></ListRow>))}</DetailSection>diff --git a/components/app-header.tsx b/components/app-header.tsxindex f29b1de..02d9de6 100644--- a/components/app-header.tsx+++ b/components/app-header.tsx@@ -28,7 +28,7 @@ interface AppHeaderProps {selectedCalendar: string | undefined;currentDate: Date;hasSyncErrors?: boolean;- /** Sync notifications manage external syncs — hidden for guests and other non-managers */+ /** Gated on the manageExternalSync capability — hidden for anyone without it */canManageSync?: boolean;onDateChange: (date: Date) => void;onSelectCalendar: (id: string) => void;diff --git a/components/calendar-discovery-sheet.tsx b/components/calendar-discovery-sheet.tsxindex c3f543a..e410008 100644--- a/components/calendar-discovery-sheet.tsx+++ b/components/calendar-discovery-sheet.tsx@@ -13,6 +13,8 @@ import {type AvailableCalendar,type DismissedCalendar,} from "@/hooks/useCalendarSubscriptions";+import { useBundleDisplayName } from "@/components/permission-bundle-picker";+import type { BundleRef } from "@/lib/permission-bundles";import { cn } from "@/lib/utils";import { shiftVars } from "@/lib/shift-display";@@ -59,21 +61,9 @@ export function CalendarDiscoverySheet({await subscribe(calendar.id, calendar.name);};- const permissionPill = (permission: string | undefined) => {- if (permission === "owner" || permission === "admin") {- return (- <Pill tone="brand">- {permission === "owner"- ? t("sharingSheet.owner")- : t("common.labels.permissions.admin")}- </Pill>- );- }- if (permission === "write") {- return <Pill tone="warning">{t("sharingSheet.permWrite")}</Pill>;- }- return <Pill>{t("sharingSheet.permRead")}</Pill>;- };+ const displayName = useBundleDisplayName();+ const bundlePill = (bundle: BundleRef | null) =>+ bundle ? <Pill>{displayName(bundle)}</Pill> : null;const renderRow = ({calendar,@@ -113,15 +103,10 @@ export function CalendarDiscoverySheet({</ListRow>);- // Shared calendars carry the share permission, public ones the guest permissionconst renderAvailable = (calendar: AvailableCalendar) =>renderRow({calendar,- pills: permissionPill(- calendar.source === "shared" && calendar.permission- ? calendar.permission- : calendar.guestPermission- ),+ pills: bundlePill(calendar.bundle),action: (<Buttonsize="sm"@@ -150,7 +135,7 @@ export function CalendarDiscoverySheet({) : (<Pill>{t("calendar.publicBadge")}</Pill>)}- {permissionPill(calendar.permission)}+ {bundlePill(calendar.bundle)}</>),action: (diff --git a/components/calendar-permissions-panel.tsx b/components/calendar-permissions-panel.tsxnew file mode 100644index 0000000..2287917--- /dev/null+++ b/components/calendar-permissions-panel.tsx@@ -0,0 +1,137 @@+"use client";++import { useState } from "react";+import { useTranslations } from "next-intl";+import { Info, Lock } from "lucide-react";+import { Button } from "@/components/ui/button";+import { PanelBody, PanelFooter } from "@/components/panel-dialog";+import { SegmentedControl } from "@/components/segmented-control";+import { InfoNote, SectionLabel, ToggleRow } from "@/components/form-kit";+import { PermissionBundleEditor } from "@/components/permission-bundle-editor";+import { PermissionAssignments } from "@/components/permission-bundle-assignments";+import { AccessLinkCreated } from "@/components/calendar-token-form";+import { useBundleDisplayName } from "@/components/permission-bundle-picker";+import { useCalendars } from "@/hooks/useCalendars";+import { useCalendarPermission } from "@/hooks/useCalendarPermission";+import { usePermissionLinkForm } from "@/hooks/usePermissionLinkForm";+import { useAuthFeatures } from "@/hooks/useAuthFeatures";+import { useReportDirty } from "@/hooks/useDirtyState";++type PermissionsTab = "groups" | "assignments" | "signups";++interface PermissionsPanelProps {+ calendarId: string;+ onClose: () => void;+ onDirtyChange?: (dirty: boolean) => void;+}++/** Central "Berechtigungen" surface (Stufe 2, 7.3): groups, assignments and signups. */+export function PermissionsPanel({ calendarId, onClose, onDirtyChange }: PermissionsPanelProps) {+ const t = useTranslations();+ const { calendars, updateCalendar } = useCalendars();+ const { allowGuest } = useAuthFeatures();+ const { can } = useCalendarPermission(calendarId);+ const canManageSettings = can("manageCalendarSettings");+ const displayName = useBundleDisplayName();+ const [tab, setTab] = useState<PermissionsTab>("groups");+ const linkForm = usePermissionLinkForm(calendarId);++ useReportDirty(linkForm.dirty, onDirtyChange);++ const [optimisticSignupsEnabled, setOptimisticSignupsEnabled] = useState<boolean | null>(null);+ const [saving, setSaving] = useState(false);+ const calendar = calendars.find((c) => c.id === calendarId);+ const signupsEnabled = optimisticSignupsEnabled ?? calendar?.signupsEnabled ?? true;++ const handleSignupsEnabledChange = async (value: boolean) => {+ if (value === signupsEnabled) return;+ setOptimisticSignupsEnabled(value);+ setSaving(true);+ try {+ await updateCalendar(calendarId, { signupsEnabled: value });+ } catch {+ // updateCalendar already reported the error and rolled back the cache.+ } finally {+ setSaving(false);+ setOptimisticSignupsEnabled(null);+ }+ };++ // A freshly created link takes over the whole panel body, same as the old+ // sharing sheet did — "Close" here resets the form, not the whole panel.+ if (linkForm.created) {+ const createdBundle = linkForm.guestEligibleBundles.find(+ (b) => b.id === linkForm.created!.bundleId+ );+ return (+ <>+ <PanelBody>+ <AccessLinkCreated+ created={linkForm.created}+ bundleName={displayName(createdBundle) ?? ""}+ />+ </PanelBody>+ <PanelFooter>+ <Button variant="outline" className="h-10 flex-1 font-semibold" onClick={linkForm.reset}>+ {t("common.close")}+ </Button>+ </PanelFooter>+ </>+ );+ }++ const tabs: { value: PermissionsTab; label: string }[] = [+ { value: "groups", label: t("permissionBundles.tabGroups") },+ { value: "assignments", label: t("permissionBundles.tabAssignments") },+ { value: "signups", label: t("permissionBundles.tabMore") },+ ];++ return (+ <>+ <PanelBody className="flex flex-col gap-3.5">+ <SegmentedControl<PermissionsTab>+ label={t("permissionBundles.title")}+ size="lg"+ value={tab}+ onChange={setTab}+ options={tabs}+ />++ {tab === "groups" && <PermissionBundleEditor calendarId={calendarId} />}++ {tab === "assignments" && (+ <PermissionAssignments+ calendarId={calendarId}+ allowGuest={allowGuest}+ linkForm={linkForm}+ calendar={calendar}+ updateCalendar={updateCalendar}+ />+ )}++ {tab === "signups" && (+ <>+ <SectionLabel className="mb-0">{t("permissionBundles.groups.signups")}</SectionLabel>+ <ToggleRow+ id="signups-enabled"+ title={t("sharingSheet.signupsEnabledLabel")}+ description={t("sharingSheet.signupsEnabledDesc")}+ checked={signupsEnabled}+ onCheckedChange={handleSignupsEnabledChange}+ disabled={saving || !canManageSettings}+ />+ {!canManageSettings && (+ <InfoNote icon={Lock}>{t("permissionBundles.signupsLocked")}</InfoNote>+ )}+ <InfoNote icon={Info}>{t("permissionBundles.signupsCapabilityHint")}</InfoNote>+ </>+ )}+ </PanelBody>+ <PanelFooter>+ <Button variant="outline" className="h-10 flex-1 font-semibold" onClick={onClose}>+ {t("common.close")}+ </Button>+ </PanelFooter>+ </>+ );+}diff --git a/components/calendar-share-list.tsx b/components/calendar-share-list.tsxdeleted file mode 100644index c6f3123..0000000--- a/components/calendar-share-list.tsx+++ /dev/null@@ -1,220 +0,0 @@-"use client";--import { ReactNode, useState } from "react";-import { useTranslations } from "next-intl";-import { Check, ChevronDown, Trash2 } from "lucide-react";-import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";-import { ListRow, SectionLabel } from "@/components/form-kit";-import {- CalendarShareUserSearch,-} from "@/components/calendar-share-user-search";-import { useCalendarShares, type CalendarShare } from "@/hooks/useCalendarShares";-import { useAuth } from "@/hooks/useAuth";-import { useCalendarPermission } from "@/hooks/useCalendarPermission";-import { cn, getUserInitials } from "@/lib/utils";--type SharePermission = "admin" | "write" | "read";--interface CalendarShareListProps {- calendarId: string;- canManageShares: boolean;-}--/** Avatar + name/email row shared by the calendar-share list and the shift-signup list. */-export function PersonRow({- user,- highlight,- suffix,- action,- fallback = "…",- showEmail = true,-}: {- user: { name: string | null; email?: string; image?: string | null };- highlight?: boolean;- suffix?: ReactNode;- action?: ReactNode;- /** Shown when the user has neither a name nor an email. */- fallback?: ReactNode;- /** Second line with the user's email below their name. */- showEmail?: boolean;-}) {- return (- <ListRow>- <Avatar className="size-8">- {user.image && <AvatarImage src={user.image} alt="" />}- <AvatarFallback- className={cn(- "text-[11.5px] font-semibold",- highlight ? "bg-brand-soft text-brand-ink" : "bg-surface-sunken text-fg-secondary"- )}- >- {getUserInitials(user)}- </AvatarFallback>- </Avatar>- <div className="min-w-0 flex-1">- <div className="truncate text-[14px] font-semibold text-fg-strong">- {user.name || user.email || fallback}- {suffix}- </div>- {showEmail && user.name && user.email && (- <div className="truncate text-[12px] text-fg-tertiary">{user.email}</div>- )}- </div>- {action}- </ListRow>- );-}--/** "Personen" tab: invite row plus everyone with access. */-export function CalendarShareList({ calendarId, canManageShares }: CalendarShareListProps) {- const t = useTranslations();- const { user: currentUser } = useAuth();- const { isOwner } = useCalendarPermission(calendarId);- const { shares, updateShare, removeShare } = useCalendarShares(calendarId);- const [shareToDelete, setShareToDelete] = useState<CalendarShare | null>(null);-- const permissionLabel = (permission: CalendarShare["permission"]) =>- permission === "owner"- ? t("sharingSheet.owner")- : permission === "admin"- ? t("common.labels.permissions.admin")- : permission === "write"- ? t("sharingSheet.permWrite")- : t("sharingSheet.permRead");-- const permissionOptions: { value: SharePermission; title: string; description: string }[] = [- { value: "read", title: t("sharingSheet.permRead"), description: t("sharingSheet.permReadDesc") },- { value: "write", title: t("sharingSheet.permWrite"), description: t("sharingSheet.permWriteDesc") },- ...(isOwner- ? [- {- value: "admin" as const,- title: t("common.labels.permissions.admin"),- description: t("sharingSheet.permAdminDesc"),- },- ]- : []),- ];-- const you = <span className="ml-1.5 font-normal text-fg-tertiary">({t("share.you")})</span>;- const staticLabel = (label: string) => (- <span className="shrink-0 px-[9px] text-[12.5px] font-medium text-fg-secondary">{label}</span>- );-- const renderAction = (share: CalendarShare) => {- const isSelf = share.userId === currentUser?.id;- // Only the owner may touch admins; nobody changes their own level.- const canRemove = canManageShares && (isOwner || share.permission !== "admin");- const canChange = canRemove && !isSelf;- if (!canRemove) return staticLabel(permissionLabel(share.permission));-- return (- <DropdownMenu>- <DropdownMenuTrigger- aria-label={t("sharingSheet.changePermission", {- name: share.user.name || share.user.email,- })}- className="flex h-[30px] shrink-0 items-center gap-1.5 rounded-lg border border-line px-[9px] text-[12.5px] font-medium text-fg-body transition-colors hover:bg-surface-panel data-[state=open]:bg-surface-panel"- >- {permissionLabel(share.permission)}- <ChevronDown className="size-[13px] text-fg-tertiary" />- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-64">- {canChange && (- <>- {permissionOptions.map((option) => (- <DropdownMenuItem- key={option.value}- onClick={() => {- if (option.value !== share.permission) updateShare(share.id, option.value);- }}- className="items-start gap-2.5 py-2"- >- <Check- className={cn(- "mt-0.5 size-4 shrink-0 text-brand",- option.value !== share.permission && "invisible"- )}- />- <span className="min-w-0">- <span className="block text-[13px] font-semibold text-fg-strong">- {option.title}- </span>- <span className="block text-[12px] text-fg-tertiary">{option.description}</span>- </span>- </DropdownMenuItem>- ))}- <DropdownMenuSeparator />- </>- )}- <DropdownMenuItem- onClick={() => setShareToDelete(share)}- className="gap-2.5 text-danger focus:text-danger"- >- <Trash2 className="size-4 text-danger" />- {t("share.removeAccess")}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- );- };-- // The shares endpoint lists grants only; the owner row is known just for the owner themself.- const ownerRow = isOwner && currentUser && (- <PersonRow- user={{ name: currentUser.name ?? null, email: currentUser.email, image: currentUser.image }}- highlight- suffix={you}- action={staticLabel(t("sharingSheet.owner"))}- />- );-- return (- <>- {canManageShares && <CalendarShareUserSearch calendarId={calendarId} />}-- <section className="flex flex-col gap-2">- <SectionLabel className="mb-0">{t("sharingSheet.haveAccess")}</SectionLabel>- {ownerRow}- {shares.map((share) => (- <PersonRow- key={share.id}- user={share.user}- suffix={share.userId === currentUser?.id ? you : undefined}- action={renderAction(share)}- />- ))}- {shares.length === 0 && (- <p className="rounded-[11px] border border-dashed border-control px-3.5 py-3 text-center text-[13px] text-fg-tertiary">- {t("share.noSharesDescription")}- </p>- )}- </section>-- {shareToDelete && (- <ConfirmationDialog- open- onOpenChange={(open) => !open && setShareToDelete(null)}- onConfirm={async () => {- await removeShare(shareToDelete.id);- setShareToDelete(null);- }}- title={t("share.removeShareConfirmTitle")}- description={t("share.removeShareConfirmDesc", {- user: shareToDelete.user.name || shareToDelete.user.email,- })}- confirmVariant="destructive"- confirmText={t("share.removeAccess")}- />- )}- </>- );-}diff --git a/components/calendar-share-management-sheet.tsx b/components/calendar-share-management-sheet.tsxdeleted file mode 100644index 873c068..0000000--- a/components/calendar-share-management-sheet.tsx+++ /dev/null@@ -1,179 +0,0 @@-"use client";--import { useState } from "react";-import { useTranslations } from "next-intl";-import { Button } from "@/components/ui/button";-import { PanelBody, PanelFooter } from "@/components/panel-dialog";-import { SegmentedControl } from "@/components/segmented-control";-import { CalendarShareList } from "@/components/calendar-share-list";-import { AccessLinksPanel } from "@/components/calendar-token-list";-import { ToggleRow } from "@/components/form-kit";-import { GuestPermissionSelector } from "@/components/guest-permission-selector";-import { useCalendars } from "@/hooks/useCalendars";-import { useCalendarPermission } from "@/hooks/useCalendarPermission";-import { useAuthFeatures } from "@/hooks/useAuthFeatures";-import { useAccessLinkForm } from "@/hooks/useAccessLinkForm";-import { useReportDirty } from "@/hooks/useDirtyState";--type GuestPermission = "none" | "read" | "write";-type SharingTab = "people" | "public" | "links";--interface SharingPanelProps {- calendarId: string;- onClose: () => void;- onDirtyChange?: (dirty: boolean) => void;-}--/** Sharing (screen 4d): people with access, public access and access links. */-export function SharingPanel({ calendarId, onClose, onDirtyChange }: SharingPanelProps) {- const t = useTranslations();- const { calendars, updateCalendar } = useCalendars();- const { canShare } = useCalendarPermission(calendarId);- const { allowGuest } = useAuthFeatures();- const [tab, setTab] = useState<SharingTab>("people");- const linkForm = useAccessLinkForm(calendarId);-- useReportDirty(linkForm.dirty, onDirtyChange);-- const [optimisticGuest, setOptimisticGuest] = useState<GuestPermission | null>(null);- const [optimisticAllowSelfSignup, setOptimisticAllowSelfSignup] = useState<- boolean | null- >(null);- const [optimisticSignupsEnabled, setOptimisticSignupsEnabled] = useState<- boolean | null- >(null);- const [saving, setSaving] = useState(false);- const calendar = calendars.find((c) => c.id === calendarId);- const guestPermission = optimisticGuest ?? calendar?.guestPermission ?? "none";- const allowSelfSignup =- optimisticAllowSelfSignup ?? calendar?.allowSelfSignup ?? true;- const signupsEnabled =- optimisticSignupsEnabled ?? calendar?.signupsEnabled ?? true;-- const handleGuestPermissionChange = async (value: GuestPermission) => {- if (!canShare || value === guestPermission) return;- setOptimisticGuest(value);- setSaving(true);- try {- await updateCalendar(calendarId, { guestPermission: value });- } catch {- // updateCalendar already reported the error and rolled back the cache.- } finally {- setSaving(false);- setOptimisticGuest(null);- }- };-- const handleAllowSelfSignupChange = async (value: boolean) => {- if (!canShare || value === allowSelfSignup) return;- setOptimisticAllowSelfSignup(value);- setSaving(true);- try {- await updateCalendar(calendarId, { allowSelfSignup: value });- } catch {- // updateCalendar already reported the error and rolled back the cache.- } finally {- setSaving(false);- setOptimisticAllowSelfSignup(null);- }- };-- const handleSignupsEnabledChange = async (value: boolean) => {- if (!canShare || value === signupsEnabled) return;- setOptimisticSignupsEnabled(value);- setSaving(true);- try {- await updateCalendar(calendarId, { signupsEnabled: value });- } catch {- // updateCalendar already reported the error and rolled back the cache.- } finally {- setSaving(false);- setOptimisticSignupsEnabled(null);- }- };-- const tabs: { value: SharingTab; label: string }[] = [- { value: "people", label: t("sharingSheet.tabPeople") },- { value: "public", label: t("share.public") },- // Access links are a pure guest-access mechanism, so they disappear once- // ALLOW_GUEST_ACCESS is off — unlike public access, which remains useful- // for signed-in users' calendar discovery regardless of that flag.- ...(allowGuest ? [{ value: "links" as const, label: t("share.links") }] : []),- ];- const activeTab = tabs.some((option) => option.value === tab) ? tab : "people";-- const switcher = (- <SegmentedControl<SharingTab>- label={t("common.labels.shares")}- size="lg"- value={activeTab}- onChange={setTab}- options={tabs}- />- );-- if (activeTab === "links") {- return (- <AccessLinksPanel- calendarId={calendarId}- form={linkForm}- onClose={onClose}- leading={switcher}- />- );- }-- return (- <>- <PanelBody className="flex flex-col gap-3.5">- {switcher}-- {activeTab === "people" ? (- <>- <CalendarShareList calendarId={calendarId} canManageShares={canShare} />- {canShare && (- <ToggleRow- id="signups-enabled"- title={t("sharingSheet.signupsEnabledLabel")}- description={t("sharingSheet.signupsEnabledDesc")}- checked={signupsEnabled}- onCheckedChange={handleSignupsEnabledChange}- disabled={saving}- />- )}- {canShare && signupsEnabled && (- <ToggleRow- id="allow-self-signup"- title={t("sharingSheet.allowSelfSignupLabel")}- description={t("sharingSheet.allowSelfSignupDesc")}- checked={allowSelfSignup}- onCheckedChange={handleAllowSelfSignupChange}- disabled={saving}- />- )}- </>- ) : (- <>- <p className="text-[13px] text-fg-secondary">- {allowGuest- ? t("share.publicAccessDescriptionGuestsOn")- : t("share.publicAccessDescriptionGuestsOff")}- </p>- <GuestPermissionSelector- value={guestPermission}- onChange={handleGuestPermissionChange}- allowGuest={allowGuest}- disabled={!canShare}- />- {saving && <p className="text-[12px] text-fg-tertiary">{t("common.saving")}</p>}- </>- )}- </PanelBody>- <PanelFooter>- <Button variant="outline" className="h-10 flex-1 font-semibold" onClick={onClose}>- {t("common.close")}- </Button>- </PanelFooter>- </>- );-}diff --git a/components/calendar-share-user-search.tsx b/components/calendar-share-user-search.tsxindex 6b9c61c..d16bcc9 100644--- a/components/calendar-share-user-search.tsx+++ b/components/calendar-share-user-search.tsx@@ -10,11 +10,17 @@ import { getUserInitials } from "@/lib/utils";interface CalendarShareUserSearchProps {calendarId: string;+ /** Bundle the invited user is granted; the caller renders the picker that sets this. */+ bundleId: string;onSuccess?: () => void;}-/** Invite row of the sharing panel: search a user and share with read access. */-export function CalendarShareUserSearch({ calendarId, onSuccess }: CalendarShareUserSearchProps) {+/** Invite row of the permissions panel: search a user and share with the selected bundle. */+export function CalendarShareUserSearch({+ calendarId,+ bundleId,+ onSuccess,+}: CalendarShareUserSearchProps) {const t = useTranslations();const { searchUsers, searchResults, searchLoading, addShare } = useCalendarShares(calendarId);@@ -54,9 +60,9 @@ export function CalendarShareUserSearch({ calendarId, onSuccess }: CalendarShare};const handleInvite = async () => {- if (!selectedUser) return;+ if (!selectedUser || !bundleId) return;setInviting(true);- const result = await addShare(selectedUser.id, "read");+ const result = await addShare(selectedUser.id, bundleId);setInviting(false);if (result.success) {clear();@@ -100,7 +106,7 @@ export function CalendarShareUserSearch({ calendarId, onSuccess }: CalendarSharetype="button"size="sm"onClick={handleInvite}- disabled={!selectedUser || inviting}+ disabled={!selectedUser || !bundleId || inviting}className="h-7 shrink-0 rounded-[7px] px-3 text-[12.5px] font-semibold">{t("sharingSheet.invite")}diff --git a/components/calendar-switcher.tsx b/components/calendar-switcher.tsxindex 651e2e0..f60c65b 100644--- a/components/calendar-switcher.tsx+++ b/components/calendar-switcher.tsx@@ -25,6 +25,7 @@ import {import { CalendarWithCount } from "@/lib/types";import { useAuth } from "@/hooks/useAuth";import { useAuthFeatures } from "@/hooks/useAuthFeatures";+import { hasEditCapability } from "@/lib/permission-bundles";import { cn } from "@/lib/utils";interface CalendarSwitcherProps {@@ -43,9 +44,7 @@ export function isCalendarReadOnly(userId: string | undefined): boolean {if (userId && calendar.ownerId === userId) return false;- if (calendar.sharePermission) return calendar.sharePermission === "read";- if (calendar.tokenPermission) return calendar.tokenPermission === "read";- return calendar.guestPermission === "read";+ return !hasEditCapability(calendar.capabilities ?? []);}export function CalendarSwitcher({@@ -61,13 +60,7 @@ export function CalendarSwitcher({const { isAuthEnabled } = useAuthFeatures();const visible = isGuest- ? calendars.filter(- (c) =>- c.guestPermission === "read" ||- c.guestPermission === "write" ||- c.tokenPermission === "read" ||- c.tokenPermission === "write"- )+ ? calendars.filter((c) => (c.capabilities?.length ?? 0) > 0): calendars;const selected = visible.find((c) => c.id === selectedId);const signedIn = isAuthEnabled && !!user && !isGuest;@@ -84,14 +77,16 @@ export function CalendarSwitcher({key: "shared",label: t("calendar.sharedCalendars"),icon: Users,- items: visible.filter((c) => c.ownerId !== user!.id && c.sharePermission),+ items: visible.filter(+ (c) => c.ownerId !== user!.id && c.subscriptionSource === "shared"+ ),},{key: "token",label: t("calendar.tokenCalendars"),icon: Link2,items: visible.filter(- (c) => c.tokenPermission && !c.sharePermission && c.ownerId !== user!.id+ (c) => c.ownerId !== user!.id && c.subscriptionSource === "token"),},{@@ -99,11 +94,7 @@ export function CalendarSwitcher({label: t("calendar.publicCalendars"),icon: Globe,items: visible.filter(- (c) =>- c.guestPermission &&- !c.sharePermission &&- !c.tokenPermission &&- c.ownerId !== user!.id+ (c) => c.ownerId !== user!.id && c.subscriptionSource === "guest"),},].filter((g) => g.items.length > 0)@@ -111,7 +102,10 @@ export function CalendarSwitcher({const statusIcon = (calendar: CalendarWithCount) => {if (!isAuthEnabled) return null;- if (calendar.sharePermission === "admin" || calendar.sharePermission === "owner") {+ if (+ calendar.ownerId !== user?.id &&+ calendar.capabilities?.includes("manageShares")+ ) {return <ShieldCheck className="h-3.5 w-3.5 text-brand-ink" />;}if (isCalendarReadOnly(calendar, user?.id)) {diff --git a/components/calendar-token-create-dialog.tsx b/components/calendar-token-form.tsxsimilarity index 80%rename from components/calendar-token-create-dialog.tsxrename to components/calendar-token-form.tsxindex 332e291..11e34b3 100644--- a/components/calendar-token-create-dialog.tsx+++ b/components/calendar-token-form.tsx@@ -9,17 +9,17 @@ import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Field, InfoNote, OptionCards, inputClass } from "@/components/form-kit";import { StatusBanner } from "@/components/status-banner";+import { BundlePicker } from "@/components/permission-bundle-picker";import type {CreatedAccessLink,- LinkPermission,LinkValidity,- useAccessLinkForm,-} from "@/hooks/useAccessLinkForm";+ usePermissionLinkForm,+} from "@/hooks/usePermissionLinkForm";import { useAuthFeatures } from "@/hooks/useAuthFeatures";import { getDateLocale } from "@/lib/locales";import { cn } from "@/lib/utils";-type AccessLinkForm = ReturnType<typeof useAccessLinkForm>;+type AccessLinkForm = ReturnType<typeof usePermissionLinkForm>;function useValidityLabel() {const t = useTranslations();@@ -33,12 +33,6 @@ function useValidityLabel() {: t("sharingSheet.validityUnlimited");}-function usePermissionLabel() {- const t = useTranslations();- return (permission: LinkPermission) =>- permission === "read" ? t("sharingSheet.permRead") : t("sharingSheet.permWrite");-}-/** Fields of the "Neuen Link erzeugen" block; submit lives in the owning panel's footer. */export function AccessLinkCreateForm({ form }: { form: AccessLinkForm }) {const t = useTranslations();@@ -73,22 +67,12 @@ export function AccessLinkCreateForm({ form }: { form: AccessLinkForm }) {</Field><Field label={t("common.labels.permission")}>- <OptionCards<LinkPermission>- label={t("common.labels.permission")}- value={form.permission}- onChange={form.setPermission}- options={[- {- value: "read",- title: t("sharingSheet.permRead"),- description: t("sharingSheet.permReadDesc"),- },- {- value: "write",- title: t("sharingSheet.permWrite"),- description: t("sharingSheet.permWriteDesc"),- },- ]}+ <BundlePicker+ bundles={form.guestEligibleBundles}+ value={form.bundleId || null}+ onChange={(id) => id && form.setBundleId(id)}+ triggerAriaLabel={t("common.labels.permission")}+ className="h-10 w-full justify-between px-3"/></Field>@@ -116,10 +100,15 @@ export function AccessLinkCreateForm({ form }: { form: AccessLinkForm }) {}/** Header block of the result view (9b), shown inside the panel body. */-export function AccessLinkCreatedHeader({ created }: { created: CreatedAccessLink }) {+export function AccessLinkCreatedHeader({+ created,+ bundleName,+}: {+ created: CreatedAccessLink;+ bundleName: string;+}) {const t = useTranslations();const validityLabel = useValidityLabel();- const permissionLabel = usePermissionLabel();return (<div className="flex items-start gap-3">@@ -131,11 +120,9 @@ export function AccessLinkCreatedHeader({ created }: { created: CreatedAccessLin{t("sharingSheet.linkReady")}</h3><p className="mt-1 truncate text-[13px] text-fg-secondary">- {[- created.name || t("token.unnamed"),- permissionLabel(created.permission),- validityLabel(created.validity),- ].join(" · ")}+ {[created.name || t("token.unnamed"), bundleName, validityLabel(created.validity)].join(+ " · "+ )}</p></div></div>@@ -143,7 +130,13 @@ export function AccessLinkCreatedHeader({ created }: { created: CreatedAccessLin}/** The one-time view of a freshly created token. */-export function AccessLinkCreated({ created }: { created: CreatedAccessLink }) {+export function AccessLinkCreated({+ created,+ bundleName,+}: {+ created: CreatedAccessLink;+ bundleName: string;+}) {const t = useTranslations();const { allowGuest } = useAuthFeatures();const linkInput = useRef<HTMLInputElement>(null);@@ -163,7 +156,7 @@ export function AccessLinkCreated({ created }: { created: CreatedAccessLink }) {return (<div className="flex flex-col gap-3.5">- <AccessLinkCreatedHeader created={created} />+ <AccessLinkCreatedHeader created={created} bundleName={bundleName} /><StatusBanner tone="warning" icon={TriangleAlert} title={t("sharingSheet.copyNowTitle")}>{t("sharingSheet.copyNowBody")}diff --git a/components/calendar-token-list.tsx b/components/calendar-token-list.tsxindex 7b8a673..6db897c 100644--- a/components/calendar-token-list.tsx+++ b/components/calendar-token-list.tsx@@ -1,19 +1,13 @@"use client";-import { ReactNode, useState } from "react";+import { useState } from "react";import { useLocale, useTranslations } from "next-intl";import { format, formatDistanceToNow } from "date-fns";import { Eye, EyeOff, Link as LinkIcon, Trash2 } from "lucide-react";-import { Button } from "@/components/ui/button";import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";import { ListRow, Pill, RowIconButton, SectionLabel } from "@/components/form-kit";-import { PanelBody, PanelFooter } from "@/components/panel-dialog";-import {- AccessLinkCreateForm,- AccessLinkCreated,-} from "@/components/calendar-token-create-dialog";+import { useBundleDisplayName } from "@/components/permission-bundle-picker";import { useCalendarTokens, type CalendarAccessToken } from "@/hooks/useCalendarTokens";-import type { useAccessLinkForm } from "@/hooks/useAccessLinkForm";import { getDateLocale } from "@/lib/locales";import { cn } from "@/lib/utils";@@ -35,6 +29,7 @@ function TokenRow({onRevoke: () => void;}) {const t = useTranslations();+ const displayName = useBundleDisplayName();const dateLocale = getDateLocale(useLocale());const expired = isExpired(token);const dimmed = expired || !token.isActive;@@ -85,11 +80,7 @@ function TokenRow({</div><div className="truncate text-[12px] text-fg-tertiary">{usage}</div></div>- {token.permission === "write" ? (- <Pill tone="warning">{t("sharingSheet.permWrite")}</Pill>- ) : (- <Pill>{t("sharingSheet.permRead")}</Pill>- )}+ <Pill>{displayName(token.bundle) ?? t("common.labels.permissions.none")}</Pill><RowIconButtonicon={token.isActive ? EyeOff : Eye}label={token.isActive ? t("token.disable") : t("token.enable")}@@ -157,55 +148,3 @@ export function CalendarTokenList({ calendarId }: { calendarId: string }) {</>);}--/**- * Access links (screens 9a/9b). The owner holds `form` so its input survives tab- * switches; `leading` renders above the list, e.g. a tab switcher.- */-export function AccessLinksPanel({- calendarId,- form,- onClose,- leading,-}: {- calendarId: string;- form: ReturnType<typeof useAccessLinkForm>;- onClose: () => void;- leading?: ReactNode;-}) {- const t = useTranslations();-- if (form.created) {- return (- <>- <PanelBody>- <AccessLinkCreated created={form.created} />- </PanelBody>- <PanelFooter>- <Button variant="outline" className="h-10 flex-1 font-semibold" onClick={form.reset}>- {t("common.close")}- </Button>- </PanelFooter>- </>- );- }-- return (- <>- <PanelBody className="flex flex-col gap-3.5">- {leading}- <CalendarTokenList calendarId={calendarId} />- <div className="h-px shrink-0 bg-line" />- <AccessLinkCreateForm form={form} />- </PanelBody>- <PanelFooter>- <Button variant="outline" className="h-10 flex-1 font-semibold" onClick={onClose}>- {t("common.cancel")}- </Button>- <Button className="h-10 flex-1 font-semibold" onClick={form.create} disabled={form.creating}>- {form.creating ? t("sharingSheet.creating") : t("sharingSheet.createLink")}- </Button>- </PanelFooter>- </>- );-}diff --git a/components/calendar-workspace.tsx b/components/calendar-workspace.tsxindex 18a2b74..49d50e7 100644--- a/components/calendar-workspace.tsx+++ b/components/calendar-workspace.tsx@@ -42,7 +42,14 @@ interface CalendarWorkspaceProps {showShiftNotes: boolean;highlightedWeekdays: number[];highlightColor: string;- canEdit: boolean;+ /** createShift — gates stamping and the "add a new shift" affordances */+ canCreateShift: boolean;+ /** manageOwnNotesEvents — creating a note/event only ever needs "own" */+ canAddNote: boolean;+ /** Per-shift own/any precision (editOwnShift/editAnyShift) for the edit affordance */+ canEditShift: (shift: ShiftWithCalendar) => boolean;+ /** Per-shift own/any precision (deleteOwnShift/deleteAnyShift) for the delete affordance */+ canDeleteShift: (shift: ShiftWithCalendar) => boolean;showStampBar: boolean;selectedPresetIds: string[];onSelectPreset: (id: string | undefined, multiSelect?: boolean) => void;@@ -70,7 +77,10 @@ export function CalendarWorkspace({showShiftNotes,highlightedWeekdays,highlightColor,- canEdit,+ canCreateShift,+ canAddNote,+ canEditShift,+ canDeleteShift,showStampBar,selectedPresetIds,onSelectPreset,@@ -103,7 +113,7 @@ export function CalendarWorkspace({shifts,});- const stampingEnabled = canEdit && isOnline && showStampBar;+ const stampingEnabled = canCreateShift && isOnline && showStampBar;const stampPresetIds = useMemo(() => orderStampPresets(presets).map((p) => p.id),[presets]@@ -120,7 +130,10 @@ export function CalendarWorkspace({currentDate,...dayData,summary: monthSummary,- canEdit: canEdit && isOnline,+ canAddShift: canCreateShift && isOnline,+ canAddNote: canAddNote && isOnline,+ canEditShift: (shift) => canEditShift(shift) && isOnline,+ canDeleteShift: (shift) => canDeleteShift(shift) && isOnline,};const banners = (@@ -135,7 +148,7 @@ export function CalendarWorkspace({</StatusBanner>)}{isGuest && <GuestBanner variant={desktop ? "default" : "compact"} />}- {!canEdit && !isGuest && calendarId && (+ {!canCreateShift && !isGuest && calendarId && (<ReadOnlyBannertitle={t("calendarView.readOnlyTitle")}message={t("calendarView.readOnlyMessage")}@@ -143,7 +156,7 @@ export function CalendarWorkspace({)}</>);- const hasBanner = !isOnline || isGuest || (!canEdit && !!calendarId);+ const hasBanner = !isOnline || isGuest || (!canCreateShift && !!calendarId);const grid = (<MonthGrid@@ -160,7 +173,7 @@ export function CalendarWorkspace({highlightedWeekdays={highlightedWeekdays}highlightColor={highlightColor}onDayClick={onDayClick}- onDayContextMenu={canEdit ? onDayContextMenu : undefined}+ onDayContextMenu={canAddNote ? onDayContextMenu : undefined}/>);@@ -230,7 +243,7 @@ export function CalendarWorkspace({setPeriod("month");setStatsOpen(true);}}- onAddShift={model.canEdit ? actions.onAddShift : undefined}+ onAddShift={model.canAddShift ? actions.onAddShift : undefined}/></div><MobileDaySheetdiff --git a/components/compare-workspace.tsx b/components/compare-workspace.tsxindex 2b943d6..c5b660e 100644--- a/components/compare-workspace.tsx+++ b/components/compare-workspace.tsx@@ -111,10 +111,11 @@ export function CompareWorkspace(props: CompareWorkspaceProps) {props.calendars.find((c) => presetOwnerIds.has(c.id))?.id ?? props.calendars[0]?.id;const activePresets = orderStampPresets(props.presetsMap.get(activeColumnId ?? "") ?? []);- // Each column carries its own permission, and only an editable one renders the- // presets the shortcuts arm — without this a key press stamps into a read-only- // calendar and the write is rejected server-side.- const { canEdit: canEditActiveColumn } = useCalendarPermission(activeColumnId);+ // Each column carries its own permission, and only a stampable one renders the+ // presets the shortcuts arm — without this a key press stamps into a calendar+ // the caller can't create shifts in and the write is rejected server-side.+ const { can: canStampActiveColumn } = useCalendarPermission(activeColumnId);+ const canEditActiveColumn = canStampActiveColumn("createShift");const { isOnline } = useConnectionStatus({ toasts: false });useStampShortcuts({@@ -321,7 +322,11 @@ function CompareColumn({}) {const t = useTranslations();const locale = useLocale();- const { canEdit } = useCalendarPermission(calendar.id);+ const { can } = useCalendarPermission(calendar.id);+ const canStamp = can("createShift");+ // The gear only needs to be worth opening — PresetManageSheet gates its own actions internally.+ const canOpenPresetManage = can("createPreset") || can("manageOwnPresets");+ const canAddNote = can("manageOwnNotesEvents");const { primary, secondary } = splitStampPresets(presetsMap.get(calendar.id) ?? []);const activeIds = new Set(selectedPresetIds);const totals = monthTotals(shifts, currentDate);@@ -343,10 +348,10 @@ function CompareColumn({{formatHours(totals.minutes, locale)}</span></div>- {canEdit && (+ {(canStamp || canOpenPresetManage) && (<div className="mt-2.5 flex h-8 items-center gap-1.5 overflow-hidden"><div className="flex min-w-0 items-center gap-1.5 overflow-hidden empty:hidden">- {primary.map((preset, index) => {+ {canStamp && primary.map((preset, index) => {const active = activeIds.has(preset.id);return (<button@@ -374,27 +379,33 @@ function CompareColumn({);})}</div>- <MorePresets- variant="compare"- presets={secondary}- selectedPresetIds={selectedPresetIds}- onSelectPreset={onSelectPreset}- multiMode={multiMode}- />- <MultiSelectToggle- variant="compare"- active={multiMode}- onClick={() => setMultiMode((m) => !m)}- />- <button- type="button"- onClick={onManagePresets}- aria-label={t("calendarView.managePresets")}- className="flex size-7 shrink-0 items-center justify-center rounded-[7px] text-fg-tertiary hover:bg-surface-sunken"- >- <SlidersHorizontal className="size-3.5" />- </button>- {!keysActive && primary.length + secondary.length > 0 && (+ {canStamp && (+ <MorePresets+ variant="compare"+ presets={secondary}+ selectedPresetIds={selectedPresetIds}+ onSelectPreset={onSelectPreset}+ multiMode={multiMode}+ />+ )}+ {canStamp && (+ <MultiSelectToggle+ variant="compare"+ active={multiMode}+ onClick={() => setMultiMode((m) => !m)}+ />+ )}+ {canOpenPresetManage && (+ <button+ type="button"+ onClick={onManagePresets}+ aria-label={t("calendarView.managePresets")}+ className="flex size-7 shrink-0 items-center justify-center rounded-[7px] text-fg-tertiary hover:bg-surface-sunken"+ >+ <SlidersHorizontal className="size-3.5" />+ </button>+ )}+ {canStamp && !keysActive && primary.length + secondary.length > 0 && (<span className="min-w-0 flex-1 truncate pl-1 text-[12px] text-fg-tertiary">{t("calendarCompare.tapToMoveStamp")}</span>@@ -416,7 +427,7 @@ function CompareColumn({highlightedWeekdays={highlightedWeekdays}highlightColor={highlightColor}onDayClick={(date) => onDayClick(calendar.id, date)}- onDayContextMenu={canEdit ? (date) => onDayContextMenu(calendar.id, date) : undefined}+ onDayContextMenu={canAddNote ? (date) => onDayContextMenu(calendar.id, date) : undefined}/></section>);diff --git a/components/day-detail.tsx b/components/day-detail.tsxindex 4cd889b..173c5ac 100644--- a/components/day-detail.tsx+++ b/components/day-detail.tsx@@ -107,6 +107,7 @@ export function Kpi({interface ShiftDetailRowProps {shift: ShiftWithCalendar;canEdit: boolean;+ canDelete: boolean;actions: "menu" | "inline";onEdit: (shift: ShiftWithCalendar) => void;onDelete: (shift: ShiftWithCalendar) => void;@@ -115,6 +116,7 @@ interface ShiftDetailRowProps {export function ShiftDetailRow({shift,canEdit,+ canDelete,actions,onEdit,onDelete,@@ -122,7 +124,10 @@ export function ShiftDetailRow({const t = useTranslations();const locale = useLocale();const synced = shift.syncedFromExternal || !!shift.externalSyncId;+ // editOwnShift/editAnyShift and deleteOwnShift/deleteAnyShift are independent+ // capabilities — a bundle can grant one without the other.const editable = canEdit && !synced;+ const deletable = canDelete && !synced;const minutes = getShiftMinutes(shift);const { user: currentUser } = useAuth();@@ -184,7 +189,7 @@ export function ShiftDetailRow({{formatHours(minutes, locale)}</span>)}- {editable &&+ {(editable || deletable) &&(actions === "menu" ? (<DropdownMenu><DropdownMenuTrigger@@ -195,51 +200,59 @@ export function ShiftDetailRow({<Ellipsis className="size-4" /></DropdownMenuTrigger><DropdownMenuContent align="end">- <DropdownMenuItem+ {editable && (+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ onEdit(shift);+ }}+ >+ <Pencil className="mr-2 size-4" />+ {t("shift.edit")}+ </DropdownMenuItem>+ )}+ {deletable && (+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ onDelete(shift);+ }}+ className="text-danger focus:text-danger"+ >+ <Trash2 className="mr-2 size-4" />+ {t("common.delete")}+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <div className="flex items-center">+ {editable && (+ <button+ type="button"onClick={(e) => {e.stopPropagation();onEdit(shift);}}+ aria-label={t("shift.edit")}+ className="flex size-9 items-center justify-center rounded-md text-fg-secondary">- <Pencil className="mr-2 size-4" />- {t("shift.edit")}- </DropdownMenuItem>- <DropdownMenuItem+ <Pencil className="size-[17px]" />+ </button>+ )}+ {deletable && (+ <button+ type="button"onClick={(e) => {e.stopPropagation();onDelete(shift);}}- className="text-danger focus:text-danger"+ aria-label={t("common.delete")}+ className="flex size-9 items-center justify-center rounded-md text-fg-secondary">- <Trash2 className="mr-2 size-4" />- {t("common.delete")}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- ) : (- <div className="flex items-center">- <button- type="button"- onClick={(e) => {- e.stopPropagation();- onEdit(shift);- }}- aria-label={t("shift.edit")}- className="flex size-9 items-center justify-center rounded-md text-fg-secondary"- >- <Pencil className="size-[17px]" />- </button>- <button- type="button"- onClick={(e) => {- e.stopPropagation();- onDelete(shift);- }}- aria-label={t("common.delete")}- className="flex size-9 items-center justify-center rounded-md text-fg-secondary"- >- <Trash2 className="size-[17px]" />- </button>+ <Trash2 className="size-[17px]" />+ </button>+ )}</div>))}</div>diff --git a/components/day-inspector.tsx b/components/day-inspector.tsxindex 161b8a9..412444d 100644--- a/components/day-inspector.tsx+++ b/components/day-inspector.tsx@@ -35,7 +35,14 @@ export interface DayViewModel {dayNotes: CalendarNote[];totalMinutes: number;summary: PeriodSummary;- canEdit: boolean;+ /** createShift — gates the "add a new shift" affordance */+ canAddShift: boolean;+ /** manageOwnNotesEvents — creating a note/event only ever needs "own" */+ canAddNote: boolean;+ /** Per-shift own/any precision (editOwnShift/editAnyShift) */+ canEditShift: (shift: ShiftWithCalendar) => boolean;+ /** Per-shift own/any precision (deleteOwnShift/deleteAnyShift) — independent from canEditShift */+ canDeleteShift: (shift: ShiftWithCalendar) => boolean;}export function useDayLabels(day: Date) {@@ -62,8 +69,18 @@ export function DayInspector({}) {const t = useTranslations();const locale = useLocale();- const { selectedDay, currentDate, dayShifts, dayNotes, totalMinutes, summary, canEdit } =- model;+ const {+ selectedDay,+ currentDate,+ dayShifts,+ dayNotes,+ totalMinutes,+ summary,+ canAddShift,+ canAddNote,+ canEditShift,+ canDeleteShift,+ } = model;const labels = useDayLabels(selectedDay);const monthName = format(currentDate, "LLLL", { locale: getDateLocale(locale) });@@ -84,7 +101,7 @@ export function DayInspector({{labels.short}</h2></div>- {canEdit && (+ {canAddShift && (<Buttonsize="sm"onClick={actions.onAddShift}@@ -107,7 +124,8 @@ export function DayInspector({<ShiftDetailRowkey={shift.id}shift={shift}- canEdit={canEdit}+ canEdit={canEditShift(shift)}+ canDelete={canDeleteShift(shift)}actions="menu"onEdit={actions.onEditShift}onDelete={actions.onDeleteShift}@@ -117,7 +135,7 @@ export function DayInspector({<NoteDetailCardkey={note.id}note={note}- onOpen={canEdit ? actions.onOpenNote : undefined}+ onOpen={canAddNote ? actions.onOpenNote : undefined}/>))}{dayShifts.length === 0 && dayNotes.length === 0 && (@@ -125,7 +143,7 @@ export function DayInspector({{t("calendarView.dayEmpty")}</p>)}- {canEdit && (+ {canAddNote && (<buttontype="button"onClick={actions.onAddNote}diff --git a/components/dialog-manager.tsx b/components/dialog-manager.tsxindex eac0a53..837f3eb 100644--- a/components/dialog-manager.tsx+++ b/components/dialog-manager.tsx@@ -77,7 +77,10 @@ interface DialogManagerProps {// Month summary dialogs opened from the day inspectorcurrentDate: Date;shifts: ShiftWithCalendar[];- canEditShifts: boolean;+ /** Per-shift own/any precision (editOwnShift/editAnyShift) — a calendar-wide boolean can't tell own from another's entry. */+ canEditShift: (shift: ShiftWithCalendar) => boolean;+ /** Per-shift own/any precision (deleteOwnShift/deleteAnyShift) — independent from canEditShift. */+ canDeleteShift: (shift: ShiftWithCalendar) => boolean;showMonthStatsDialog: boolean;onMonthStatsDialogChange: (open: boolean) => void;showMonthShiftsDialog: boolean;@@ -153,7 +156,8 @@ export function DialogManager(props: DialogManagerProps) {shifts={props.selectedDayShifts}onDeleteShift={props.onDeleteShiftFromDayDialog}onEditShift={props.onEditShiftFromDayDialog}- canEdit={props.canEditShifts}+ canEditShift={props.canEditShift}+ canDeleteShift={props.canDeleteShift}/>{props.selectedDayDate && (@@ -179,7 +183,8 @@ export function DialogManager(props: DialogManagerProps) {onOpenChange={props.onMonthShiftsDialogChange}currentDate={props.currentDate}shifts={props.shifts}- canEdit={props.canEditShifts}+ canEditShift={props.canEditShift}+ canDeleteShift={props.canDeleteShift}onEditShift={(shift) => props.onEditShiftFromDayDialog?.(shift)}onDeleteShift={props.onDeleteShift}/>diff --git a/components/guest-permission-selector.tsx b/components/guest-permission-selector.tsxdeleted file mode 100644index 2594e66..0000000--- a/components/guest-permission-selector.tsx+++ /dev/null@@ -1,76 +0,0 @@-"use client";--import { useTranslations } from "next-intl";-import { Info } from "lucide-react";-import { InfoNote, OptionCards } from "@/components/form-kit";-import { cn } from "@/lib/utils";--type GuestPermission = "none" | "read" | "write";--/** Who a public-access level reaches; visitors without an account only with ALLOW_GUEST_ACCESS. */-export function usePublicAccessNote() {- const t = useTranslations();- return (value: GuestPermission, allowGuest: boolean) => {- if (value === "none") return t("share.publicPermissionNoneDesc");- if (value === "read")- return allowGuest- ? t("share.publicPermissionReadDescGuestsOn")- : t("share.publicPermissionReadDescGuestsOff");- return allowGuest- ? t("share.publicPermissionWriteDescGuestsOn")- : t("share.publicPermissionWriteDescGuestsOff");- };-}--interface GuestPermissionSelectorProps {- value: GuestPermission;- onChange: (value: GuestPermission) => void;- allowGuest: boolean;- disabled?: boolean;-}--export function GuestPermissionSelector({- value,- onChange,- allowGuest,- disabled = false,-}: GuestPermissionSelectorProps) {- const t = useTranslations();- const publicAccessNote = usePublicAccessNote();-- return (- <div className="flex flex-col gap-2.5">- {/* A disabled fieldset disables the option buttons natively. */}- <fieldset disabled={disabled} className={cn("m-0 min-w-0 border-0 p-0", disabled && "opacity-60")}>- <OptionCards<GuestPermission>- label={t("share.publicAccess")}- columns={3}- value={value}- onChange={onChange}- options={[- {- value: "none",- title: t("sharingSheet.accessNone"),- description: t("sharingSheet.guestNoneShort"),- },- {- value: "read",- title: t("sharingSheet.permRead"),- description: allowGuest- ? t("sharingSheet.guestReadShortGuestsOn")- : t("sharingSheet.guestReadShortGuestsOff"),- },- {- value: "write",- title: t("sharingSheet.permWrite"),- description: allowGuest- ? t("sharingSheet.guestWriteShortGuestsOn")- : t("sharingSheet.guestWriteShortGuestsOff"),- },- ]}- />- </fieldset>- <InfoNote icon={Info}>{publicAccessNote(value, allowGuest)}</InfoNote>- </div>- );-}diff --git a/components/mobile-day-sheet.tsx b/components/mobile-day-sheet.tsxindex 8fbf914..a5c09c6 100644--- a/components/mobile-day-sheet.tsx+++ b/components/mobile-day-sheet.tsx@@ -134,7 +134,8 @@ export function MobileDaySheet({setWasOpen(open);if (open) setSnapIndex(0);}- const { selectedDay, dayShifts, dayNotes, canEdit } = model;+ const { selectedDay, dayShifts, dayNotes, canAddShift, canAddNote, canEditShift, canDeleteShift } =+ model;const labels = useDayLabels(selectedDay);const windowHeight = useWindowHeight();@@ -220,7 +221,8 @@ export function MobileDaySheet({<ShiftDetailRowkey={shift.id}shift={shift}- canEdit={canEdit}+ canEdit={canEditShift(shift)}+ canDelete={canDeleteShift(shift)}actions="inline"onEdit={(s) => {close();@@ -233,7 +235,7 @@ export function MobileDaySheet({<NoteDetailCardkey={note.id}note={note}- onOpen={canEdit ? (n) => { close(); actions.onOpenNote(n); } : undefined}+ onOpen={canAddNote ? (n) => { close(); actions.onOpenNote(n); } : undefined}/>))}{dayShifts.length === 0 && dayNotes.length === 0 && (@@ -244,26 +246,30 @@ export function MobileDaySheet({</div></div>- {canEdit && (+ {(canAddShift || canAddNote) && (<divref={barRef}className="flex shrink-0 gap-2 border-t border-line px-4 pb-[max(12px,env(safe-area-inset-bottom))] pt-3">- <Button- onClick={run(actions.onAddShift)}- className="h-11 flex-1 gap-2 rounded-[10px] text-[14px] font-semibold"- >- <Plus className="size-[18px]" />- {t("calendarView.shift")}- </Button>- <Button- variant="outline"- onClick={run(actions.onAddNote)}- className="h-11 flex-1 gap-2 rounded-[10px] text-[14px] font-semibold"- >- <StickyNote className="size-[18px]" />- {t("calendarView.note")}- </Button>+ {canAddShift && (+ <Button+ onClick={run(actions.onAddShift)}+ className="h-11 flex-1 gap-2 rounded-[10px] text-[14px] font-semibold"+ >+ <Plus className="size-[18px]" />+ {t("calendarView.shift")}+ </Button>+ )}+ {canAddNote && (+ <Button+ variant="outline"+ onClick={run(actions.onAddNote)}+ className="h-11 flex-1 gap-2 rounded-[10px] text-[14px] font-semibold"+ >+ <StickyNote className="size-[18px]" />+ {t("calendarView.note")}+ </Button>+ )}</div>)}</div>diff --git a/components/month-dialogs.tsx b/components/month-dialogs.tsxindex 9f43125..b614e8b 100644--- a/components/month-dialogs.tsx+++ b/components/month-dialogs.tsx@@ -42,12 +42,16 @@ export function MonthShiftsDialog({onOpenChange,currentDate,shifts,- canEdit,+ canEditShift,+ canDeleteShift,onEditShift,onDeleteShift,}: MonthDialogProps & {shifts: ShiftWithCalendar[];- canEdit: boolean;+ /** Per-shift own/any precision (editOwnShift/editAnyShift) */+ canEditShift: (shift: ShiftWithCalendar) => boolean;+ /** Per-shift own/any precision (deleteOwnShift/deleteAnyShift) — independent from canEditShift */+ canDeleteShift: (shift: ShiftWithCalendar) => boolean;onEditShift: (shift: ShiftWithCalendar) => void;onDeleteShift: (shift: ShiftWithCalendar) => void;}) {@@ -115,7 +119,8 @@ export function MonthShiftsDialog({<ShiftDetailRowkey={shift.id}shift={shift}- canEdit={canEdit}+ canEdit={canEditShift(shift)}+ canDelete={canDeleteShift(shift)}actions="menu"onEdit={(s) => {onOpenChange(false);diff --git a/components/note-sheet.tsx b/components/note-sheet.tsxindex 28c0a8c..d2bc37e 100644--- a/components/note-sheet.tsx+++ b/components/note-sheet.tsx@@ -116,7 +116,11 @@ export function NoteSheet({setIntervalDraft(null);}- const isReadOnly = readOnly || !permission.canEdit;+ const isReadOnly =+ readOnly ||+ (note+ ? !permission.canOwned("manageOwnNotesEvents", "manageAnyNotesEvents", note.createdBy)+ : !permission.can("manageOwnNotesEvents"));const isEvent = form.type === "event";const update = (patch: Partial<NoteFormState>) => setForm((prev) => ({ ...prev, ...patch }));diff --git a/components/notes-list-dialog.tsx b/components/notes-list-dialog.tsxindex 59e52b0..9bd8a46 100644--- a/components/notes-list-dialog.tsx+++ b/components/notes-list-dialog.tsx@@ -105,7 +105,12 @@ export function NotesListDialog({const t = useTranslations();const locale = useLocale();const permission = useCalendarPermission(calendarId);- const isReadOnly = readOnly || !permission.canEdit;+ // Single capability pair for notes, so "can create" doubles as the banner's+ // "no notes capability at all" — per-row edit/delete still gate themselves.+ const canCreate = !readOnly && permission.can("manageOwnNotesEvents");+ const canEditNote = (note: CalendarNote) =>+ !readOnly &&+ permission.canOwned("manageOwnNotesEvents", "manageAnyNotesEvents", note.createdBy);const formattedDate = formatLongDate(date, locale, { year: true });@@ -139,7 +144,7 @@ export function NotesListDialog({</Button>}>- {isReadOnly && <ReadOnlyBanner message={t("guest.cannotEdit")} />}+ {!canCreate && <ReadOnlyBanner message={t("guest.cannotEdit")} />}{entries.length === 0 && (<p className="py-6 text-center text-[13px] text-fg-tertiary">{t("note.noEntries")}</p>@@ -149,13 +154,13 @@ export function NotesListDialog({<NoteRowkey={note.id}note={note}- editable={!isReadOnly}+ editable={canEditNote(note)}onEdit={() => onEditNote(note)}onDelete={() => onDeleteNote(note.id)}/>))}- {!isReadOnly && (+ {canCreate && (<buttontype="button"onClick={handleAdd}diff --git a/components/permission-bundle-assignments.tsx b/components/permission-bundle-assignments.tsxnew file mode 100644index 0000000..a031718--- /dev/null+++ b/components/permission-bundle-assignments.tsx@@ -0,0 +1,249 @@+"use client";++import { useState } from "react";+import { useTranslations } from "next-intl";+import { Trash2, TriangleAlert } from "lucide-react";+import { Button } from "@/components/ui/button";+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";+import { SegmentedControl } from "@/components/segmented-control";+import { StatusBanner } from "@/components/status-banner";+import { PersonRow } from "@/components/person-row";+import { CalendarShareUserSearch } from "@/components/calendar-share-user-search";+import { BundlePicker, useBundleDisplayName } from "@/components/permission-bundle-picker";+import { CalendarTokenList } from "@/components/calendar-token-list";+import { AccessLinkCreateForm } from "@/components/calendar-token-form";+import { useCalendarShares, type CalendarShare } from "@/hooks/useCalendarShares";+import { useCalendarBundles } from "@/hooks/useCalendarBundles";+import { useCalendars } from "@/hooks/useCalendars";+import { useCalendarPermission } from "@/hooks/useCalendarPermission";+import { useAuth } from "@/hooks/useAuth";+import type { usePermissionLinkForm } from "@/hooks/usePermissionLinkForm";+import type { CalendarWithCount } from "@/lib/types";++interface PermissionAssignmentsProps {+ calendarId: string;+ allowGuest: boolean;+ linkForm: ReturnType<typeof usePermissionLinkForm>;+ calendar: CalendarWithCount | undefined;+ updateCalendar: ReturnType<typeof useCalendars>["updateCalendar"];+}++/** "Zuweisungen" tab: who and what holds each bundle — people, public/guest access, links. */+export function PermissionAssignments({+ calendarId,+ allowGuest,+ linkForm,+ calendar,+ updateCalendar,+}: PermissionAssignmentsProps) {+ const t = useTranslations();+ const { user: currentUser } = useAuth();+ const { bundles, isError: bundlesError } = useCalendarBundles(calendarId);+ const { shares, updateShare, removeShare } = useCalendarShares(calendarId);+ const { can, isOwner } = useCalendarPermission(calendarId);+ const displayName = useBundleDisplayName();++ // S2: assigning shares needs manageShares; guest access and links need+ // manageGuestAccess — a bundle can hold one without the other.+ const canManageShares = can("manageShares");+ const canManageGuestAccess = can("manageGuestAccess");++ const [inviteBundleId, setInviteBundleId] = useState<string>("");+ const [shareToDelete, setShareToDelete] = useState<CalendarShare | null>(null);+ const [guestSaving, setGuestSaving] = useState(false);+ const [optimisticGuestBundleId, setOptimisticGuestBundleId] = useState<+ string | null | undefined+ >(undefined);++ type AssignmentSubTab = "people" | "public" | "links";+ const [subTab, setSubTab] = useState<AssignmentSubTab>("people");+ const subTabs: { value: AssignmentSubTab; label: string }[] = [+ { value: "people", label: t("permissionBundles.people") },+ { value: "public", label: t("share.publicAccess") },+ ...(allowGuest+ ? [{ value: "links" as const, label: t("share.links") }]+ : []),+ ];++ const effectiveInviteBundleId =+ inviteBundleId || bundles.find((b) => b.seedKey === "read")?.id || bundles[0]?.id || "";++ const guestBundleId =+ optimisticGuestBundleId !== undefined+ ? optimisticGuestBundleId+ : (calendar?.guestBundleId ?? null);++ const handleGuestChange = async (bundleId: string | null) => {+ if (!canManageGuestAccess) return;+ setOptimisticGuestBundleId(bundleId);+ setGuestSaving(true);+ try {+ await updateCalendar(calendarId, { guestBundleId: bundleId });+ } finally {+ setGuestSaving(false);+ setOptimisticGuestBundleId(undefined);+ }+ };++ const you = <span className="ml-1.5 font-normal text-fg-tertiary">({t("share.you")})</span>;+ const staticLabel = (label: string) => (+ <span className="shrink-0 px-[9px] text-[12.5px] font-medium text-fg-secondary">{label}</span>+ );++ const ownerRow = isOwner && currentUser && (+ <PersonRow+ user={{ name: currentUser.name ?? null, email: currentUser.email, image: currentUser.image }}+ highlight+ suffix={you}+ action={staticLabel(t("sharingSheet.owner"))}+ />+ );++ const cardClass = "flex flex-col gap-3 rounded-[11px] border border-line p-3.5";++ return (+ <div className="flex flex-col gap-3.5">+ <SegmentedControl+ label={t("permissionBundles.tabAssignments")}+ value={subTab}+ onChange={setSubTab}+ options={subTabs}+ />++ {subTab === "people" && (+ <section className={cardClass}>+ {canManageShares && bundlesError && (+ <StatusBanner tone="danger" icon={TriangleAlert}>+ {t("permissionBundles.bundlesUnavailable")}+ </StatusBanner>+ )}+ {canManageShares && !bundlesError && (+ <div className="flex flex-col gap-2 sm:flex-row">+ <div className="min-w-0 flex-1">+ <CalendarShareUserSearch calendarId={calendarId} bundleId={effectiveInviteBundleId} />+ </div>+ <BundlePicker+ bundles={bundles}+ value={effectiveInviteBundleId || null}+ onChange={(id) => id && setInviteBundleId(id)}+ triggerAriaLabel={t("permissionBundles.inviteAs")}+ className="h-10 shrink-0 self-start"+ />+ </div>+ )}+ <div className="flex flex-col gap-2">+ {ownerRow}+ {shares.map((share) => {+ const isSelf = share.userId === currentUser?.id;+ const editable = canManageShares && !isSelf && !bundlesError;+ return (+ <PersonRow+ key={share.id}+ user={share.user}+ suffix={isSelf ? you : undefined}+ action={+ editable ? (+ <div className="flex shrink-0 items-center gap-1.5">+ <BundlePicker+ bundles={bundles}+ value={share.bundleId}+ onChange={(id) => id && updateShare(share.id, id)}+ triggerAriaLabel={t("sharingSheet.changePermission", {+ name: share.user.name || share.user.email,+ })}+ />+ <button+ type="button"+ aria-label={t("share.removeAccess")}+ onClick={() => setShareToDelete(share)}+ className="flex size-8 shrink-0 items-center justify-center rounded-lg text-fg-tertiary transition-colors hover:bg-danger-soft hover:text-danger"+ >+ <Trash2 className="size-4" />+ </button>+ </div>+ ) : (+ staticLabel(displayName(share.bundle) ?? "")+ )+ }+ />+ );+ })}+ {shares.length === 0 && !ownerRow && (+ <p className="rounded-[11px] border border-dashed border-control px-3.5 py-3 text-center text-[13px] text-fg-tertiary">+ {t("share.noSharesDescription")}+ </p>+ )}+ </div>+ </section>+ )}++ {subTab === "public" && (+ <section className={cardClass}>+ {canManageGuestAccess && bundlesError ? (+ <StatusBanner tone="danger" icon={TriangleAlert}>+ {t("permissionBundles.bundlesUnavailable")}+ </StatusBanner>+ ) : (+ <div className="flex flex-col gap-2.5 sm:flex-row sm:items-center sm:justify-between sm:gap-3">+ <p className="min-w-0 flex-1 text-[13px] text-fg-secondary">+ {allowGuest+ ? t("share.publicAccessDescriptionGuestsOn")+ : t("share.publicAccessDescriptionGuestsOff")}+ </p>+ <BundlePicker+ bundles={bundles}+ value={guestBundleId}+ onChange={handleGuestChange}+ guestEligibleOnly+ allowNone+ noneLabel={t("sharingSheet.accessNone")}+ disabled={!canManageGuestAccess || guestSaving}+ triggerAriaLabel={t("share.publicAccess")}+ />+ </div>+ )}+ </section>+ )}++ {subTab === "links" && allowGuest && (+ <section className={cardClass}>+ <CalendarTokenList calendarId={calendarId} />+ {canManageGuestAccess && linkForm.bundlesError && (+ <StatusBanner tone="danger" icon={TriangleAlert}>+ {t("permissionBundles.bundlesUnavailable")}+ </StatusBanner>+ )}+ {canManageGuestAccess && !linkForm.bundlesError && (+ <>+ <AccessLinkCreateForm form={linkForm} />+ <Button+ onClick={linkForm.create}+ disabled={linkForm.creating || !linkForm.bundleId}+ className="h-10 self-start font-semibold"+ >+ {linkForm.creating ? t("sharingSheet.creating") : t("sharingSheet.createLink")}+ </Button>+ </>+ )}+ </section>+ )}++ {shareToDelete && (+ <ConfirmationDialog+ open+ onOpenChange={(open) => !open && setShareToDelete(null)}+ onConfirm={async () => {+ await removeShare(shareToDelete.id);+ setShareToDelete(null);+ }}+ title={t("share.removeShareConfirmTitle")}+ description={t("share.removeShareConfirmDesc", {+ user: shareToDelete.user.name || shareToDelete.user.email,+ })}+ confirmVariant="destructive"+ confirmText={t("share.removeAccess")}+ />+ )}+ </div>+ );+}diff --git a/components/permission-bundle-editor.tsx b/components/permission-bundle-editor.tsxnew file mode 100644index 0000000..7bd6029--- /dev/null+++ b/components/permission-bundle-editor.tsx@@ -0,0 +1,313 @@+"use client";++import { useState } from "react";+import { useTranslations } from "next-intl";+import { ChevronDown, Copy, Info, MoreVertical, Plus, Trash2, TriangleAlert } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";+import { StatusBanner } from "@/components/status-banner";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { CheckRow, Field, InfoNote, SectionLabel, inputClass } from "@/components/form-kit";+import {+ useCalendarBundles,+ type PermissionBundle,+ type PermissionBundleWithUsage,+} from "@/hooks/useCalendarBundles";+import { usePermissionBundleForm } from "@/hooks/usePermissionBundleForm";+import { useBundleDisplayName } from "@/components/permission-bundle-picker";+import {+ CAPABILITY_GROUPS,+ getBlockingDependents,+ isAdminOnlyCapability,+ type Capability,+} from "@/lib/permission-bundles";+import { cn } from "@/lib/utils";++type UpdateBundle = (+ bundleId: string,+ input: { name?: string; capabilities?: Capability[] }+) => Promise<PermissionBundle>;++function BundleEditor({+ bundle,+ updateBundle,+}: {+ bundle: PermissionBundleWithUsage;+ updateBundle: UpdateBundle;+}) {+ const t = useTranslations();+ const form = usePermissionBundleForm(bundle);+ const [saving, setSaving] = useState(false);++ const save = async () => {+ setSaving(true);+ try {+ await updateBundle(bundle.id, {+ ...(form.name.trim() !== bundle.name ? { name: form.name.trim() } : {}),+ capabilities: form.capabilities,+ });+ } finally {+ setSaving(false);+ }+ };++ return (+ <div className="flex flex-col gap-4 border-t border-line px-3.5 py-4">+ <Field label={t("common.labels.name")} htmlFor={`bundle-name-${bundle.id}`}>+ <Input+ id={`bundle-name-${bundle.id}`}+ value={form.name}+ onChange={(e) => form.setName(e.target.value)}+ className={inputClass}+ maxLength={50}+ />+ </Field>++ {form.isGuestBound && (+ <InfoNote icon={Info}>{t("permissionBundles.guestLockedHint")}</InfoNote>+ )}+ {form.stampPresetBypassWarning && (+ <InfoNote icon={TriangleAlert}>+ {t("permissionBundles.stampPresetBypassWarning")}+ </InfoNote>+ )}++ {CAPABILITY_GROUPS.map((group) => (+ <section key={group.key} className="flex flex-col gap-2">+ <SectionLabel className="mb-0">+ {t(`permissionBundles.groups.${group.key}`)}+ </SectionLabel>+ <div className="flex flex-col gap-2.5">+ {group.capabilities.map((capability) => {+ const guestLocked = form.isGuestBound && isAdminOnlyCapability(capability);+ const blockers = guestLocked+ ? []+ : getBlockingDependents(capability, form.capabilities);+ const dependencyLocked = blockers.length > 0;+ const hint = guestLocked+ ? undefined+ : dependencyLocked+ ? t("permissionBundles.requiredByHint", {+ capability: t(`permissionBundles.capabilityLabels.${blockers[0]}`),+ })+ : t(`permissionBundles.capabilityHints.${capability}`);+ return (+ <CheckRow+ key={capability}+ id={`cap-${bundle.id}-${capability}`}+ checked={form.capabilities.includes(capability)}+ onCheckedChange={(checked) => form.toggle(capability, checked)}+ disabled={guestLocked || dependencyLocked}+ label={t(`permissionBundles.capabilityLabels.${capability}`)}+ hint={hint}+ />+ );+ })}+ </div>+ </section>+ ))}++ <div className="flex gap-2">+ <Button+ variant="outline"+ className="h-10 flex-1 font-semibold"+ onClick={form.reset}+ disabled={!form.dirty || saving}+ >+ {t("common.cancel")}+ </Button>+ <Button+ className="h-10 flex-1 font-semibold"+ onClick={save}+ disabled={!form.dirty || !form.name.trim() || saving}+ >+ {saving ? t("common.saving") : t("common.save")}+ </Button>+ </div>+ </div>+ );+}++function BundleRow({+ bundle,+ expanded,+ onToggleExpand,+ onClone,+ onDelete,+ updateBundle,+}: {+ bundle: PermissionBundleWithUsage;+ expanded: boolean;+ onToggleExpand: () => void;+ onClone: () => void;+ onDelete: () => void;+ updateBundle: UpdateBundle;+}) {+ const t = useTranslations();+ const displayName = useBundleDisplayName();+ const usageCount =+ bundle.usage.shareCount + bundle.usage.tokenCount + (bundle.usage.isGuestBundle ? 1 : 0);++ return (+ <div className="rounded-[11px] border border-line">+ <div className="flex items-center gap-1 px-2 py-1.5">+ <div+ role="button"+ tabIndex={0}+ onClick={onToggleExpand}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ onToggleExpand();+ }+ }}+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 rounded-lg px-1.5 py-1.5 hover:bg-surface-panel"+ >+ <span className="min-w-0 flex-1">+ <span className="block text-[14px] font-semibold text-fg-strong">+ {displayName(bundle)}+ </span>+ <span className="block text-[12px] text-fg-tertiary">+ {t("permissionBundles.usedByCount", { count: usageCount })}+ </span>+ </span>+ <ChevronDown+ className={cn(+ "size-4 shrink-0 text-fg-tertiary transition-transform",+ expanded && "rotate-180"+ )}+ />+ </div>+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label={t("common.labels.action")}+ className="flex size-8 shrink-0 items-center justify-center rounded-lg text-fg-tertiary transition-colors hover:bg-surface-panel data-[state=open]:bg-surface-panel"+ >+ <MoreVertical className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={onClone} className="gap-2.5">+ <Copy className="size-4" />+ {t("permissionBundles.clone")}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={onDelete} className="gap-2.5 text-danger focus:text-danger">+ <Trash2 className="size-4 text-danger" />+ {t("common.delete")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ {expanded && <BundleEditor bundle={bundle} updateBundle={updateBundle} />}+ </div>+ );+}++/** "Gruppen" tab: bundle list, create/clone/delete, and the capability editor. */+export function PermissionBundleEditor({ calendarId }: { calendarId: string }) {+ const t = useTranslations();+ const { bundles, isError, createBundle, cloneBundle, deleteBundle, updateBundle } =+ useCalendarBundles(calendarId);+ const displayName = useBundleDisplayName();+ const [expandedId, setExpandedId] = useState<string | null>(null);+ const [creating, setCreating] = useState(false);+ const [newName, setNewName] = useState("");+ const [bundleToDelete, setBundleToDelete] = useState<PermissionBundleWithUsage | null>(null);++ if (isError) {+ return (+ <StatusBanner tone="danger" icon={TriangleAlert}>+ {t("permissionBundles.bundlesUnavailable")}+ </StatusBanner>+ );+ }++ const handleCreate = async () => {+ const name = newName.trim();+ if (!name) return;+ const created = await createBundle({ name, capabilities: [] });+ setNewName("");+ setCreating(false);+ setExpandedId(created.id);+ };++ const handleClone = async (bundle: PermissionBundleWithUsage) => {+ const suggested = `${displayName(bundle)} ${t("permissionBundles.cloneSuffix")}`;+ const cloned = await cloneBundle(bundle.id, suggested);+ setExpandedId(cloned.id);+ };++ return (+ <div className="flex flex-col gap-3">+ {bundles.map((bundle) => (+ <BundleRow+ key={bundle.id}+ bundle={bundle}+ expanded={expandedId === bundle.id}+ onToggleExpand={() => setExpandedId((id) => (id === bundle.id ? null : bundle.id))}+ onClone={() => handleClone(bundle)}+ onDelete={() => setBundleToDelete(bundle)}+ updateBundle={updateBundle}+ />+ ))}++ {creating ? (+ <div className="flex gap-2">+ <Input+ autoFocus+ value={newName}+ onChange={(e) => setNewName(e.target.value)}+ placeholder={t("permissionBundles.newBundleNamePlaceholder")}+ className={cn(inputClass, "min-w-0 flex-1")}+ maxLength={50}+ onKeyDown={(e) => e.key === "Enter" && handleCreate()}+ />+ <Button onClick={handleCreate} disabled={!newName.trim()} className="h-10 shrink-0 font-semibold">+ {t("common.save")}+ </Button>+ <Button+ variant="outline"+ onClick={() => {+ setCreating(false);+ setNewName("");+ }}+ className="h-10 shrink-0 font-semibold"+ >+ {t("common.cancel")}+ </Button>+ </div>+ ) : (+ <Button+ variant="outline"+ onClick={() => setCreating(true)}+ className="h-10 justify-start gap-2 font-semibold"+ >+ <Plus className="size-4" />+ {t("permissionBundles.newBundle")}+ </Button>+ )}++ {bundleToDelete && (+ <ConfirmationDialog+ open+ onOpenChange={(open) => !open && setBundleToDelete(null)}+ onConfirm={async () => {+ await deleteBundle(bundleToDelete.id);+ setBundleToDelete(null);+ }}+ title={t("permissionBundles.deleteConfirmTitle")}+ description={t("permissionBundles.deleteConfirmDesc", {+ name: displayName(bundleToDelete) ?? "",+ })}+ confirmVariant="destructive"+ confirmText={t("common.delete")}+ />+ )}+ </div>+ );+}diff --git a/components/permission-bundle-picker.tsx b/components/permission-bundle-picker.tsxnew file mode 100644index 0000000..11dbe1f--- /dev/null+++ b/components/permission-bundle-picker.tsx@@ -0,0 +1,96 @@+"use client";++import { useTranslations } from "next-intl";+import { Check, ChevronDown } from "lucide-react";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { isGuestEligible, type BundleRef, type Capability } from "@/lib/permission-bundles";+import { cn } from "@/lib/utils";++export interface BundleOption extends BundleRef {+ capabilities: Capability[];+}++/** A bundle's display name: the translated standard label while `seedKey` is set, otherwise its own name (4.2/E6). */+export function useBundleDisplayName() {+ const t = useTranslations();+ return (bundle: Pick<BundleOption, "name" | "seedKey"> | null | undefined) => {+ if (!bundle) return null;+ return bundle.seedKey ? t(`permissionBundles.seed.${bundle.seedKey}`) : bundle.name;+ };+}++interface BundlePickerProps {+ bundles: BundleOption[];+ /** null selects the "no access" option (only meaningful with allowNone). */+ value: string | null;+ onChange: (bundleId: string | null) => void;+ /** Restrict to guest-eligible bundles only (guest access / links, E7). */+ guestEligibleOnly?: boolean;+ /** Adds a "no access" option that reports null. */+ allowNone?: boolean;+ noneLabel?: string;+ disabled?: boolean;+ triggerAriaLabel?: string;+ className?: string;+}++/** Dropdown to assign a permission bundle — replaces the old read/write/admin pickers. */+export function BundlePicker({+ bundles,+ value,+ onChange,+ guestEligibleOnly = false,+ allowNone = false,+ noneLabel,+ disabled = false,+ triggerAriaLabel,+ className,+}: BundlePickerProps) {+ const displayName = useBundleDisplayName();+ const options = guestEligibleOnly+ ? bundles.filter((b) => isGuestEligible(b.capabilities))+ : bundles;+ const selected = value ? options.find((b) => b.id === value) : null;+ const label = value === null ? noneLabel : selected ? displayName(selected) : "…";++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ disabled={disabled}+ aria-label={triggerAriaLabel}+ className={cn(+ "flex h-[30px] shrink-0 items-center gap-1.5 rounded-lg border border-line px-[9px] text-[12.5px] font-medium text-fg-body transition-colors hover:bg-surface-panel disabled:pointer-events-none disabled:opacity-50 data-[state=open]:bg-surface-panel",+ className+ )}+ >+ {label}+ <ChevronDown className="size-[13px] text-fg-tertiary" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-64">+ {allowNone && (+ <DropdownMenuItem onClick={() => onChange(null)} className="items-start gap-2.5 py-2">+ <Check className={cn("mt-0.5 size-4 shrink-0 text-brand", value !== null && "invisible")} />+ <span className="text-[13px] font-semibold text-fg-strong">{noneLabel}</span>+ </DropdownMenuItem>+ )}+ {options.map((bundle) => (+ <DropdownMenuItem+ key={bundle.id}+ onClick={() => onChange(bundle.id)}+ className="items-start gap-2.5 py-2"+ >+ <Check+ className={cn("mt-0.5 size-4 shrink-0 text-brand", bundle.id !== value && "invisible")}+ />+ <span className="text-[13px] font-semibold text-fg-strong">{displayName(bundle)}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/components/person-row.tsx b/components/person-row.tsxnew file mode 100644index 0000000..afe66de--- /dev/null+++ b/components/person-row.tsx@@ -0,0 +1,51 @@+"use client";++import { ReactNode } from "react";+import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";+import { ListRow } from "@/components/form-kit";+import { cn, getUserInitials } from "@/lib/utils";++/** Avatar + name/email row shared by the permissions panel and the shift-signup list. */+export function PersonRow({+ user,+ highlight,+ suffix,+ action,+ fallback = "…",+ showEmail = true,+}: {+ user: { name: string | null; email?: string; image?: string | null };+ highlight?: boolean;+ suffix?: ReactNode;+ action?: ReactNode;+ /** Shown when the user has neither a name nor an email. */+ fallback?: ReactNode;+ /** Second line with the user's email below their name. */+ showEmail?: boolean;+}) {+ return (+ <ListRow>+ <Avatar className="size-8">+ {user.image && <AvatarImage src={user.image} alt="" />}+ <AvatarFallback+ className={cn(+ "text-[11.5px] font-semibold",+ highlight ? "bg-brand-soft text-brand-ink" : "bg-surface-sunken text-fg-secondary"+ )}+ >+ {getUserInitials(user)}+ </AvatarFallback>+ </Avatar>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[14px] font-semibold text-fg-strong">+ {user.name || user.email || fallback}+ {suffix}+ </div>+ {showEmail && user.name && user.email && (+ <div className="truncate text-[12px] text-fg-tertiary">{user.email}</div>+ )}+ </div>+ {action}+ </ListRow>+ );+}diff --git a/components/preset-list.tsx b/components/preset-list.tsxindex b9ac818..bf90ca4 100644--- a/components/preset-list.tsx+++ b/components/preset-list.tsx@@ -26,7 +26,12 @@ import { ListRow, Pill, RowIconButton, SectionLabel } from "@/components/form-kiimport { cn } from "@/lib/utils";interface PresetRowActions {- readOnly: boolean;+ /** Per-preset Own/Any check — edit/delete depend on who created that preset. */+ canEdit: (preset: ShiftPreset) => boolean;+ /** Cloning creates a new preset, so it's gated calendar-wide, not per-row. */+ canClone: boolean;+ /** Reordering changes the shared order for everyone, so it needs manageAnyPresets. */+ canReorder: boolean;editingId: string | null;deletingId: string | null;cloningId: string | null;@@ -43,7 +48,8 @@ interface SortablePresetRowProps extends PresetRowActions {function SortablePresetRow({preset,draggable,- readOnly,+ canEdit,+ canClone,editingId,deletingId,cloningId,@@ -62,6 +68,7 @@ function SortablePresetRow({isDragging,} = useSortable({ id: preset.id, disabled: !draggable });const busy = deletingId === preset.id || cloningId === preset.id;+ const editable = canEdit(preset);return (<div@@ -108,27 +115,33 @@ function SortablePresetRow({)}</div></div>- {!readOnly && (+ {(canClone || editable) && (<>- <RowIconButton- icon={Copy}- label={t("common.copy")}- onClick={() => onClone(preset)}- disabled={busy}- />- <RowIconButton- icon={Pencil}- label={t("preset.edit")}- onClick={() => onEdit(preset)}- disabled={busy}- />- <RowIconButton- icon={Trash2}- tone="danger"- label={t("presetSheet.delete")}- onClick={() => onDelete(preset)}- disabled={busy}- />+ {canClone && (+ <RowIconButton+ icon={Copy}+ label={t("common.copy")}+ onClick={() => onClone(preset)}+ disabled={busy}+ />+ )}+ {editable && (+ <RowIconButton+ icon={Pencil}+ label={t("preset.edit")}+ onClick={() => onEdit(preset)}+ disabled={busy}+ />+ )}+ {editable && (+ <RowIconButton+ icon={Trash2}+ tone="danger"+ label={t("presetSheet.delete")}+ onClick={() => onDelete(preset)}+ disabled={busy}+ />+ )}</>)}</ListRow>@@ -159,7 +172,7 @@ function PresetSubgroup({...actions}: PresetSubgroupProps) {const ids = subgroupPresets.map((p) => p.id);- const draggable = !actions.readOnly && subgroupPresets.length > 1;+ const draggable = actions.canReorder && subgroupPresets.length > 1;const handleDragEnd = ({ active, over }: DragEndEvent) => {if (!over || active.id === over.id) return;diff --git a/components/preset-manage-sheet.tsx b/components/preset-manage-sheet.tsxindex 4dbe534..8bc5f8c 100644--- a/components/preset-manage-sheet.tsx+++ b/components/preset-manage-sheet.tsx@@ -41,7 +41,15 @@ export function PresetsPanel({const t = useTranslations();const permission = useCalendarPermission(calendarId);const desktop = useMediaQuery(DESKTOP_QUERY, false);- const isReadOnly = readOnly || !permission.canEdit;+ // Creating a new preset and reordering the shared list are calendar-wide;+ // editing/deleting an existing one depends on who created it (Own/Any).+ const canCreate = !readOnly && permission.can("createPreset");+ const canReorder = !readOnly && permission.can("manageAnyPresets");+ const canEditPreset = (preset: ShiftPreset) =>+ !readOnly && permission.canOwned("manageOwnPresets", "manageAnyPresets", preset.createdBy);+ // Banner-level "no preset capability at all" — individual actions still gate themselves.+ const isReadOnly =+ readOnly || (!permission.can("createPreset") && !permission.can("manageOwnPresets"));const { presets, loading, createPreset, updatePreset, deletePreset, reorderPresets } =usePresets(calendarId);@@ -60,7 +68,10 @@ export function PresetsPanel({// Holds the dropped order until the reorder request settles, so rows don't snap back.const [pendingOrder, setPendingOrder] = useState<string[] | null>(null);- const isDirty = !isReadOnly && !samePresetForm(formData, baseline);+ // The create-form is shown for a new preset; the same form area is reused+ // for editing, reachable only via an already-gated Edit button.+ const formVisible = editingPreset ? canEditPreset(editingPreset) : canCreate;+ const isDirty = formVisible && !samePresetForm(formData, baseline);const canSave = !isSaving && formData.title.trim() !== "" && (!editingPreset || isDirty);useReportDirty(isDirty, onDirtyChange);@@ -91,6 +102,7 @@ export function PresetsPanel({};const saveOrder = async (next: ShiftPreset[]) => {+ if (!canReorder) return;const ids = next.map((p) => p.id);setPendingOrder(ids);const success = await reorderPresets(ids.map((id, order) => ({ id, order })));@@ -115,7 +127,7 @@ export function PresetsPanel({};const clonePreset = async (preset: ShiftPreset) => {- if (isReadOnly || isSaving || cloningId) return;+ if (!canCreate || isSaving || cloningId) return;setCloningId(preset.id);try {const success = await createPreset({@@ -165,7 +177,9 @@ export function PresetsPanel({};const rowActions = {- readOnly: isReadOnly,+ canEdit: canEditPreset,+ canClone: canCreate,+ canReorder,editingId: editingPreset?.id ?? null,deletingId,cloningId,@@ -207,7 +221,7 @@ export function PresetsPanel({/>)}- {!isReadOnly && (+ {formVisible && (<PresetFormCardformId={formId}editing={!!editingPreset}@@ -222,7 +236,7 @@ export function PresetsPanel({)}</PanelBody>- {!isReadOnly && (+ {formVisible && (<PanelFooter><Buttontype="button"diff --git a/components/settings-dialog.tsx b/components/settings-dialog.tsxindex 25019c4..8748998 100644--- a/components/settings-dialog.tsx+++ b/components/settings-dialog.tsx@@ -23,7 +23,7 @@ import { CalendarViewPanel, ViewSettingsState } from "@/components/view-settingsimport { PresetsPanel } from "@/components/preset-manage-sheet";import { ExternalSyncPanel } from "@/components/external-sync-manage-sheet";import { SyncNotificationsPanel } from "@/components/sync-notification-dialog";-import { SharingPanel } from "@/components/calendar-share-management-sheet";+import { PermissionsPanel } from "@/components/calendar-permissions-panel";import { isUsableToken } from "@/components/calendar-token-list";import { useCalendars } from "@/hooks/useCalendars";import { useCalendarPermission } from "@/hooks/useCalendarPermission";@@ -39,7 +39,7 @@ export type SettingsSection =| "general"| "presets"| "external"- | "sharing"+ | "permissions"| "export"| "view"| "notifications";@@ -182,21 +182,25 @@ export function useCalendarSettings(calendarId: string | null) {const permission = useCalendarPermission(calendarId);const { isAuthEnabled } = useAuthFeatures();const { presets } = usePresets(calendarId ?? undefined);+ const canOpenExternal = permission.can("manageExternalSync");const { externalSyncs, hasSyncErrors } = useExternalSync(- permission.canManage ? calendarId : null+ canOpenExternal ? calendarId : null);- const { tokens } = useCalendarTokens(permission.canShare ? calendarId : null);+ const canOpenPermissions =+ permission.can("manageShares") || permission.can("manageGuestAccess");+ const { tokens } = useCalendarTokens(canOpenPermissions ? calendarId : null);const items: SettingsItem[] = [];if (!calendar) return { calendar, items };- if (permission.canManage)+ if (permission.can("manageCalendarSettings"))items.push({id: "general",icon: Palette,title: t("settings.general"),description: t("settings.generalHint"),});- if (permission.canEdit)+ // Matches PresetsPanel's own "no preset capability at all" gate.+ if (permission.can("createPreset") || permission.can("manageOwnPresets"))items.push({id: "presets",icon: Layers,@@ -204,7 +208,7 @@ export function useCalendarSettings(calendarId: string | null) {description: t("settings.presetsHint", { count: presets.length }),meta: presets.length,});- if (permission.canManage)+ if (canOpenExternal)items.push({id: "external",icon: RefreshCw,@@ -212,12 +216,14 @@ export function useCalendarSettings(calendarId: string | null) {description: t("settings.externalHint", { count: externalSyncs.length }),meta: externalSyncs.length,});- if (isAuthEnabled && permission.canShare)+ // S2: the panel is worth opening with either capability — it self-gates each+ // section (manageShares for people, manageGuestAccess for guest/links).+ if (isAuthEnabled && canOpenPermissions)items.push({- id: "sharing",+ id: "permissions",icon: Users,- title: t("settings.sharing"),- description: t("settings.sharingHint", { count: tokens.filter(isUsableToken).length }),+ title: t("settings.permissions"),+ description: t("settings.permissionsHint", { count: tokens.filter(isUsableToken).length }),});items.push({@@ -236,7 +242,7 @@ export function useCalendarSettings(calendarId: string | null) {);// Sync notifications manage external syncs, so they need the same permission// tier as that section — guests only ever get read/write, never manage.- if (permission.canManage)+ if (canOpenExternal)items.push({id: "notifications",icon: Bell,@@ -295,8 +301,8 @@ export function CalendarSettingsPanel({onDirtyChange={onDirtyChange}/>);- case "sharing":- return <SharingPanel calendarId={calendarId} onClose={onCancel} onDirtyChange={onDirtyChange} />;+ case "permissions":+ return <PermissionsPanel calendarId={calendarId} onClose={onCancel} onDirtyChange={onDirtyChange} />;case "export":return <ExportPanel calendarId={calendarId} onClose={onClose} />;case "view":diff --git a/components/shift-sheet.tsx b/components/shift-sheet.tsxindex b349471..1b61449 100644--- a/components/shift-sheet.tsx+++ b/components/shift-sheet.tsx@@ -68,7 +68,11 @@ export function ShiftSheet({const [isSaving, setIsSaving] = useState(false);// Determine if sheet should be in read-only mode- const isReadOnly = readOnly || !permission.canEdit;+ const isReadOnly =+ readOnly ||+ (shift+ ? !permission.canOwned("editOwnShift", "editAnyShift", shift.createdBy ?? null)+ : !permission.can("createShift"));const {formData,diff --git a/components/shift-signup-list.tsx b/components/shift-signup-list.tsxindex 77bfa80..81eabe9 100644--- a/components/shift-signup-list.tsx+++ b/components/shift-signup-list.tsx@@ -13,7 +13,7 @@ import {SelectValue,} from "@/components/ui/select";import { Field, inputClass, Pill, RowIconButton, SectionLabel } from "@/components/form-kit";-import { PersonRow } from "@/components/calendar-share-list";+import { PersonRow } from "@/components/person-row";import { useAuth } from "@/hooks/useAuth";import {useShiftSignupPermission,diff --git a/components/shift-stats.tsx b/components/shift-stats.tsxindex 5b8e8df..ee9e88a 100644--- a/components/shift-stats.tsx+++ b/components/shift-stats.tsx@@ -3,7 +3,7 @@import { useState, useMemo } from "react";import { useLocale, useTranslations } from "next-intl";import { useTheme } from "next-themes";-import { Loader2 } from "lucide-react";+import { Loader2, Lock } from "lucide-react";import { useShiftStats } from "@/hooks/useShiftStats";import { useShifts } from "@/hooks/useShifts";import { usePresets } from "@/hooks/usePresets";@@ -117,7 +117,7 @@ export function ShiftStats({ calendarId, currentDate }: ShiftStatsProps) {const [viewMode, setViewMode] = useState<ViewMode>("overview");const outerRadius = useMediaQuery("(min-width: 640px)", true) ? 120 : 80;- const { stats, loading } = useShiftStats({+ const { stats, loading, forbidden } = useShiftStats({calendarId,currentDate,period,@@ -188,6 +188,15 @@ export function ShiftStats({ calendarId, currentDate }: ShiftStatsProps) {if (!calendarId) return null;+ if (forbidden) {+ return (+ <div className="flex flex-col items-center gap-2 py-12 text-center">+ <Lock className="size-6 text-fg-tertiary" />+ <p className="text-[13px] text-fg-tertiary">{t("stats.noPermission")}</p>+ </div>+ );+ }+const colorFor = (title: string) => colorByTitle.get(title) ?? "var(--chart-1)";const totalShifts = stats?.totalShifts || 0;const totalMinutes = stats?.totalMinutes || 0;diff --git a/components/shifts-overview-dialog.tsx b/components/shifts-overview-dialog.tsxindex 106e09e..3c6a45b 100644--- a/components/shifts-overview-dialog.tsx+++ b/components/shifts-overview-dialog.tsx@@ -14,8 +14,10 @@ interface ShiftsOverviewDialogProps {shifts: ShiftWithCalendar[];onDeleteShift?: (shiftId: string) => void;onEditShift?: (shift: ShiftWithCalendar) => void;- /** Viewer's edit permission on the calendar the shifts belong to */- canEdit: boolean;+ /** Per-shift own/any precision (editOwnShift/editAnyShift) for the calendar the shifts belong to */+ canEditShift: (shift: ShiftWithCalendar) => boolean;+ /** Per-shift own/any precision (deleteOwnShift/deleteAnyShift) — independent from canEditShift */+ canDeleteShift: (shift: ShiftWithCalendar) => boolean;}export function ShiftsOverviewDialog({@@ -25,7 +27,8 @@ export function ShiftsOverviewDialog({shifts,onDeleteShift,onEditShift,- canEdit,+ canEditShift,+ canDeleteShift,}: ShiftsOverviewDialogProps) {const t = useTranslations();const locale = useLocale();@@ -56,7 +59,8 @@ export function ShiftsOverviewDialog({<ShiftDetailRowkey={shift.id}shift={shift}- canEdit={canEdit && !!onEditShift && !!onDeleteShift}+ canEdit={canEditShift(shift) && !!onEditShift}+ canDelete={canDeleteShift(shift) && !!onDeleteShift}actions="menu"onEdit={(s) => {onOpenChange(false);diff --git a/components/view-settings-sheet.tsx b/components/view-settings-sheet.tsxindex 7830f4b..78c3c37 100644--- a/components/view-settings-sheet.tsx+++ b/components/view-settings-sheet.tsx@@ -305,7 +305,10 @@ function CalendarViewPanelBody({const t = useTranslations();const id = useId();const { calendars, updateCalendar } = useCalendars();- const { canManage } = useCalendarPermission(calendarId);+ // Calendar-wide view settings are calendar-settings territory, not an editAnyShift+ // approximation — narrower than the old canEdit/canManage coarse checks (see Paket 5b report).+ const { can } = useCalendarPermission(calendarId);+ const canManage = can("manageCalendarSettings");const calendar = calendars.find((c) => c.id === calendarId);const saved = calendar?.viewSettings ? sanitizeCalendarViewSettings(calendar.viewSettings) : null;const personalFields = sanitizeCalendarViewSettings(personal);diff --git a/docs/ADMIN_PANEL.md b/docs/ADMIN_PANEL.mdindex 4f8857b..191c64b 100644--- a/docs/ADMIN_PANEL.md+++ b/docs/ADMIN_PANEL.md@@ -164,7 +164,7 @@ Displays all calendars in the system with:- Calendar name and color indicator- Owner information (or "Orphaned" badge)- Statistics (shifts, notes, presets, shares)-- Guest permission setting+- Guest access bundle- Action menu### Orphaned Calendars@@ -182,7 +182,7 @@ Orphaned calendars are invisible to regular users and can only be managed throug| Action | Admin | Superadmin | Description || ------------------ | ----- | ---------- | ------------------------------------ || View Details | Yes | Yes | View calendar info and statistics |-| Edit Calendar | Yes | Yes | Change name, color, guest permission |+| Edit Calendar | Yes | Yes | Change name, color, guest access bundle || Transfer Ownership | Yes | Yes | Assign calendar to a different user || Delete Calendar | No | Yes | Permanently delete calendar |diff --git a/docs/PERMISSIONS.md b/docs/PERMISSIONS.mdindex 814be9f..be2eefb 100644--- a/docs/PERMISSIONS.md+++ b/docs/PERMISSIONS.md@@ -4,32 +4,100 @@ This guide explains how calendar permissions work in BetterShift, including shar## Table of Contents-1. [Permission Hierarchy](#permission-hierarchy)+1. [Permission Bundles](#permission-bundles)2. [Calendar Ownership](#calendar-ownership)3. [Sharing Calendars](#sharing-calendars)4. [Access Tokens (Share Links)](#access-tokens-share-links)5. [Guest Access](#guest-access)6. [Calendar Discovery](#calendar-discovery)+7. [Permission Resolution](#permission-resolution)+8. [Best Practices](#best-practices)----## Permission Hierarchy+## Permission Bundles-BetterShift uses a four-level permission hierarchy for calendars:+BetterShift doesn't use a fixed access ladder. Instead, each calendar owner defines named **permission bundles** — groups of individual capabilities — and assigns a bundle to each person, to guest access, and to each share link. What "editing" or "viewing" means on a calendar is entirely up to the owner: a bundle can allow "only stamp existing presets", "create and edit shifts but never touch anyone else's", or any other combination.-| Level | Can View | Can Edit | Can Share | Can Delete |-| --------- | -------- | -------- | --------- | ---------- |-| **owner** | Yes | Yes | Yes | Yes |-| **admin** | Yes | Yes | Yes | No |-| **write** | Yes | Yes | No | No |-| **read** | Yes | No | No | No |+### Starter bundles-### Permission Details+Every calendar is created with four bundles: **Read**, **Contribute**, **Manage**, and **Admin**. Their names are shown translated into your interface language until one is renamed — after a rename, the custom name is used everywhere instead. From the "Groups" tab in a calendar's Permissions settings, an owner can rename, clone, edit the capabilities of, or delete any bundle. A bundle currently assigned to a person, a link, or guest access can't be deleted — the delete action lists what's still using it so you can reassign first.-- **owner**: Full control over the calendar, including deletion-- **admin**: Can manage calendar settings and share with others, but cannot delete-- **write**: Can create, edit, and delete shifts, notes, and presets-- **read**: View-only access to all calendar data+Recommended defaults for a newly created calendar:++| Bundle | Grants |+| --- | --- |+| **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 |++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.++### Capability catalog++The bundle editor groups capabilities by area:++**Viewing**+- View shifts — see the calendar and its shifts+- View notes & events — see notes and events on the calendar+- View statistics — see the statistics/summary panel++**Shifts**+- Stamp presets — add a shift by picking an existing preset+- Create shifts — create new shifts freely, not limited to a preset+- Edit own shifts / Edit any shift — change shifts you created vs. any shift regardless of who created it+- Delete own shifts / Delete any shift — remove shifts you created vs. any shift++**Notes & events**+- Manage own notes & events / Manage any notes & events — create, edit, or delete notes and events you created vs. anyone's (creating a new one only needs one of the two)++**Signups**+- Sign up self — join or leave shifts that have open slots+- Sign up others — add or remove other people from a shift's signups; this also lets you see the calendar's members (owner + shares), since that list is how you pick who to add++**Presets**+- Create presets — add new presets+- Manage own presets / Manage any presets — edit or delete presets you created vs. anyone's; reordering the calendar's shared preset list specifically needs "manage any presets", since it changes the order for everyone regardless of who created which preset++**External sync**+- Manage external sync — set up, edit, and remove external calendar subscriptions+- Delete sync logs — remove entries from the sync log++**Administrative**+- 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++### Editing your own vs. anyone's entries++For shifts, presets, and notes/events, a bundle can separately grant editing/deleting entries you created and editing/deleting anyone's. This is what lets an owner allow contributors to manage their own work without touching other people's.++One rule to keep in mind: an entry with no known creator — imported legacy data, an entry whose creator account was later deleted, or one added by an anonymous guest — counts as "your own" for **anyone** holding the matching own-capability, not just for the calendar owner. If you rely on the own/any split to keep contributors from editing each other's entries, be aware that creator-less entries are fair game for everyone with the "own" capability.++### 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:++- Manage shares+- Manage guest access+- Manage calendar settings+- Manage external sync+- Delete sync logs++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.++### 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.++### Who can assign or edit bundles++Assigning a bundle to a person needs **manage shares**. Assigning a bundle to guest access or to a link needs **manage guest access**. Editing what a bundle actually contains — its ticked capabilities, its name — needs either of those two capabilities as well: anyone who can assign a bundle can just as easily edit a bundle's contents directly, so this isn't a wider grant than manage shares/manage guest access already imply. Both are subject to the same cap: a non-owner can only create or assign a bundle whose capabilities are a subset of their own current access (see [Managing Shares](#managing-shares)).++### Signups++The "sign up self" and "sign up others" capabilities let people join/leave shifts (for themselves or for others) through a bundle — except an anonymous visitor with no account or session, who can never sign up for someone else's shift regardless of what a bundle says. Signups as a whole are additionally gated by a separate calendar-wide "Signups enabled" switch, next to the signup capabilities in the same Permissions settings, independent of any bundle.---@@ -44,8 +112,9 @@ BetterShift uses a four-level permission hierarchy for calendars:### Owner Capabilities- Full control over calendar settings-- Grant/revoke access to other users-- Set guest permission level+- Every capability, regardless of bundles — an owner is never gated by the bundle system+- Create, edit, and delete permission bundles+- Assign bundles to people, guest access, and links- Create/manage access tokens- Delete the calendar permanently@@ -55,53 +124,48 @@ BetterShift uses a four-level permission hierarchy for calendars:### Share with Specific Users-Owners and admins can share calendars with other registered users:+Anyone with the **manage shares** capability (owners always have it) can share a calendar with other registered users:-1. Open the calendar settings-2. Go to the "Sharing" section, "People" tab-3. Search for users by name or email-4. Select permission level (admin, write, or read)+1. Open the calendar's Permissions settings+2. Go to the "Assignments" tab, "People" section+3. Search for a user by name or email+4. Pick a bundle from the bundle picker5. Click "Invite"### Managing Shares-From calendar settings, you can:--- View all users with access-- Change permission levels-- Remove access for specific users+From the same tab, you can:-### Share Permissions+- View everyone with access and which bundle they hold+- Change a person's bundle at any time+- Remove access for a specific person-| Sharer's Role | Can Share With | Max Permission |-| ------------- | -------------- | -------------- |-| owner | Anyone | admin |-| admin | Anyone | admin |-| write | Cannot share | - |-| read | Cannot share | - |+Anyone with manage shares can assign any bundle to anyone they could already grant themselves. The calendar owner can assign any bundle, including Admin. A non-owner is capped to bundles whose capabilities are a subset of their own current access — someone who only holds a narrow custom bundle plus manage shares cannot hand out Admin, even to themselves.---## Access Tokens (Share Links)-Access tokens provide a way to share calendars via a URL. With Guest Access enabled globally (admin panel → System Settings) the recipient needs no account; otherwise they sign in first and the token applies afterwards.+Access tokens provide a way to share calendars via a URL. With Guest Access enabled globally (admin panel → System Settings) the recipient needs no account; otherwise they sign in first and the link's bundle applies afterwards.### Creating Access Tokens-1. Open calendar settings-2. Go to the "Sharing" section, "Links" tab+1. Open the calendar's Permissions settings+2. Go to the "Assignments" tab, "Links" section3. Configure:- **Name**: Description for your reference- - **Permission**: read or write+ - **Bundle**: Which guest-eligible permission bundle the link grants- **Expiration**: Optional expiry date4. Click "Create link" and copy it; the token is shown only once+Only bundles that don't contain any of the guest-locked capabilities (see [Permission Bundles](#capabilities-that-can-never-reach-a-guest-or-a-link)) appear in the picker.+### Token Properties| Property | Description || ----------- | ------------------------------------------------- || Name | Identifier for the token (e.g., "Team View Link") |-| Permission | `read` or `write` access level |+| Bundle | Which guest-eligible permission bundle the link grants || Expiration | Optional date when token becomes invalid || Active | Can be disabled without deletion || Usage Count | Number of times the token was used |@@ -123,50 +187,46 @@ Access tokens provide a way to share calendars via a URL. With Guest Access enab### Token vs. User Sharing-| Aspect | Access Token | User Sharing |-| ------------------------ | --------------------------- | ------------------ |-| Requires account | Only if guest access is off | Yes |-| Trackable per-user | No | Yes |-| Revocable per-person | No (revoke token) | Yes |-| Can set admin permission | No | Yes |-| Best for | Public/temporary access | Team collaboration |+| Aspect | Access Token | User Sharing |+| ------------------------------------ | --------------------------- | ------------------- |+| Requires account | Only if guest access is off | Yes |+| Trackable per-user | No | Yes |+| Revocable per-person | No (revoke token) | Yes |+| Can hold administrative capabilities | No, ever | Yes |+| Best for | Public/temporary access | Team collaboration |---## Guest Access-Guest access allows unauthenticated users to view or edit calendars without any token or account.+Guest access allows unauthenticated users to view or edit calendars without any token or account, using whichever permission bundle the calendar has assigned to it.### Configuration1. Enable globally: Turn on Guest Access in the admin panel under System Settings-2. Enable per-calendar: Set public access in calendar settings, "Sharing" section, "Public" tab+2. Assign per-calendar: In the calendar's Permissions settings, "Assignments" tab, pick a bundle under "Public access" (or "No access" to disable it for this calendar)-The per-calendar level applies to visitors without an account only while Guest Access is enabled globally; otherwise they are sent to the login page. Signed-in users get it through [Calendar Discovery](#calendar-discovery), whatever the setting says. Access links work even with public access set to `none`, but with Guest Access disabled a recipient without a session is sent to the login page first; the link's grant applies once they sign in.+The per-calendar bundle applies to visitors without an account only while Guest Access is enabled globally; otherwise they are sent to the login page. Signed-in users get it through [Calendar Discovery](#calendar-discovery), whatever the setting says. Access links work even when public access is set to "No access", but with Guest Access disabled a recipient without a session is sent to the login page first; the link's bundle applies once they sign in.-### Guest Permission Levels+### Guest Access Bundles-| Setting | Description |-| --------- | -------------------------------------- |-| **none** | No guest access (default) |-| **read** | Guests can view calendar data |-| **write** | Guests can view and edit calendar data |+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.### Guest vs. Token Access-| Aspect | Guest Access | Token Access |-| --------- | ----------------------- | ----------------------- |-| URL | Standard calendar URL | Special token URL |-| Scope | Per-calendar setting | Per-token setting |-| Tracking | No tracking | Usage count, last used |-| Revocable | Change calendar setting | Delete/disable token |-| Security | Public to everyone | Limited to link holders |+| Aspect | Guest Access | Token Access |+| --------- | ------------------------ | ------------------------- |+| URL | Standard calendar URL | Special token URL |+| Scope | Per-calendar setting | Per-token setting |+| Tracking | No tracking | Usage count, last used |+| Revocable | Change calendar setting | Delete/disable token |+| Security | Public to everyone | Limited to link holders |---## Calendar Discovery-Signed-in users can discover and subscribe to any calendar whose public access is `read` or `write`. This does not depend on the global Guest Access setting, which only governs visitors without an account.+Signed-in users can discover and subscribe to any calendar that has a guest access bundle assigned (i.e., public access is not set to "No access"). This does not depend on the global Guest Access setting, which only governs visitors without an account.### Finding Public Calendars@@ -183,35 +243,34 @@ Signed-in users can discover and subscribe to any calendar whose public access i### Subscription vs. Sharing-| Aspect | Subscription | Sharing |-| ----------------- | --------------------------- | ------------------------- |-| Permission source | Calendar's guest permission | Explicit share permission |-| Initiated by | User subscribing | Owner/admin sharing |-| Can be dismissed | Yes | Yes |-| Permission level | As set on calendar | As granted when sharing |+| Aspect | Subscription | Sharing |+| ---------------------- | ------------------------------ | --------------------------- |+| Bundle source | Calendar's guest access bundle | Bundle chosen when sharing |+| Initiated by | User subscribing | Owner/manage-shares holder |+| Can be dismissed | Yes | Yes |+| Effective capabilities | As set by the guest access bundle | As granted when sharing |---## Permission Resolution-When a user accesses a calendar, BetterShift resolves permissions in this order:+When a user accesses a calendar, BetterShift resolves their capabilities in this order:-1. **Owner check**: Is user the calendar owner? → `owner`-2. **Share check**: Is user explicitly shared? → Use share permission-3. **Token check**: Valid access token in cookie? → Use token permission-4. **Subscription check**: Is user subscribed to public calendar? → Use guest permission-5. **Guest check**: Guest access enabled + calendar allows guests? → Use guest permission-6. **No access**: None of the above → Access denied+1. **Owner check**: Is the user the calendar owner? → full access, no bundle involved.+2. **Share check**: Is the user explicitly shared with? → that share's bundle.+3. **Token check**: Valid access token in the request's cookie? → that link's bundle.+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 permission level.+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.---## Best Practices-1. **Use appropriate permission levels**: Grant minimum required access+1. **Grant the minimum bundle needed**: Start from Read or Contribute rather than handing out Manage or Admin by default2. **Prefer user sharing over tokens**: Better tracking and individual revocation3. **Set token expiration**: Don't leave tokens valid indefinitely-4. **Review shares periodically**: Remove access that's no longer needed-5. **Use read permission by default**: Only grant write when editing is required+4. **Review shares and bundle assignments periodically**: Remove access that's no longer needed+5. **Split own/any capabilities deliberately**: If you want contributors to only touch their own entries, don't also tick the matching "any" capability6. **Consider public access carefully**: Public calendars are open to every signed-in user, and to everyone when Guest Access is enabled globallydiff --git a/docs/UPGRADING.md b/docs/UPGRADING.mdindex 1cb512a..680b1a9 100644--- a/docs/UPGRADING.md+++ b/docs/UPGRADING.md@@ -25,10 +25,81 @@ Breaking changes between BetterShift releases and the steps to get through them.## Versions+- [3.1.0](#310-from-300) — from `3.0.0`- [3.0.0](#300-from-22x) — from `2.2.x`---+## 3.1.0 (from 3.0.0)++BetterShift 3.1.0 replaces the fixed calendar read/write/admin permission ladder with per-calendar **permission bundles** — an owner defines named bundles by ticking individual capabilities instead of the app hard-coding what "write" means. See the [Permissions and Sharing Guide](PERMISSIONS.md) for the full picture. The upgrade itself needs no configuration changes; there's a single deliberate behavior change to be aware of, described below.++### Before You Start (3.1.0)++**Prerequisites**++- A BetterShift instance running `3.0.0`+- Database backup (recommended) — this migration rewrites the permission tables and is not cleanly reversible in place++```bash+# SQLite database location (default)+cp ./data/sqlite.db ./data/sqlite.db.backup++# Or if using Docker+docker cp bettershift:/app/data/sqlite.db ./sqlite.db.backup+```++The migration replaces the old `read`/`write`/`admin` enum columns on shares, tokens, and calendars with permission bundle rows, mapping every existing calendar's shares, links, and guest access onto equivalent bundles — see [Breaking Changes](#breaking-changes-310) for the one place where "equivalent" isn't identical.++### Breaking Changes (3.1.0)++#### 1. Guest and link access can no longer manage external sync++This is the one deliberate behavior change for existing calendars. The old `write` tier is split into two new bundles: **Contribute** (create shifts/presets, edit your own entries — no external sync) and **Manage** (adds editing anyone's entries, still no external sync). The migration maps a calendar's `write` guest access or share links onto Contribute, and — specifically for guest/link access, not for invited users — strips `manageExternalSync` and `deleteSyncLogs` out of what it grants, even though those capabilities were part of the old `write` tier. A user invited directly (`calendarShares`, not guest/link) keeps exactly their previous capabilities, external sync management included; only guest and link access lose it.++This isn't an incidental migration side effect — external sync configuration touches credentials and arbitrary URLs, and guest/link access is now hard-locked out of it at the enforcement layer, not just by the migrated defaults. No bundle assigned to guest access or a link can ever hold `manageExternalSync`/`deleteSyncLogs`, regardless of what an owner ticks into it afterwards.++| Your setup | Action |+| --- | --- |+| No calendar ever had guest access or a share link set to `write` | No action |+| A calendar's guest access or a share link was `write`, and you relied on that to manage external sync | Re-check your sync setup after upgrading — see [FAQ](#faq-310) |++#### 2. Everything else keeps its prior effective permissions++Every existing calendar's owner, shares (`read`/`write`/`admin`), and guest/link access (`none`/`read`/`write`) are mapped 1:1 onto the new bundle system — nobody gains or loses access as part of this upgrade, aside from the external-sync change above. The improved defaults introduced alongside bundles (for example, the Read bundle now granting self-signup out of the box) only apply to calendars created after upgrading, not retroactively to existing ones.++### Upgrade Steps (3.1.0)++1. **Back up your database** (see [Before You Start](#before-you-start-310)).+2. **Pull the new image** (`ghcr.io/pantelx/bettershift:latest` or `:3.1.0`).+3. **Restart the container** (or `npm run build && npm run db:migrate && npm start` from source). The migration runs automatically on container start.+4. **If any calendar's guest access or a share link was previously `write`**: open that calendar's Permissions settings and confirm whether external sync management is still needed there — see [Breaking Change 1](#1-guest-and-link-access-can-no-longer-manage-external-sync).++### FAQ (3.1.0)++**Do I need to change anything in `.env` for this release?**++No. This release has no new environment variables and no required configuration change — the migration runs automatically, and the one behavior change above is informational rather than an action every instance needs to take.++**A guest or a link used to manage my external calendar sync. What do I do now?**++Guest and link access can no longer hold that capability, by design — it touches sync credentials and URLs. Invite the person who needs to manage sync as a regular shared user instead, and assign them a bundle that includes "Manage external sync" (the built-in Admin bundle already does). See [Sharing Calendars](PERMISSIONS.md#sharing-calendars).++**Will my existing shares, links, and guest access still work the same after upgrading?**++Yes, with the one exception above. Every prior `read`/`write`/`admin` share, and every guest/link `read`/`write` setting, maps to an equivalent bundle with the same effective capabilities.++**Do the new default bundles (e.g. self-signup on Read) apply to my existing calendars?**++No. They only apply to calendars created after the upgrade. Existing calendars keep their migrated bundles, which you can still edit like any other bundle.++### Rollback (3.1.0)++1. Re-deploy the `v3.0.0` image tag (or your previous version).+2. Restore the `sqlite.db` backup taken in [Before You Start](#before-you-start-310) — this migration drops the old permission enum columns in place, so an older version cannot read the new bundle tables and a plain image downgrade is not enough on its own.++---+## 3.0.0 (from 2.2.x)BetterShift 3.0.0 is the redesign release — a new visual design across the calendar, admin panel and sign-in flow — bundled with a handful of infrastructure changes that need action from every self-hosted instance coming from `2.2.x`.diff --git a/drizzle/0019_add_permission_bundles_additive.sql b/drizzle/0019_add_permission_bundles_additive.sqlnew file mode 100644index 0000000..c6df4d7--- /dev/null+++ b/drizzle/0019_add_permission_bundles_additive.sql@@ -0,0 +1,14 @@+CREATE TABLE `calendar_permission_bundles` (+ `id` text PRIMARY KEY NOT NULL,+ `calendar_id` text NOT NULL,+ `name` text NOT NULL,+ `capabilities` text NOT NULL,+ `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+);+--> statement-breakpoint+CREATE INDEX `calendar_permission_bundles_calendarId_idx` ON `calendar_permission_bundles` (`calendar_id`);--> statement-breakpoint+ALTER TABLE `calendar_access_tokens` ADD `bundle_id` text REFERENCES calendar_permission_bundles(id);--> statement-breakpoint+ALTER TABLE `calendar_shares` ADD `bundle_id` text REFERENCES calendar_permission_bundles(id);--> statement-breakpoint+ALTER TABLE `calendars` ADD `guest_bundle_id` text;\ No newline at end of filediff --git a/drizzle/0020_backfill_permission_bundles.sql b/drizzle/0020_backfill_permission_bundles.sqlnew file mode 100644index 0000000..21c1eda--- /dev/null+++ b/drizzle/0020_backfill_permission_bundles.sql@@ -0,0 +1,117 @@+-- Backfill capability bundles for every existing calendar, preserving+-- today's effective owner/admin/write/read behavior 1:1 — see+-- .LOCAL/calendar-permission-bundles-plan.md ("Bundle lifecycle &+-- migration"). The capability lists below are a frozen snapshot of that+-- design at migration time (intentionally duplicated rather than generated+-- from lib/permission-bundles.ts, since a later change to that file must+-- not rewrite what already-applied migrations did).++-- FK enforcement (PRAGMA foreign_keys) has never actually been turned on+-- by the app, so a pre-existing install could have accumulated shares or+-- tokens whose calendar_id no longer matches any row in `calendars`. The+-- UPDATE statements below would leave bundle_id NULL for such orphans,+-- which then fails the NOT NULL rebuild in the next migration — drop them+-- first so the upgrade can't be blocked by stale, already-meaningless rows.+DELETE FROM calendar_shares WHERE calendar_id NOT IN (SELECT id FROM calendars);+--> statement-breakpoint+DELETE FROM calendar_access_tokens WHERE calendar_id NOT IN (SELECT id FROM calendars);+--> statement-breakpoint++-- Read: view-only, plus self-signup if this calendar currently allows it.+INSERT INTO calendar_permission_bundles (id, calendar_id, name, capabilities, created_at, updated_at)+SELECT+ lower(hex(randomblob(16))),+ id,+ 'Read',+ CASE WHEN allow_self_signup THEN+ json_array('viewShifts','viewNotesEvents','viewStats','signUpSelf')+ ELSE+ json_array('viewShifts','viewNotesEvents','viewStats')+ END,+ CURRENT_TIMESTAMP,+ CURRENT_TIMESTAMP+FROM calendars;+--> statement-breakpoint++-- Contribute: everything today's "write" permission actually grants+-- (presets, shift editing, external sync config and sync-log deletion all+-- included, since that's what write means today).+INSERT INTO calendar_permission_bundles (id, calendar_id, name, capabilities, created_at, updated_at)+SELECT+ lower(hex(randomblob(16))),+ id,+ 'Contribute',+ json_array('viewShifts','viewNotesEvents','viewStats','stampPreset','createShift','deleteShift','createPreset','editShift','manageNotesEvents','managePresets','manageExternalSync','deleteSyncLogs','viewMembers','signUpSelf','signUpOthers'),+ CURRENT_TIMESTAMP,+ CURRENT_TIMESTAMP+FROM calendars;+--> statement-breakpoint++-- Manage: nothing in today's ladder maps to it (no such tier exists yet) —+-- seeded with the same content as Contribute so it's immediately usable+-- without affecting any already-assigned share, token or guest link.+INSERT INTO calendar_permission_bundles (id, calendar_id, name, capabilities, created_at, updated_at)+SELECT+ lower(hex(randomblob(16))),+ id,+ 'Manage',+ json_array('viewShifts','viewNotesEvents','viewStats','stampPreset','createShift','deleteShift','createPreset','editShift','manageNotesEvents','managePresets','manageExternalSync','deleteSyncLogs','viewMembers','signUpSelf','signUpOthers'),+ CURRENT_TIMESTAMP,+ CURRENT_TIMESTAMP+FROM calendars;+--> statement-breakpoint++-- Admin: everything today's "admin" permission grants (superset of write).+INSERT INTO calendar_permission_bundles (id, calendar_id, name, capabilities, created_at, updated_at)+SELECT+ lower(hex(randomblob(16))),+ id,+ 'Admin',+ json_array('viewShifts','viewNotesEvents','viewStats','stampPreset','createShift','deleteShift','createPreset','editShift','manageNotesEvents','managePresets','manageExternalSync','deleteSyncLogs','viewMembers','signUpSelf','signUpOthers','manageShares','manageGuestAccess','manageCalendarSettings'),+ CURRENT_TIMESTAMP,+ CURRENT_TIMESTAMP+FROM calendars;+--> statement-breakpoint++-- Point every existing share at its calendar's matching generated bundle.+-- 'owner' is a legacy value some pre-existing rows may still carry (see the+-- historical cast in app/api/calendars/[id]/shares/[shareId]/route.ts) —+-- it graned full owner-equivalent access under the old hierarchy, so it+-- maps to Admin, the highest tier a share can hold.+UPDATE calendar_shares+SET bundle_id = (+ SELECT b.id FROM calendar_permission_bundles b+ WHERE b.calendar_id = calendar_shares.calendar_id+ AND b.name = CASE calendar_shares.permission+ WHEN 'owner' THEN 'Admin'+ WHEN 'admin' THEN 'Admin'+ WHEN 'write' THEN 'Contribute'+ ELSE 'Read'+ END+);+--> statement-breakpoint++-- Point every existing access token at its calendar's matching generated bundle.+UPDATE calendar_access_tokens+SET bundle_id = (+ SELECT b.id FROM calendar_permission_bundles b+ WHERE b.calendar_id = calendar_access_tokens.calendar_id+ AND b.name = CASE calendar_access_tokens.permission+ WHEN 'write' THEN 'Contribute'+ ELSE 'Read'+ END+);+--> statement-breakpoint++-- Point every calendar with a public guest permission at its matching+-- bundle; calendars with guest_permission = 'none' keep guest_bundle_id NULL.+UPDATE calendars+SET guest_bundle_id = (+ SELECT b.id FROM calendar_permission_bundles b+ WHERE b.calendar_id = calendars.id+ AND b.name = CASE calendars.guest_permission+ WHEN 'write' THEN 'Contribute'+ ELSE 'Read'+ END+)+WHERE calendars.guest_permission != 'none';diff --git a/drizzle/0021_drop_legacy_permission_columns.sql b/drizzle/0021_drop_legacy_permission_columns.sqlnew file mode 100644index 0000000..1fd6788--- /dev/null+++ b/drizzle/0021_drop_legacy_permission_columns.sql@@ -0,0 +1,46 @@+PRAGMA foreign_keys=OFF;--> statement-breakpoint+CREATE TABLE `__new_calendar_access_tokens` (+ `id` text PRIMARY KEY NOT NULL,+ `calendar_id` text NOT NULL,+ `token` text NOT NULL,+ `name` text,+ `bundle_id` text NOT NULL,+ `expires_at` integer,+ `created_by` text NOT NULL,+ `created_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,+ `last_used_at` integer,+ `usage_count` integer DEFAULT 0 NOT NULL,+ `is_active` integer DEFAULT true NOT NULL,+ FOREIGN KEY (`calendar_id`) REFERENCES `calendars`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`bundle_id`) REFERENCES `calendar_permission_bundles`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`created_by`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+INSERT INTO `__new_calendar_access_tokens`("id", "calendar_id", "token", "name", "bundle_id", "expires_at", "created_by", "created_at", "last_used_at", "usage_count", "is_active") SELECT "id", "calendar_id", "token", "name", "bundle_id", "expires_at", "created_by", "created_at", "last_used_at", "usage_count", "is_active" FROM `calendar_access_tokens`;--> statement-breakpoint+DROP TABLE `calendar_access_tokens`;--> statement-breakpoint+ALTER TABLE `__new_calendar_access_tokens` RENAME TO `calendar_access_tokens`;--> statement-breakpoint+PRAGMA foreign_keys=ON;--> statement-breakpoint+CREATE UNIQUE INDEX `calendar_access_tokens_token_unique` ON `calendar_access_tokens` (`token`);--> statement-breakpoint+CREATE INDEX `calendar_access_tokens_token_idx` ON `calendar_access_tokens` (`token`);--> statement-breakpoint+CREATE INDEX `calendar_access_tokens_calendarId_isActive_idx` ON `calendar_access_tokens` (`calendar_id`,`is_active`);--> statement-breakpoint+CREATE INDEX `calendar_access_tokens_createdBy_idx` ON `calendar_access_tokens` (`created_by`);--> statement-breakpoint+CREATE TABLE `__new_calendar_shares` (+ `id` text PRIMARY KEY NOT NULL,+ `calendar_id` text NOT NULL,+ `user_id` text NOT NULL,+ `bundle_id` text NOT NULL,+ `shared_by` text NOT NULL,+ `created_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,+ FOREIGN KEY (`calendar_id`) REFERENCES `calendars`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`bundle_id`) REFERENCES `calendar_permission_bundles`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`shared_by`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+INSERT INTO `__new_calendar_shares`("id", "calendar_id", "user_id", "bundle_id", "shared_by", "created_at") SELECT "id", "calendar_id", "user_id", "bundle_id", "shared_by", "created_at" FROM `calendar_shares`;--> statement-breakpoint+DROP TABLE `calendar_shares`;--> statement-breakpoint+ALTER TABLE `__new_calendar_shares` RENAME TO `calendar_shares`;--> statement-breakpoint+CREATE INDEX `calendar_shares_calendarId_idx` ON `calendar_shares` (`calendar_id`);--> statement-breakpoint+CREATE INDEX `calendar_shares_userId_idx` ON `calendar_shares` (`user_id`);--> statement-breakpoint+ALTER TABLE `calendars` DROP COLUMN `guest_permission`;--> statement-breakpoint+ALTER TABLE `calendars` DROP COLUMN `allow_self_signup`;\ No newline at end of filediff --git a/drizzle/0022_quick_felicia_hardy.sql b/drizzle/0022_quick_felicia_hardy.sqlnew file mode 100644index 0000000..693c518--- /dev/null+++ b/drizzle/0022_quick_felicia_hardy.sql@@ -0,0 +1,48 @@+PRAGMA foreign_keys=OFF;--> statement-breakpoint+CREATE TABLE `__new_calendar_access_tokens` (+ `id` text PRIMARY KEY NOT NULL,+ `calendar_id` text NOT NULL,+ `token` text NOT NULL,+ `name` text,+ `bundle_id` text NOT NULL,+ `expires_at` integer,+ `created_by` text NOT NULL,+ `created_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,+ `last_used_at` integer,+ `usage_count` integer DEFAULT 0 NOT NULL,+ `is_active` integer DEFAULT true NOT NULL,+ FOREIGN KEY (`calendar_id`) REFERENCES `calendars`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`bundle_id`) REFERENCES `calendar_permission_bundles`(`id`) ON UPDATE no action ON DELETE restrict,+ FOREIGN KEY (`created_by`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+INSERT INTO `__new_calendar_access_tokens`("id", "calendar_id", "token", "name", "bundle_id", "expires_at", "created_by", "created_at", "last_used_at", "usage_count", "is_active") SELECT "id", "calendar_id", "token", "name", "bundle_id", "expires_at", "created_by", "created_at", "last_used_at", "usage_count", "is_active" FROM `calendar_access_tokens`;--> statement-breakpoint+DROP TABLE `calendar_access_tokens`;--> statement-breakpoint+ALTER TABLE `__new_calendar_access_tokens` RENAME TO `calendar_access_tokens`;--> statement-breakpoint+PRAGMA foreign_keys=ON;--> statement-breakpoint+CREATE UNIQUE INDEX `calendar_access_tokens_token_unique` ON `calendar_access_tokens` (`token`);--> statement-breakpoint+CREATE INDEX `calendar_access_tokens_token_idx` ON `calendar_access_tokens` (`token`);--> statement-breakpoint+CREATE INDEX `calendar_access_tokens_calendarId_isActive_idx` ON `calendar_access_tokens` (`calendar_id`,`is_active`);--> statement-breakpoint+CREATE INDEX `calendar_access_tokens_createdBy_idx` ON `calendar_access_tokens` (`created_by`);--> statement-breakpoint+CREATE TABLE `__new_calendar_shares` (+ `id` text PRIMARY KEY NOT NULL,+ `calendar_id` text NOT NULL,+ `user_id` text NOT NULL,+ `bundle_id` text NOT NULL,+ `shared_by` text NOT NULL,+ `created_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,+ FOREIGN KEY (`calendar_id`) REFERENCES `calendars`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`bundle_id`) REFERENCES `calendar_permission_bundles`(`id`) ON UPDATE no action ON DELETE restrict,+ FOREIGN KEY (`shared_by`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+INSERT INTO `__new_calendar_shares`("id", "calendar_id", "user_id", "bundle_id", "shared_by", "created_at") SELECT "id", "calendar_id", "user_id", "bundle_id", "shared_by", "created_at" FROM `calendar_shares`;--> statement-breakpoint+DROP TABLE `calendar_shares`;--> statement-breakpoint+ALTER TABLE `__new_calendar_shares` RENAME TO `calendar_shares`;--> statement-breakpoint+CREATE INDEX `calendar_shares_calendarId_idx` ON `calendar_shares` (`calendar_id`);--> statement-breakpoint+CREATE INDEX `calendar_shares_userId_idx` ON `calendar_shares` (`user_id`);--> statement-breakpoint+ALTER TABLE `calendar_notes` ADD `created_by` text REFERENCES user(id);--> statement-breakpoint+ALTER TABLE `calendar_permission_bundles` ADD `seed_key` text;--> statement-breakpoint+ALTER TABLE `shift_presets` ADD `created_by` text REFERENCES user(id);--> statement-breakpoint+ALTER TABLE `shifts` ADD `created_by` text REFERENCES user(id);\ No newline at end of filediff --git a/drizzle/0023_permission_bundles_own_any.sql b/drizzle/0023_permission_bundles_own_any.sqlnew file mode 100644index 0000000..3d636cf--- /dev/null+++ b/drizzle/0023_permission_bundles_own_any.sql@@ -0,0 +1,75 @@+-- Own/Any capability split (E1) plus the extended guest lockout (E2, E7)+-- for every bundle that already exists — a frozen, one-time snapshot of+-- this shape, hand-written rather than generated from+-- lib/permission-bundles.ts so a later catalog change never rewrites what+-- this migration already did. See+-- .LOCAL/calendar-permission-bundles-plan.md, Stufe 1b package 2.+--+-- At this point every bundle in the database is one of the four seeded+-- ones from drizzle/0020_backfill_permission_bundles.sql (the bundle+-- editor that lets an owner create custom bundles doesn't exist yet), so+-- name-based matching below is safe.++-- 1. Rename the collapsed capabilities into their Own/Any pair. Every+-- Contribute/Manage/Admin bundle currently holds the old name (0020+-- gave all three the full "write" content), so this is unconditional.+-- Plain substring replacement is safe: capabilities is compact+-- JSON (`["a","b"]`, no whitespace) and none of the old names is a+-- substring of another capability name.+UPDATE calendar_permission_bundles+SET capabilities = REPLACE(+ REPLACE(+ REPLACE(+ REPLACE(capabilities, '"editShift"', '"editOwnShift","editAnyShift"'),+ '"deleteShift"', '"deleteOwnShift","deleteAnyShift"'+ ),+ '"managePresets"', '"manageOwnPresets","manageAnyPresets"'+ ),+ '"manageNotesEvents"', '"manageOwnNotesEvents","manageAnyNotesEvents"'+);+--> statement-breakpoint++-- 2. Stamp seedKey so the UI can show a translated standard name until the+-- bundle is renamed (E6).+UPDATE calendar_permission_bundles SET seed_key = 'read' WHERE name = 'Read' AND seed_key IS NULL;+--> statement-breakpoint+UPDATE calendar_permission_bundles SET seed_key = 'contribute' WHERE name = 'Contribute' AND seed_key IS NULL;+--> statement-breakpoint+UPDATE calendar_permission_bundles SET seed_key = 'manage' WHERE name = 'Manage' AND seed_key IS NULL;+--> statement-breakpoint+UPDATE calendar_permission_bundles SET seed_key = 'admin' WHERE name = 'Admin' AND seed_key IS NULL;+--> statement-breakpoint++-- 3. Extend the guest lockout to manageExternalSync/deleteSyncLogs (E2),+-- without changing anything for an already-invited user. Contribute and+-- Manage currently hold identical content (0020), so repointing every+-- share that sits on a synced Contribute bundle to that calendar's+-- Manage bundle preserves that user's behavior exactly (Manage keeps+-- the sync capabilities). Only guest/link access — calendars.guest_bundle_id+-- and calendar_access_tokens, deliberately untouched here — actually+-- loses the capability, which is the intended behavior change.+UPDATE calendar_shares+SET bundle_id = (+ SELECT manage.id FROM calendar_permission_bundles manage+ WHERE manage.calendar_id = (+ SELECT contribute.calendar_id FROM calendar_permission_bundles contribute+ WHERE contribute.id = calendar_shares.bundle_id+ )+ AND manage.name = 'Manage'+)+WHERE bundle_id IN (+ SELECT id FROM calendar_permission_bundles+ WHERE name = 'Contribute' AND capabilities LIKE '%"manageExternalSync"%'+);+--> statement-breakpoint++-- 4. Now strip manageExternalSync/deleteSyncLogs from every Contribute+-- bundle — no share still points at one with that capability set after+-- step 3, so this only affects guest/link reachability.+UPDATE calendar_permission_bundles+SET capabilities = (+ SELECT json_group_array(value)+ FROM json_each(calendar_permission_bundles.capabilities)+ WHERE value NOT IN ('manageExternalSync', 'deleteSyncLogs')+)+WHERE name = 'Contribute';diff --git a/drizzle/0024_flawless_iron_man.sql b/drizzle/0024_flawless_iron_man.sqlnew file mode 100644index 0000000..1ff2809--- /dev/null+++ b/drizzle/0024_flawless_iron_man.sql@@ -0,0 +1,3 @@+CREATE INDEX `calendar_access_tokens_bundleId_idx` ON `calendar_access_tokens` (`bundle_id`);--> statement-breakpoint+CREATE UNIQUE INDEX `calendar_permission_bundles_calendarId_seedKey_idx` ON `calendar_permission_bundles` (`calendar_id`,`seed_key`) WHERE "calendar_permission_bundles"."seed_key" is not null;--> statement-breakpoint+CREATE INDEX `calendar_shares_bundleId_idx` ON `calendar_shares` (`bundle_id`);\ No newline at end of filediff --git a/drizzle/0019_peaceful_peter_parker.sql b/drizzle/0025_nappy_swarm.sqlsimilarity index 100%rename from drizzle/0019_peaceful_peter_parker.sqlrename to drizzle/0025_nappy_swarm.sqldiff --git a/drizzle/meta/0019_snapshot.json b/drizzle/meta/0019_snapshot.jsonindex a5dac52..cf5ba7c 100644--- a/drizzle/meta/0019_snapshot.json+++ b/drizzle/meta/0019_snapshot.json@@ -1,7 +1,7 @@{"version": "6","dialect": "sqlite",- "id": "20a88346-8085-45af-901f-ced11a89ebcf",+ "id": "050fdae0-67a8-4a33-87a4-874c6ef5a42d","prevId": "46c43bf1-957b-48a6-80b6-8bb2d5c9ac6c","tables": {"account": {@@ -289,6 +289,13 @@"notNull": false,"autoincrement": false},+ "bundle_id": {+ "name": "bundle_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },"permission": {"name": "permission","type": "text",@@ -388,6 +395,19 @@"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": "cascade",+ "onUpdate": "no action"+ },"calendar_access_tokens_created_by_user_id_fk": {"name": "calendar_access_tokens_created_by_user_id_fk","tableFrom": "calendar_access_tokens",@@ -504,6 +524,82 @@"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+ },+ "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+ }+ },+ "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": {@@ -528,6 +624,13 @@"notNull": true,"autoincrement": false},+ "bundle_id": {+ "name": "bundle_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },"permission": {"name": "permission","type": "text",@@ -595,6 +698,19 @@"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": "cascade",+ "onUpdate": "no action"+ },"calendar_shares_shared_by_user_id_fk": {"name": "calendar_shares_shared_by_user_id_fk","tableFrom": "calendar_shares",@@ -645,6 +761,13 @@"notNull": false,"autoincrement": false},+ "guest_bundle_id": {+ "name": "guest_bundle_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },"guest_permission": {"name": "guest_permission","type": "text",@@ -1529,13 +1652,6 @@"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",@@ -1634,14 +1750,6 @@"primaryKey": false,"notNull": false,"autoincrement": false- },- "must_change_password": {- "name": "must_change_password",- "type": "integer",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": false}},"indexes": {diff --git a/drizzle/meta/0020_snapshot.json b/drizzle/meta/0020_snapshot.jsonnew file mode 100644index 0000000..cba9d62--- /dev/null+++ b/drizzle/meta/0020_snapshot.json@@ -0,0 +1,1991 @@+{+ "id": "a1d7deb0-bf31-4e98-b48f-ea6479425eec",+ "prevId": "050fdae0-67a8-4a33-87a4-874c6ef5a42d",+ "version": "6",+ "dialect": "sqlite",+ "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",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "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": false,+ "autoincrement": false+ },+ "permission": {+ "name": "permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'read'"+ },+ "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+ }+ },+ "foreignKeys": {+ "calendar_access_tokens_calendar_id_calendars_id_fk": {+ "name": "calendar_access_tokens_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_access_tokens",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "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",+ "columnsFrom": [+ "bundle_id"+ ],+ "tableTo": "calendar_permission_bundles",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "calendar_access_tokens_created_by_user_id_fk": {+ "name": "calendar_access_tokens_created_by_user_id_fk",+ "tableFrom": "calendar_access_tokens",+ "columnsFrom": [+ "created_by"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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_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",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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+ },+ "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+ }+ },+ "foreignKeys": {+ "calendar_permission_bundles_calendar_id_calendars_id_fk": {+ "name": "calendar_permission_bundles_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_permission_bundles",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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": false,+ "autoincrement": false+ },+ "permission": {+ "name": "permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'read'"+ },+ "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+ }+ },+ "foreignKeys": {+ "calendar_shares_calendar_id_calendars_id_fk": {+ "name": "calendar_shares_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_shares",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "calendar_shares_user_id_user_id_fk": {+ "name": "calendar_shares_user_id_user_id_fk",+ "tableFrom": "calendar_shares",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "calendar_shares_bundle_id_calendar_permission_bundles_id_fk": {+ "name": "calendar_shares_bundle_id_calendar_permission_bundles_id_fk",+ "tableFrom": "calendar_shares",+ "columnsFrom": [+ "bundle_id"+ ],+ "tableTo": "calendar_permission_bundles",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "calendar_shares_shared_by_user_id_fk": {+ "name": "calendar_shares_shared_by_user_id_fk",+ "tableFrom": "calendar_shares",+ "columnsFrom": [+ "shared_by"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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+ },+ "guest_permission": {+ "name": "guest_permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'none'"+ },+ "allow_self_signup": {+ "name": "allow_self_signup",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "signups_enabled": {+ "name": "signups_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "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",+ "columnsFrom": [+ "owner_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "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",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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_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",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": [+ "shift_id"+ ],+ "tableTo": "shifts",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "shift_signups_user_id_user_id_fk": {+ "name": "shift_signups_user_id_user_id_fk",+ "tableFrom": "shift_signups",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "shift_signups_signed_up_by_user_id_fk": {+ "name": "shift_signups_signed_up_by_user_id_fk",+ "tableFrom": "shift_signups",+ "columnsFrom": [+ "signed_up_by"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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_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",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "shifts_preset_id_shift_presets_id_fk": {+ "name": "shifts_preset_id_shift_presets_id_fk",+ "tableFrom": "shifts",+ "columnsFrom": [+ "preset_id"+ ],+ "tableTo": "shift_presets",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ },+ "shifts_external_sync_id_external_syncs_id_fk": {+ "name": "shifts_external_sync_id_external_syncs_id_fk",+ "tableFrom": "shifts",+ "columnsFrom": [+ "external_sync_id"+ ],+ "tableTo": "external_syncs",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "sync_logs_external_sync_id_external_syncs_id_fk": {+ "name": "sync_logs_external_sync_id_external_syncs_id_fk",+ "tableFrom": "sync_logs",+ "columnsFrom": [+ "external_sync_id"+ ],+ "tableTo": "external_syncs",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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'"+ },+ "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+ }+ },+ "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",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "user_calendar_subscriptions_calendar_id_calendars_id_fk": {+ "name": "user_calendar_subscriptions_calendar_id_calendars_id_fk",+ "tableFrom": "user_calendar_subscriptions",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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": {+ "columns": {},+ "schemas": {},+ "tables": {}+ },+ "internal": {+ "indexes": {}+ }+}\ No newline at end of filediff --git a/drizzle/meta/0021_snapshot.json b/drizzle/meta/0021_snapshot.jsonnew file mode 100644index 0000000..9ebe550--- /dev/null+++ b/drizzle/meta/0021_snapshot.json@@ -0,0 +1,1959 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "599ae3ff-6ef8-45d9-9271-50a74b2d0927",+ "prevId": "a1d7deb0-bf31-4e98-b48f-ea6479425eec",+ "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+ }+ },+ "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": "cascade",+ "onUpdate": "no action"+ },+ "calendar_access_tokens_created_by_user_id_fk": {+ "name": "calendar_access_tokens_created_by_user_id_fk",+ "tableFrom": "calendar_access_tokens",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_notes": {+ "name": "calendar_notes",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "date": {+ "name": "date",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "note": {+ "name": "note",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'note'"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recurring_pattern": {+ "name": "recurring_pattern",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'none'"+ },+ "recurring_interval": {+ "name": "recurring_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_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"+ }+ },+ "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+ },+ "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+ }+ },+ "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+ }+ },+ "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": "cascade",+ "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+ },+ "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": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "impersonated_by": {+ "name": "impersonated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "session_token_unique": {+ "name": "session_token_unique",+ "columns": [+ "token"+ ],+ "isUnique": true+ },+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "shift_presets": {+ "name": "shift_presets",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "start_time": {+ "name": "start_time",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "end_time": {+ "name": "end_time",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'#3b82f6'"+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "group_name": {+ "name": "group_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_secondary": {+ "name": "is_secondary",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "is_all_day": {+ "name": "is_all_day",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "hide_from_stats": {+ "name": "hide_from_stats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "default_signup_capacity": {+ "name": "default_signup_capacity",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_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"+ }+ },+ "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": {}+ },+ "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_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"+ }+ },+ "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'"+ },+ "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+ }+ },+ "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 filediff --git a/drizzle/meta/0022_snapshot.json b/drizzle/meta/0022_snapshot.jsonnew file mode 100644index 0000000..df14670--- /dev/null+++ b/drizzle/meta/0022_snapshot.json@@ -0,0 +1,2026 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "7a8485e7-50f6-45b1-8f77-904502fd4996",+ "prevId": "599ae3ff-6ef8-45d9-9271-50a74b2d0927",+ "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+ }+ },+ "foreignKeys": {+ "calendar_access_tokens_calendar_id_calendars_id_fk": {+ "name": "calendar_access_tokens_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_access_tokens",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_access_tokens_bundle_id_calendar_permission_bundles_id_fk": {+ "name": "calendar_access_tokens_bundle_id_calendar_permission_bundles_id_fk",+ "tableFrom": "calendar_access_tokens",+ "tableTo": "calendar_permission_bundles",+ "columnsFrom": [+ "bundle_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "restrict",+ "onUpdate": "no action"+ },+ "calendar_access_tokens_created_by_user_id_fk": {+ "name": "calendar_access_tokens_created_by_user_id_fk",+ "tableFrom": "calendar_access_tokens",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_notes": {+ "name": "calendar_notes",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "date": {+ "name": "date",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "note": {+ "name": "note",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'note'"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recurring_pattern": {+ "name": "recurring_pattern",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'none'"+ },+ "recurring_interval": {+ "name": "recurring_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "calendar_notes_calendar_id_calendars_id_fk": {+ "name": "calendar_notes_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_notes",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_notes_created_by_user_id_fk": {+ "name": "calendar_notes_created_by_user_id_fk",+ "tableFrom": "calendar_notes",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_permission_bundles": {+ "name": "calendar_permission_bundles",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "seed_key": {+ "name": "seed_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "capabilities": {+ "name": "capabilities",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "calendar_permission_bundles_calendarId_idx": {+ "name": "calendar_permission_bundles_calendarId_idx",+ "columns": [+ "calendar_id"+ ],+ "isUnique": false+ }+ },+ "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+ }+ },+ "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+ },+ "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": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "impersonated_by": {+ "name": "impersonated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "session_token_unique": {+ "name": "session_token_unique",+ "columns": [+ "token"+ ],+ "isUnique": true+ },+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "shift_presets": {+ "name": "shift_presets",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "start_time": {+ "name": "start_time",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "end_time": {+ "name": "end_time",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'#3b82f6'"+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "group_name": {+ "name": "group_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_secondary": {+ "name": "is_secondary",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "is_all_day": {+ "name": "is_all_day",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "hide_from_stats": {+ "name": "hide_from_stats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "default_signup_capacity": {+ "name": "default_signup_capacity",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "shift_presets_calendar_id_calendars_id_fk": {+ "name": "shift_presets_calendar_id_calendars_id_fk",+ "tableFrom": "shift_presets",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "shift_presets_created_by_user_id_fk": {+ "name": "shift_presets_created_by_user_id_fk",+ "tableFrom": "shift_presets",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "shift_signups": {+ "name": "shift_signups",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "shift_id": {+ "name": "shift_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "signed_up_by": {+ "name": "signed_up_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "shift_signups_shiftId_idx": {+ "name": "shift_signups_shiftId_idx",+ "columns": [+ "shift_id"+ ],+ "isUnique": false+ },+ "shift_signups_userId_idx": {+ "name": "shift_signups_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "shift_signups_shiftId_userId_idx": {+ "name": "shift_signups_shiftId_userId_idx",+ "columns": [+ "shift_id",+ "user_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "shift_signups_shift_id_shifts_id_fk": {+ "name": "shift_signups_shift_id_shifts_id_fk",+ "tableFrom": "shift_signups",+ "tableTo": "shifts",+ "columnsFrom": [+ "shift_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "shift_signups_user_id_user_id_fk": {+ "name": "shift_signups_user_id_user_id_fk",+ "tableFrom": "shift_signups",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "shift_signups_signed_up_by_user_id_fk": {+ "name": "shift_signups_signed_up_by_user_id_fk",+ "tableFrom": "shift_signups",+ "tableTo": "user",+ "columnsFrom": [+ "signed_up_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "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'"+ },+ "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+ }+ },+ "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 filediff --git a/drizzle/meta/0023_snapshot.json b/drizzle/meta/0023_snapshot.jsonnew file mode 100644index 0000000..862209c--- /dev/null+++ b/drizzle/meta/0023_snapshot.json@@ -0,0 +1,2026 @@+{+ "id": "46b67c6c-01f1-4e58-b035-d65526da0d20",+ "prevId": "7a8485e7-50f6-45b1-8f77-904502fd4996",+ "version": "6",+ "dialect": "sqlite",+ "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",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "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+ }+ },+ "foreignKeys": {+ "calendar_access_tokens_calendar_id_calendars_id_fk": {+ "name": "calendar_access_tokens_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_access_tokens",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "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",+ "columnsFrom": [+ "bundle_id"+ ],+ "tableTo": "calendar_permission_bundles",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "restrict"+ },+ "calendar_access_tokens_created_by_user_id_fk": {+ "name": "calendar_access_tokens_created_by_user_id_fk",+ "tableFrom": "calendar_access_tokens",+ "columnsFrom": [+ "created_by"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "calendar_notes_created_by_user_id_fk": {+ "name": "calendar_notes_created_by_user_id_fk",+ "tableFrom": "calendar_notes",+ "columnsFrom": [+ "created_by"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "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+ }+ },+ "foreignKeys": {+ "calendar_permission_bundles_calendar_id_calendars_id_fk": {+ "name": "calendar_permission_bundles_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_permission_bundles",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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+ }+ },+ "foreignKeys": {+ "calendar_shares_calendar_id_calendars_id_fk": {+ "name": "calendar_shares_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_shares",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "calendar_shares_user_id_user_id_fk": {+ "name": "calendar_shares_user_id_user_id_fk",+ "tableFrom": "calendar_shares",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "calendar_shares_bundle_id_calendar_permission_bundles_id_fk": {+ "name": "calendar_shares_bundle_id_calendar_permission_bundles_id_fk",+ "tableFrom": "calendar_shares",+ "columnsFrom": [+ "bundle_id"+ ],+ "tableTo": "calendar_permission_bundles",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "restrict"+ },+ "calendar_shares_shared_by_user_id_fk": {+ "name": "calendar_shares_shared_by_user_id_fk",+ "tableFrom": "calendar_shares",+ "columnsFrom": [+ "shared_by"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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+ },+ "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",+ "columnsFrom": [+ "owner_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "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",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "shift_presets_created_by_user_id_fk": {+ "name": "shift_presets_created_by_user_id_fk",+ "tableFrom": "shift_presets",+ "columnsFrom": [+ "created_by"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "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",+ "columnsFrom": [+ "shift_id"+ ],+ "tableTo": "shifts",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "shift_signups_user_id_user_id_fk": {+ "name": "shift_signups_user_id_user_id_fk",+ "tableFrom": "shift_signups",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "shift_signups_signed_up_by_user_id_fk": {+ "name": "shift_signups_signed_up_by_user_id_fk",+ "tableFrom": "shift_signups",+ "columnsFrom": [+ "signed_up_by"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "shifts_preset_id_shift_presets_id_fk": {+ "name": "shifts_preset_id_shift_presets_id_fk",+ "tableFrom": "shifts",+ "columnsFrom": [+ "preset_id"+ ],+ "tableTo": "shift_presets",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ },+ "shifts_external_sync_id_external_syncs_id_fk": {+ "name": "shifts_external_sync_id_external_syncs_id_fk",+ "tableFrom": "shifts",+ "columnsFrom": [+ "external_sync_id"+ ],+ "tableTo": "external_syncs",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "shifts_created_by_user_id_fk": {+ "name": "shifts_created_by_user_id_fk",+ "tableFrom": "shifts",+ "columnsFrom": [+ "created_by"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "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",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "sync_logs_external_sync_id_external_syncs_id_fk": {+ "name": "sync_logs_external_sync_id_external_syncs_id_fk",+ "tableFrom": "sync_logs",+ "columnsFrom": [+ "external_sync_id"+ ],+ "tableTo": "external_syncs",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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'"+ },+ "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+ }+ },+ "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",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "user_calendar_subscriptions_calendar_id_calendars_id_fk": {+ "name": "user_calendar_subscriptions_calendar_id_calendars_id_fk",+ "tableFrom": "user_calendar_subscriptions",+ "columnsFrom": [+ "calendar_id"+ ],+ "tableTo": "calendars",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": [+ "user_id"+ ],+ "tableTo": "user",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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": {+ "columns": {},+ "schemas": {},+ "tables": {}+ },+ "internal": {+ "indexes": {}+ }+}\ No newline at end of filediff --git a/drizzle/meta/0024_snapshot.json b/drizzle/meta/0024_snapshot.jsonnew file mode 100644index 0000000..8b1a0a6--- /dev/null+++ b/drizzle/meta/0024_snapshot.json@@ -0,0 +1,2049 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "8083584b-0a43-44eb-88ac-0ac063912f77",+ "prevId": "46b67c6c-01f1-4e58-b035-d65526da0d20",+ "tables": {+ "account": {+ "name": "account",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_logs": {+ "name": "audit_logs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resource_id": {+ "name": "resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "severity": {+ "name": "severity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'info'"+ },+ "is_user_visible": {+ "name": "is_user_visible",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "timestamp": {+ "name": "timestamp",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "audit_logs_userId_timestamp_idx": {+ "name": "audit_logs_userId_timestamp_idx",+ "columns": [+ "user_id",+ "timestamp"+ ],+ "isUnique": false+ },+ "audit_logs_action_timestamp_idx": {+ "name": "audit_logs_action_timestamp_idx",+ "columns": [+ "action",+ "timestamp"+ ],+ "isUnique": false+ },+ "audit_logs_userVisible_userId_timestamp_idx": {+ "name": "audit_logs_userVisible_userId_timestamp_idx",+ "columns": [+ "is_user_visible",+ "user_id",+ "timestamp"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_logs_user_id_user_id_fk": {+ "name": "audit_logs_user_id_user_id_fk",+ "tableFrom": "audit_logs",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_access_tokens": {+ "name": "calendar_access_tokens",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "bundle_id": {+ "name": "bundle_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "usage_count": {+ "name": "usage_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ }+ },+ "indexes": {+ "calendar_access_tokens_token_unique": {+ "name": "calendar_access_tokens_token_unique",+ "columns": [+ "token"+ ],+ "isUnique": true+ },+ "calendar_access_tokens_token_idx": {+ "name": "calendar_access_tokens_token_idx",+ "columns": [+ "token"+ ],+ "isUnique": false+ },+ "calendar_access_tokens_calendarId_isActive_idx": {+ "name": "calendar_access_tokens_calendarId_isActive_idx",+ "columns": [+ "calendar_id",+ "is_active"+ ],+ "isUnique": false+ },+ "calendar_access_tokens_createdBy_idx": {+ "name": "calendar_access_tokens_createdBy_idx",+ "columns": [+ "created_by"+ ],+ "isUnique": false+ },+ "calendar_access_tokens_bundleId_idx": {+ "name": "calendar_access_tokens_bundleId_idx",+ "columns": [+ "bundle_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "calendar_access_tokens_calendar_id_calendars_id_fk": {+ "name": "calendar_access_tokens_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_access_tokens",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_access_tokens_bundle_id_calendar_permission_bundles_id_fk": {+ "name": "calendar_access_tokens_bundle_id_calendar_permission_bundles_id_fk",+ "tableFrom": "calendar_access_tokens",+ "tableTo": "calendar_permission_bundles",+ "columnsFrom": [+ "bundle_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "restrict",+ "onUpdate": "no action"+ },+ "calendar_access_tokens_created_by_user_id_fk": {+ "name": "calendar_access_tokens_created_by_user_id_fk",+ "tableFrom": "calendar_access_tokens",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_notes": {+ "name": "calendar_notes",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "date": {+ "name": "date",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "note": {+ "name": "note",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'note'"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recurring_pattern": {+ "name": "recurring_pattern",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'none'"+ },+ "recurring_interval": {+ "name": "recurring_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "calendar_notes_calendar_id_calendars_id_fk": {+ "name": "calendar_notes_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_notes",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_notes_created_by_user_id_fk": {+ "name": "calendar_notes_created_by_user_id_fk",+ "tableFrom": "calendar_notes",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_permission_bundles": {+ "name": "calendar_permission_bundles",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "seed_key": {+ "name": "seed_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "capabilities": {+ "name": "capabilities",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "calendar_permission_bundles_calendarId_idx": {+ "name": "calendar_permission_bundles_calendarId_idx",+ "columns": [+ "calendar_id"+ ],+ "isUnique": false+ },+ "calendar_permission_bundles_calendarId_seedKey_idx": {+ "name": "calendar_permission_bundles_calendarId_seedKey_idx",+ "columns": [+ "calendar_id",+ "seed_key"+ ],+ "isUnique": true,+ "where": "\"calendar_permission_bundles\".\"seed_key\" is not null"+ }+ },+ "foreignKeys": {+ "calendar_permission_bundles_calendar_id_calendars_id_fk": {+ "name": "calendar_permission_bundles_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_permission_bundles",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_shares": {+ "name": "calendar_shares",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bundle_id": {+ "name": "bundle_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "shared_by": {+ "name": "shared_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "calendar_shares_calendarId_idx": {+ "name": "calendar_shares_calendarId_idx",+ "columns": [+ "calendar_id"+ ],+ "isUnique": false+ },+ "calendar_shares_userId_idx": {+ "name": "calendar_shares_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "calendar_shares_bundleId_idx": {+ "name": "calendar_shares_bundleId_idx",+ "columns": [+ "bundle_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "calendar_shares_calendar_id_calendars_id_fk": {+ "name": "calendar_shares_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_shares",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_shares_user_id_user_id_fk": {+ "name": "calendar_shares_user_id_user_id_fk",+ "tableFrom": "calendar_shares",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_shares_bundle_id_calendar_permission_bundles_id_fk": {+ "name": "calendar_shares_bundle_id_calendar_permission_bundles_id_fk",+ "tableFrom": "calendar_shares",+ "tableTo": "calendar_permission_bundles",+ "columnsFrom": [+ "bundle_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "restrict",+ "onUpdate": "no action"+ },+ "calendar_shares_shared_by_user_id_fk": {+ "name": "calendar_shares_shared_by_user_id_fk",+ "tableFrom": "calendar_shares",+ "tableTo": "user",+ "columnsFrom": [+ "shared_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendars": {+ "name": "calendars",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'#3b82f6'"+ },+ "owner_id": {+ "name": "owner_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "guest_bundle_id": {+ "name": "guest_bundle_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "signups_enabled": {+ "name": "signups_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "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": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "impersonated_by": {+ "name": "impersonated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "session_token_unique": {+ "name": "session_token_unique",+ "columns": [+ "token"+ ],+ "isUnique": true+ },+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "shift_presets": {+ "name": "shift_presets",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "start_time": {+ "name": "start_time",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "end_time": {+ "name": "end_time",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'#3b82f6'"+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "group_name": {+ "name": "group_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_secondary": {+ "name": "is_secondary",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "is_all_day": {+ "name": "is_all_day",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "hide_from_stats": {+ "name": "hide_from_stats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "default_signup_capacity": {+ "name": "default_signup_capacity",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "shift_presets_calendar_id_calendars_id_fk": {+ "name": "shift_presets_calendar_id_calendars_id_fk",+ "tableFrom": "shift_presets",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "shift_presets_created_by_user_id_fk": {+ "name": "shift_presets_created_by_user_id_fk",+ "tableFrom": "shift_presets",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "shift_signups": {+ "name": "shift_signups",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "shift_id": {+ "name": "shift_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "signed_up_by": {+ "name": "signed_up_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "shift_signups_shiftId_idx": {+ "name": "shift_signups_shiftId_idx",+ "columns": [+ "shift_id"+ ],+ "isUnique": false+ },+ "shift_signups_userId_idx": {+ "name": "shift_signups_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "shift_signups_shiftId_userId_idx": {+ "name": "shift_signups_shiftId_userId_idx",+ "columns": [+ "shift_id",+ "user_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "shift_signups_shift_id_shifts_id_fk": {+ "name": "shift_signups_shift_id_shifts_id_fk",+ "tableFrom": "shift_signups",+ "tableTo": "shifts",+ "columnsFrom": [+ "shift_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "shift_signups_user_id_user_id_fk": {+ "name": "shift_signups_user_id_user_id_fk",+ "tableFrom": "shift_signups",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "shift_signups_signed_up_by_user_id_fk": {+ "name": "shift_signups_signed_up_by_user_id_fk",+ "tableFrom": "shift_signups",+ "tableTo": "user",+ "columnsFrom": [+ "signed_up_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "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'"+ },+ "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+ }+ },+ "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 filediff --git a/drizzle/meta/0025_snapshot.json b/drizzle/meta/0025_snapshot.jsonnew file mode 100644index 0000000..dd83604--- /dev/null+++ b/drizzle/meta/0025_snapshot.json@@ -0,0 +1,2064 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "5d6f9d6d-8737-4803-a72b-9db3701bee45",+ "prevId": "8083584b-0a43-44eb-88ac-0ac063912f77",+ "tables": {+ "account": {+ "name": "account",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_logs": {+ "name": "audit_logs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resource_id": {+ "name": "resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "severity": {+ "name": "severity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'info'"+ },+ "is_user_visible": {+ "name": "is_user_visible",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "timestamp": {+ "name": "timestamp",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "audit_logs_userId_timestamp_idx": {+ "name": "audit_logs_userId_timestamp_idx",+ "columns": [+ "user_id",+ "timestamp"+ ],+ "isUnique": false+ },+ "audit_logs_action_timestamp_idx": {+ "name": "audit_logs_action_timestamp_idx",+ "columns": [+ "action",+ "timestamp"+ ],+ "isUnique": false+ },+ "audit_logs_userVisible_userId_timestamp_idx": {+ "name": "audit_logs_userVisible_userId_timestamp_idx",+ "columns": [+ "is_user_visible",+ "user_id",+ "timestamp"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_logs_user_id_user_id_fk": {+ "name": "audit_logs_user_id_user_id_fk",+ "tableFrom": "audit_logs",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_access_tokens": {+ "name": "calendar_access_tokens",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "bundle_id": {+ "name": "bundle_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "usage_count": {+ "name": "usage_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ }+ },+ "indexes": {+ "calendar_access_tokens_token_unique": {+ "name": "calendar_access_tokens_token_unique",+ "columns": [+ "token"+ ],+ "isUnique": true+ },+ "calendar_access_tokens_token_idx": {+ "name": "calendar_access_tokens_token_idx",+ "columns": [+ "token"+ ],+ "isUnique": false+ },+ "calendar_access_tokens_calendarId_isActive_idx": {+ "name": "calendar_access_tokens_calendarId_isActive_idx",+ "columns": [+ "calendar_id",+ "is_active"+ ],+ "isUnique": false+ },+ "calendar_access_tokens_createdBy_idx": {+ "name": "calendar_access_tokens_createdBy_idx",+ "columns": [+ "created_by"+ ],+ "isUnique": false+ },+ "calendar_access_tokens_bundleId_idx": {+ "name": "calendar_access_tokens_bundleId_idx",+ "columns": [+ "bundle_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "calendar_access_tokens_calendar_id_calendars_id_fk": {+ "name": "calendar_access_tokens_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_access_tokens",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_access_tokens_bundle_id_calendar_permission_bundles_id_fk": {+ "name": "calendar_access_tokens_bundle_id_calendar_permission_bundles_id_fk",+ "tableFrom": "calendar_access_tokens",+ "tableTo": "calendar_permission_bundles",+ "columnsFrom": [+ "bundle_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "restrict",+ "onUpdate": "no action"+ },+ "calendar_access_tokens_created_by_user_id_fk": {+ "name": "calendar_access_tokens_created_by_user_id_fk",+ "tableFrom": "calendar_access_tokens",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_notes": {+ "name": "calendar_notes",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "date": {+ "name": "date",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "note": {+ "name": "note",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'note'"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recurring_pattern": {+ "name": "recurring_pattern",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'none'"+ },+ "recurring_interval": {+ "name": "recurring_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "calendar_notes_calendar_id_calendars_id_fk": {+ "name": "calendar_notes_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_notes",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_notes_created_by_user_id_fk": {+ "name": "calendar_notes_created_by_user_id_fk",+ "tableFrom": "calendar_notes",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_permission_bundles": {+ "name": "calendar_permission_bundles",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "seed_key": {+ "name": "seed_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "capabilities": {+ "name": "capabilities",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "calendar_permission_bundles_calendarId_idx": {+ "name": "calendar_permission_bundles_calendarId_idx",+ "columns": [+ "calendar_id"+ ],+ "isUnique": false+ },+ "calendar_permission_bundles_calendarId_seedKey_idx": {+ "name": "calendar_permission_bundles_calendarId_seedKey_idx",+ "columns": [+ "calendar_id",+ "seed_key"+ ],+ "isUnique": true,+ "where": "\"calendar_permission_bundles\".\"seed_key\" is not null"+ }+ },+ "foreignKeys": {+ "calendar_permission_bundles_calendar_id_calendars_id_fk": {+ "name": "calendar_permission_bundles_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_permission_bundles",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_shares": {+ "name": "calendar_shares",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bundle_id": {+ "name": "bundle_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "shared_by": {+ "name": "shared_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "calendar_shares_calendarId_idx": {+ "name": "calendar_shares_calendarId_idx",+ "columns": [+ "calendar_id"+ ],+ "isUnique": false+ },+ "calendar_shares_userId_idx": {+ "name": "calendar_shares_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "calendar_shares_bundleId_idx": {+ "name": "calendar_shares_bundleId_idx",+ "columns": [+ "bundle_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "calendar_shares_calendar_id_calendars_id_fk": {+ "name": "calendar_shares_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_shares",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_shares_user_id_user_id_fk": {+ "name": "calendar_shares_user_id_user_id_fk",+ "tableFrom": "calendar_shares",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_shares_bundle_id_calendar_permission_bundles_id_fk": {+ "name": "calendar_shares_bundle_id_calendar_permission_bundles_id_fk",+ "tableFrom": "calendar_shares",+ "tableTo": "calendar_permission_bundles",+ "columnsFrom": [+ "bundle_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "restrict",+ "onUpdate": "no action"+ },+ "calendar_shares_shared_by_user_id_fk": {+ "name": "calendar_shares_shared_by_user_id_fk",+ "tableFrom": "calendar_shares",+ "tableTo": "user",+ "columnsFrom": [+ "shared_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendars": {+ "name": "calendars",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'#3b82f6'"+ },+ "owner_id": {+ "name": "owner_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "guest_bundle_id": {+ "name": "guest_bundle_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "signups_enabled": {+ "name": "signups_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "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": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "impersonated_by": {+ "name": "impersonated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "session_token_unique": {+ "name": "session_token_unique",+ "columns": [+ "token"+ ],+ "isUnique": true+ },+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "shift_presets": {+ "name": "shift_presets",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "start_time": {+ "name": "start_time",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "end_time": {+ "name": "end_time",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'#3b82f6'"+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "group_name": {+ "name": "group_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_secondary": {+ "name": "is_secondary",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "is_all_day": {+ "name": "is_all_day",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "hide_from_stats": {+ "name": "hide_from_stats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "default_signup_capacity": {+ "name": "default_signup_capacity",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "shift_presets_calendar_id_calendars_id_fk": {+ "name": "shift_presets_calendar_id_calendars_id_fk",+ "tableFrom": "shift_presets",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "shift_presets_created_by_user_id_fk": {+ "name": "shift_presets_created_by_user_id_fk",+ "tableFrom": "shift_presets",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "shift_signups": {+ "name": "shift_signups",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "shift_id": {+ "name": "shift_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "signed_up_by": {+ "name": "signed_up_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "shift_signups_shiftId_idx": {+ "name": "shift_signups_shiftId_idx",+ "columns": [+ "shift_id"+ ],+ "isUnique": false+ },+ "shift_signups_userId_idx": {+ "name": "shift_signups_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "shift_signups_shiftId_userId_idx": {+ "name": "shift_signups_shiftId_userId_idx",+ "columns": [+ "shift_id",+ "user_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "shift_signups_shift_id_shifts_id_fk": {+ "name": "shift_signups_shift_id_shifts_id_fk",+ "tableFrom": "shift_signups",+ "tableTo": "shifts",+ "columnsFrom": [+ "shift_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "shift_signups_user_id_user_id_fk": {+ "name": "shift_signups_user_id_user_id_fk",+ "tableFrom": "shift_signups",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "shift_signups_signed_up_by_user_id_fk": {+ "name": "shift_signups_signed_up_by_user_id_fk",+ "tableFrom": "shift_signups",+ "tableTo": "user",+ "columnsFrom": [+ "signed_up_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "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 filediff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.jsonindex 9b06f78..88677eb 100644--- a/drizzle/meta/_journal.json+++ b/drizzle/meta/_journal.json@@ -138,8 +138,50 @@{"idx": 19,"version": "6",- "when": 1789388420861,- "tag": "0019_peaceful_peter_parker",+ "when": 1789312613924,+ "tag": "0019_add_permission_bundles_additive",+ "breakpoints": true+ },+ {+ "idx": 20,+ "version": "6",+ "when": 1789312626329,+ "tag": "0020_backfill_permission_bundles",+ "breakpoints": true+ },+ {+ "idx": 21,+ "version": "6",+ "when": 1789312778402,+ "tag": "0021_drop_legacy_permission_columns",+ "breakpoints": true+ },+ {+ "idx": 22,+ "version": "6",+ "when": 1789318003589,+ "tag": "0022_quick_felicia_hardy",+ "breakpoints": true+ },+ {+ "idx": 23,+ "version": "6",+ "when": 1789318282174,+ "tag": "0023_permission_bundles_own_any",+ "breakpoints": true+ },+ {+ "idx": 24,+ "version": "6",+ "when": 1789369724137,+ "tag": "0024_flawless_iron_man",+ "breakpoints": true+ },+ {+ "idx": 25,+ "version": "6",+ "when": 1789406686317,+ "tag": "0025_nappy_swarm","breakpoints": true}]diff --git a/hooks/useAdminAccess.ts b/hooks/useAdminAccess.tsindex 092bbb3..eafe5f0 100644--- a/hooks/useAdminAccess.ts+++ b/hooks/useAdminAccess.ts@@ -11,7 +11,7 @@ import {canDeleteUser,canBanUser,canChangeUserRole,- canManageCalendar,+ siteAdminCanManageCalendar,canAssignOrphanedCalendar,canViewAuditLogs,canDeleteAuditLogs,@@ -130,7 +130,10 @@ export function useCanChangeUserRole(*/export function useCanManageCalendar(operation: "view" | "delete"): boolean {const { user } = useAuth();- return useMemo(() => canManageCalendar(user, operation), [user, operation]);+ return useMemo(+ () => siteAdminCanManageCalendar(user, operation),+ [user, operation]+ );}/**diff --git a/hooks/useAdminCalendars.ts b/hooks/useAdminCalendars.tsindex 3b4595c..fad4033 100644--- a/hooks/useAdminCalendars.ts+++ b/hooks/useAdminCalendars.ts@@ -23,6 +23,10 @@ import {run,useAdminErrorToast,} from "@/hooks/useAdminList";+import type { BundleOption } from "@/components/permission-bundle-picker";+import type { BundleRef } from "@/lib/permission-bundles";++export type { BundleRef };/*** Calendar Owner Info@@ -40,7 +44,7 @@ export interface AdminCalendar {id: string;name: string;color: string;- guestPermission: "none" | "read" | "write";+ guestBundle: BundleRef | null;createdAt: Date;updatedAt: Date;owner: CalendarOwner | null;@@ -61,12 +65,12 @@ export interface CalendarDetails extends AdminCalendar {userName: string;userEmail: string;userImage: string | null;- permission: string;+ bundle: BundleRef;}>;shareTokens: Array<{id: string;name: string;- permission: string;+ bundle: BundleRef;createdAt: Date;}>;externalSyncs: Array<{@@ -118,12 +122,40 @@ export async function fetchAdminCalendarDetails(};}+/**+ * Lists a calendar's permission bundles for the admin panel's guest-access+ * picker (read-only — bundle content editing stays owner-only, Paket 6).+ */+async function fetchAdminCalendarBundles(+ calendarId: string,+): Promise<BundleOption[]> {+ const response = await fetch(`/api/admin/calendars/${calendarId}/bundles`);+ if (!response.ok) throw new AdminRequestError(response.status);++ const data: BundleOption[] = await response.json();+ return data.map((bundle) => ({+ id: bundle.id,+ name: bundle.name,+ seedKey: bundle.seedKey,+ capabilities: bundle.capabilities,+ }));+}++/** Fetches only while `enabled` (typically the owning sheet's `open` state). */+export function useAdminCalendarBundles(calendarId: string, enabled: boolean) {+ return useQuery({+ queryKey: queryKeys.admin.calendars.bundles(calendarId),+ queryFn: () => fetchAdminCalendarBundles(calendarId),+ enabled: enabled && !!calendarId,+ });+}+/*** Update calendar via API*/async function updateCalendarApi(calendarId: string,- updates: { name?: string; color?: string; guestPermission?: AdminCalendar["guestPermission"] },+ updates: { name?: string; color?: string; guestBundleId?: string | null },): Promise<void> {const response = await fetch(`/api/admin/calendars/${calendarId}`, {method: "PATCH",@@ -263,11 +295,22 @@ export function useAdminCalendarActions() {updates,}: {calendarId: string;- updates: { name?: string; color?: string; guestPermission?: AdminCalendar["guestPermission"] };+ updates: { name?: string; color?: string; guestBundleId?: string | null };}) => updateCalendarApi(calendarId, updates),+ // guestBundleId isn't optimistically reflected: the list shows the guest+ // bundle's {id, name, seedKey}, not the raw id the PATCH body carries, so+ // it just waits for onSettled's invalidation like the rest of the app.onMutate: async ({ calendarId, updates }) => ({snapshot: await patchCalendars((calendars) =>- calendars.map((cal) => (cal.id === calendarId ? { ...cal, ...updates } : cal)),+ calendars.map((cal) =>+ cal.id === calendarId+ ? {+ ...cal,+ ...(updates.name !== undefined ? { name: updates.name } : {}),+ ...(updates.color !== undefined ? { color: updates.color } : {}),+ }+ : cal,+ ),),}),onError: (err, variables, context) => {@@ -355,7 +398,7 @@ export function useAdminCalendarActions() {isTransferring: transferMutation.isPending || bulkTransferMutation.isPending,updateCalendar: (calendarId: string,- updates: { name?: string; color?: string; guestPermission?: AdminCalendar["guestPermission"] },+ updates: { name?: string; color?: string; guestBundleId?: string | null },) => run(updateMutation.mutateAsync, { calendarId, updates }),deleteCalendar: (calendarId: string) => run(deleteMutation.mutateAsync, calendarId),transferCalendar: (calendarId: string, newOwnerId: string) =>diff --git a/hooks/useAdminUsers.ts b/hooks/useAdminUsers.tsindex bb2a0b6..a142d7a 100644--- a/hooks/useAdminUsers.ts+++ b/hooks/useAdminUsers.ts@@ -24,6 +24,7 @@ import {run,useAdminErrorToast,} from "@/hooks/useAdminList";+import type { BundleRef } from "@/hooks/useAdminCalendars";/*** Extended User Type with Admin-specific fields@@ -56,7 +57,7 @@ export interface UserDetails extends AdminUser {sharedCalendars: Array<{id: string;name: string;- permission: string;+ bundle: BundleRef;}>;}diff --git a/hooks/useCalendarBundles.ts b/hooks/useCalendarBundles.tsnew file mode 100644index 0000000..ef8e254--- /dev/null+++ b/hooks/useCalendarBundles.ts@@ -0,0 +1,387 @@+import { useQuery, 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 { normalizeCapabilities, type BundleSeedKey, type Capability } from "@/lib/permission-bundles";+import { isRateLimitError, handleRateLimitError } from "@/lib/rate-limit-client";++export interface PermissionBundleUsage {+ shareCount: number;+ tokenCount: number;+ isGuestBundle: boolean;+}++export interface PermissionBundle {+ id: string;+ calendarId: string;+ name: string;+ seedKey: BundleSeedKey | null;+ capabilities: Capability[];+ createdAt: string;+ updatedAt: string;+}++export interface PermissionBundleWithUsage extends PermissionBundle {+ usage: PermissionBundleUsage;+}++/** Carries the service layer's error detail (forbidden capabilities, usage counts) alongside the HTTP status. */+export class PermissionBundleApiError extends ApiError {+ constructor(+ message: string,+ status: number,+ public readonly details?: unknown+ ) {+ super(message, status);+ this.name = "PermissionBundleApiError";+ }+}++/** Thrown instead of PermissionBundleApiError 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 PermissionBundleApiError(+ body.error || fallback,+ response.status,+ body.details+ );+}++async function fetchBundlesApi(+ calendarId: string+): Promise<PermissionBundleWithUsage[]> {+ const response = await fetch(`/api/calendars/${calendarId}/bundles`);+ if (!response.ok) {+ return parseErrorResponse(response, "Failed to fetch permission bundles");+ }+ return response.json();+}++async function createBundleApi(+ calendarId: string,+ input: { name: string; capabilities: Capability[] }+): Promise<PermissionBundle> {+ const response = await fetch(`/api/calendars/${calendarId}/bundles`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(input),+ });+ if (!response.ok) {+ return parseErrorResponse(response, "Failed to create permission bundle");+ }+ return response.json();+}++async function updateBundleApi(+ calendarId: string,+ bundleId: string,+ input: { name?: string; capabilities?: Capability[] }+): Promise<PermissionBundle> {+ const response = await fetch(+ `/api/calendars/${calendarId}/bundles/${bundleId}`,+ {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(input),+ }+ );+ if (!response.ok) {+ return parseErrorResponse(response, "Failed to update permission bundle");+ }+ return response.json();+}++async function deleteBundleApi(+ calendarId: string,+ bundleId: string+): Promise<void> {+ const response = await fetch(+ `/api/calendars/${calendarId}/bundles/${bundleId}`,+ { method: "DELETE" }+ );+ if (!response.ok) {+ return parseErrorResponse(response, "Failed to delete permission bundle");+ }+}++async function cloneBundleApi(+ calendarId: string,+ bundleId: string,+ name: string+): Promise<PermissionBundle> {+ const response = await fetch(+ `/api/calendars/${calendarId}/bundles/${bundleId}/clone`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name }),+ }+ );+ if (!response.ok) {+ return parseErrorResponse(response, "Failed to clone permission bundle");+ }+ return response.json();+}++interface MutationContext {+ previous?: PermissionBundleWithUsage[];+}++const EMPTY_USAGE: PermissionBundleUsage = {+ shareCount: 0,+ tokenCount: 0,+ isGuestBundle: false,+};++/** create/update/clone all 409 only on a name collision (delete's 409 carries `details.usage` instead). */+function isNameConflict(err: unknown): boolean {+ return (+ err instanceof PermissionBundleApiError &&+ err.status === 409 &&+ !(err.details && typeof err.details === "object" && "usage" in err.details)+ );+}++/**+ * CRUD for a calendar's permission bundles (Stufe 2, 7.3), optimistic per the+ * onMutate/onError/onSettled pattern in hooks/useShifts.ts. Every mutation+ * also invalidates queryKeys.calendars.all — a bundle's capabilities can+ * change what every holder of it is effectively allowed to do.+ */+export function useCalendarBundles(calendarId: string | undefined) {+ const t = useTranslations();+ const queryClient = useQueryClient();+ const queryKey = queryKeys.permissionBundles.byCalendar(calendarId!);++ const { data: bundles = [], isLoading, isError } = useQuery({+ queryKey,+ queryFn: () => fetchBundlesApi(calendarId!),+ enabled: !!calendarId,+ });++ const invalidate = () => {+ queryClient.invalidateQueries({ queryKey });+ queryClient.invalidateQueries({ queryKey: queryKeys.calendars.all });+ };++ const rollback = (context?: MutationContext) => {+ if (context?.previous) queryClient.setQueryData(queryKey, context.previous);+ };++ const buildOptimisticBundle = (+ name: string,+ capabilities: Capability[]+ ): PermissionBundleWithUsage => ({+ id: `temp-${generateTempId()}`,+ calendarId: calendarId!,+ name,+ seedKey: null,+ capabilities,+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ usage: EMPTY_USAGE,+ });++ const createMutation = useMutation<+ PermissionBundle,+ Error,+ { name: string; capabilities: Capability[] },+ MutationContext+ >({+ mutationFn: (input) => createBundleApi(calendarId!, input),+ onMutate: async (input) => {+ await queryClient.cancelQueries({ queryKey });+ const previous = queryClient.getQueryData<PermissionBundleWithUsage[]>(queryKey);+ const optimistic = buildOptimisticBundle(+ input.name,+ normalizeCapabilities(input.capabilities)+ );+ queryClient.setQueryData<PermissionBundleWithUsage[]>(queryKey, (old = []) => [+ ...old,+ optimistic,+ ]);+ return { previous };+ },+ onError: async (err, _input, context) => {+ rollback(context);+ console.error("Failed to create permission bundle:", err);+ if (err instanceof RateLimitError) {+ await handleRateLimitError(err.response, t);+ return;+ }+ toast.error(+ isNameConflict(err)+ ? t("permissionBundles.nameTaken")+ : t("common.createError", { item: t("permissionBundles.bundle") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.created", { item: t("permissionBundles.bundle") }));+ },+ onSettled: invalidate,+ });++ const updateMutation = useMutation<+ PermissionBundle,+ Error,+ { bundleId: string; name?: string; capabilities?: Capability[] },+ MutationContext+ >({+ mutationFn: ({ bundleId, ...input }) =>+ updateBundleApi(calendarId!, bundleId, input),+ onMutate: async ({ bundleId, ...input }) => {+ await queryClient.cancelQueries({ queryKey });+ const previous = queryClient.getQueryData<PermissionBundleWithUsage[]>(queryKey);+ queryClient.setQueryData<PermissionBundleWithUsage[]>(queryKey, (old = []) =>+ old.map((b) =>+ b.id === bundleId+ ? {+ ...b,+ ...(input.name !== undefined ? { name: input.name, seedKey: null } : {}),+ ...(input.capabilities !== undefined+ ? { capabilities: normalizeCapabilities(input.capabilities) }+ : {}),+ updatedAt: new Date().toISOString(),+ }+ : b+ )+ );+ return { previous };+ },+ onError: async (err, _variables, context) => {+ rollback(context);+ console.error("Failed to update permission bundle:", err);+ if (err instanceof RateLimitError) {+ await handleRateLimitError(err.response, t);+ return;+ }+ toast.error(+ isNameConflict(err)+ ? t("permissionBundles.nameTaken")+ : t("common.updateError", { item: t("permissionBundles.bundle") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.updated", { item: t("permissionBundles.bundle") }));+ },+ onSettled: invalidate,+ });++ const deleteMutation = useMutation<void, Error, string, MutationContext>({+ mutationFn: (bundleId) => deleteBundleApi(calendarId!, bundleId),+ onMutate: async (bundleId) => {+ await queryClient.cancelQueries({ queryKey });+ const previous = queryClient.getQueryData<PermissionBundleWithUsage[]>(queryKey);+ queryClient.setQueryData<PermissionBundleWithUsage[]>(queryKey, (old = []) =>+ old.filter((b) => b.id !== bundleId)+ );+ return { previous };+ },+ onError: async (err, _bundleId, context) => {+ rollback(context);+ console.error("Failed to delete permission bundle:", err);+ if (err instanceof RateLimitError) {+ await handleRateLimitError(err.response, t);+ return;+ }+ if (+ err instanceof PermissionBundleApiError &&+ err.status === 409 &&+ err.details &&+ typeof err.details === "object" &&+ "usage" in err.details+ ) {+ const usage = (err.details as { usage: PermissionBundleUsage }).usage;+ const parts = [+ usage.shareCount > 0 &&+ t("permissionBundles.usageShares", { count: usage.shareCount }),+ usage.tokenCount > 0 &&+ t("permissionBundles.usageTokens", { count: usage.tokenCount }),+ usage.isGuestBundle && t("permissionBundles.usageGuestAccess"),+ ].filter(Boolean);+ toast.error(t("permissionBundles.deleteInUse", { usage: parts.join(", ") }));+ return;+ }+ toast.error(t("common.deleteError", { item: t("permissionBundles.bundle") }));+ },+ onSuccess: () => {+ toast.success(t("common.deleted", { item: t("permissionBundles.bundle") }));+ },+ onSettled: invalidate,+ });++ // Cloning creates a new, independent bundle — same optimistic shape as+ // create, no rollback of the source bundle needed.+ const cloneMutation = useMutation<+ PermissionBundle,+ Error,+ { bundleId: string; name: string },+ MutationContext+ >({+ mutationFn: ({ bundleId, name }) => cloneBundleApi(calendarId!, bundleId, name),+ onMutate: async ({ bundleId, name }) => {+ await queryClient.cancelQueries({ queryKey });+ const previous = queryClient.getQueryData<PermissionBundleWithUsage[]>(queryKey);+ const source = previous?.find((b) => b.id === bundleId);+ const optimistic = buildOptimisticBundle(name, source?.capabilities ?? []);+ queryClient.setQueryData<PermissionBundleWithUsage[]>(queryKey, (old = []) => [+ ...old,+ optimistic,+ ]);+ return { previous };+ },+ onError: async (err, _variables, context) => {+ rollback(context);+ console.error("Failed to clone permission bundle:", err);+ if (err instanceof RateLimitError) {+ await handleRateLimitError(err.response, t);+ return;+ }+ toast.error(+ isNameConflict(err)+ ? t("permissionBundles.nameTaken")+ : t("common.createError", { item: t("permissionBundles.bundle") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.created", { item: t("permissionBundles.bundle") }));+ },+ onSettled: invalidate,+ });++ return {+ bundles,+ loading: isLoading,+ /** The list fetch itself failed (e.g. a manageGuestAccess-only user against a manageShares-gated route) — callers must not render bundle pickers/editors as if `bundles` were a legitimate empty list. */+ isError,+ createBundle: (input: { name: string; capabilities: Capability[] }) =>+ createMutation.mutateAsync(input),+ updateBundle: (+ bundleId: string,+ input: { name?: string; capabilities?: Capability[] }+ ) => updateMutation.mutateAsync({ bundleId, ...input }),+ deleteBundle: (bundleId: string) => deleteMutation.mutateAsync(bundleId),+ cloneBundle: (bundleId: string, name: string) =>+ cloneMutation.mutateAsync({ bundleId, name }),+ isMutating:+ createMutation.isPending ||+ updateMutation.isPending ||+ deleteMutation.isPending ||+ cloneMutation.isPending,+ };+}diff --git a/hooks/useCalendarPermission.ts b/hooks/useCalendarPermission.tsindex 9acaa56..13a35bb 100644--- a/hooks/useCalendarPermission.ts+++ b/hooks/useCalendarPermission.ts@@ -5,32 +5,43 @@ import { useAuth } from "@/hooks/useAuth";import { useCalendars } from "@/hooks/useCalendars";import { CalendarWithCount } from "@/lib/types";import { usePublicConfig } from "@/hooks/usePublicConfig";-import type { CalendarPermission } from "@/lib/auth/permissions";+import { type Capability } from "@/lib/permission-bundles";++export interface CalendarPermission {+ isOwner: boolean;+ /** Whether the caller may perform a specific capability on the calendar — mirrors CalendarAccess.can() server-side. */+ can(capability: Capability): boolean;+ /** Whether the caller may act on a resource given its own/any capabilities and creator — mirrors CalendarAccess.canOwned() server-side (E1/E8). */+ canOwned(own: Capability, any: Capability, createdBy: string | null): boolean;+ /** Owner-only — deletion of the calendar itself, not a resource on it. */+ canDelete: boolean;+}++const NO_ACCESS: CalendarPermission = {+ isOwner: false,+ can: () => false,+ canOwned: () => false,+ canDelete: false,+};/**- * Hook to check calendar permissions client-side+ * Hook to check calendar permissions client-side.*- * Returns permission helpers for the given calendar.- * Takes into account:- * - User authentication status- * - Calendar ownership- * - Guest permissions (if user is guest)+ * Mirrors lib/auth/permissions.ts's getCalendarAccess() using the effective+ * `capabilities` the calendar list API already resolved for the caller+ * (share > token > subscribed guest bundle priority, ceiling-filtered) —+ * this hook does no permission resolution of its own.*- * Accepts either a calendar object or a calendar ID string.- * If a string is provided, it will look up the calendar from the calendars list.+ * Accepts either a calendar object or a calendar ID string. If a string is+ * provided, it will look up the calendar from the calendars list.** @example- * // With calendar object- * const { canEdit, canView, canManage, isReadOnly } = useCalendarPermission(calendar);- *- * // With calendar ID- * const { canEdit, canView, canManage, isReadOnly } = useCalendarPermission(calendarId);- *- * if (!canEdit) return <ReadOnlyBanner />;+ * const { can, canOwned } = useCalendarPermission(calendarId);+ * if (!canOwned("editOwnShift", "editAnyShift", shift.createdBy)) return;*/export function useCalendarPermission(calendarOrId?: CalendarWithCount | string | null-) {+): CalendarPermission {const { user, isGuest } = useAuth();const { calendars } = useCalendars();const { auth } = usePublicConfig();@@ -44,192 +55,35 @@ export function useCalendarPermission(return calendarOrId;}, [calendarOrId, calendars]);- const permission = useMemo(() => {- if (!calendar) {- return {- level: "none" as const,- canView: false,- canEdit: false,- canManage: false,- canDelete: false,- canShare: false,- isReadOnly: true,- isOwner: false,- };- }-- // If auth is disabled, grant full owner access (backwards compatibility)- if (!auth.enabled) {- return {- level: "owner" as const,- canView: true,- canEdit: true,- canManage: true,- canDelete: true,- canShare: true,- isReadOnly: false,- isOwner: true,- };- }-- // If user is authenticated- if (user) {- // User is owner- if (calendar.ownerId === user.id) {- return {- level: "owner" as const,- canView: true,- canEdit: true,- canManage: true,- canDelete: true,- canShare: true,- isReadOnly: false,- isOwner: true,- };- }-- // Check if user has explicit share permission- const sharePermission = (calendar as { sharePermission?: string })- .sharePermission;- if (sharePermission) {- const isOwner = sharePermission === "owner";- const isAdmin = sharePermission === "admin";- const isWrite = sharePermission === "write";- const isRead = sharePermission === "read";-- return {- level: sharePermission,- canView: true,- canEdit: isOwner || isAdmin || isWrite,- canManage: isOwner || isAdmin,- canDelete: isOwner,- canShare: isOwner || isAdmin,- isReadOnly: isRead,- isOwner: isOwner,- };- }-- // Check if user has token-based access- const tokenPermission = (- calendar as { tokenPermission?: "read" | "write" }- ).tokenPermission;- if (tokenPermission) {- return {- level: tokenPermission,- canView: true,- canEdit: tokenPermission === "write",- canManage: false,- canDelete: false,- canShare: false,- isReadOnly: tokenPermission === "read",- isOwner: false,- };- }-- // Check if calendar is public (guest permission) and user is subscribed- // In this case, user gets the guest permission level- const isSubscribed = (calendar as { isSubscribed?: boolean })- .isSubscribed;- if (isSubscribed && calendar.guestPermission !== "none") {- const guestPerm = calendar.guestPermission as CalendarPermission;- return {- level: guestPerm,- canView: true,- canEdit: guestPerm === "write",- canManage: false,- canDelete: false,- canShare: false,- isReadOnly: guestPerm === "read",- isOwner: false,- };- }-- // User has no access to this calendar- return {- level: "none" as const,- canView: false,- canEdit: false,- canManage: false,- canDelete: false,- canShare: false,- isReadOnly: true,- isOwner: false,- };- }-- // If user is guest (not authenticated)- if (isGuest) {- // Check for token-based access first (higher priority)- const tokenPermission = (- calendar as { tokenPermission?: "read" | "write" }- ).tokenPermission;- if (tokenPermission) {- return {- level: tokenPermission,- canView: true,- canEdit: tokenPermission === "write",- canManage: false,- canDelete: false,- canShare: false,- isReadOnly: tokenPermission === "read",- isOwner: false,- };- }-- // Then check guest permission- const guestPerm = calendar.guestPermission || "none";-- if (guestPerm === "write") {- return {- level: "write" as const,- canView: true,- canEdit: true,- canManage: false,- canDelete: false,- canShare: false,- isReadOnly: false,- isOwner: false,- };- }-- if (guestPerm === "read") {- return {- level: "read" as const,- canView: true,- canEdit: false,- canManage: false,- canDelete: false,- canShare: false,- isReadOnly: true,- isOwner: false,- };- }-- // guestPerm === "none"- return {- level: "none" as const,- canView: false,- canEdit: false,- canManage: false,- canDelete: false,- canShare: false,- isReadOnly: true,- isOwner: false,- };- }+ return useMemo(() => {+ if (!calendar) return NO_ACCESS;+ // Auth disabled grants full owner access to everyone regardless of+ // user/isGuest, which otherwise both stay false in that mode.+ if (auth.enabled && !user && !isGuest) return NO_ACCESS;++ const isOwner = !auth.enabled || calendar.ownerId === user?.id;+ const capabilities = calendar.capabilities ?? [];+ const userId = user?.id ?? null;++ const can = (capability: Capability): boolean =>+ isOwner || capabilities.includes(capability);++ const canOwned = (+ own: Capability,+ any: Capability,+ createdBy: string | null+ ): boolean => {+ if (isOwner) return true;+ if (can(any)) return true;+ if (!can(own)) return false;+ return createdBy === null || createdBy === userId;+ };- // No user, no guest accessreturn {- level: "none" as const,- canView: false,- canEdit: false,- canManage: false,- canDelete: false,- canShare: false,- isReadOnly: true,- isOwner: false,+ isOwner,+ can,+ canOwned,+ canDelete: isOwner,};}, [calendar, user, isGuest, auth.enabled]);-- return permission;}diff --git a/hooks/useCalendarShares.ts b/hooks/useCalendarShares.tsindex e35e9dc..f58b1b6 100644--- a/hooks/useCalendarShares.ts+++ b/hooks/useCalendarShares.ts@@ -12,12 +12,14 @@ import {import { ApiError } from "@/lib/api-error";import { generateTempId } from "@/lib/utils";import { useIsCalendarAccessible } from "@/hooks/useCalendars";+import type { BundleRef } from "@/lib/permission-bundles";export interface CalendarShare {id: string;calendarId: string;userId: string;- permission: "owner" | "admin" | "write" | "read";+ bundleId: string;+ bundle: BundleRef;sharedBy: string;createdAt: Date;user: {@@ -40,6 +42,11 @@ export interface SearchUser {image: string | null;}+/** Optimistic placeholder for a bundle reference — settles once the real response/refetch lands. */+function placeholderBundle(bundleId: string): BundleRef {+ return { id: bundleId, name: "…", seedKey: null };+}+/*** Fetch calendar shares from API*/@@ -65,12 +72,12 @@ async function fetchSharesApi(calendarId: string): Promise<CalendarShare[]> {async function addShareApi(calendarId: string,userId: string,- permission: "admin" | "write" | "read"+ bundleId: string): Promise<CalendarShare> {const response = await fetch(`/api/calendars/${calendarId}/shares`, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ userId, permission }),+ body: JSON.stringify({ userId, bundleId }),});if (!response.ok) {@@ -87,19 +94,19 @@ async function addShareApi(}/**- * Update a share's permission via API+ * Update a share's bundle via API*/async function updateShareApi(calendarId: string,shareId: string,- permission: "admin" | "write" | "read"+ bundleId: string): Promise<CalendarShare> {const response = await fetch(`/api/calendars/${calendarId}/shares/${shareId}`,{method: "PUT",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ permission }),+ body: JSON.stringify({ bundleId }),});@@ -171,12 +178,12 @@ export function useCalendarShares(calendarId: string) {const addShareMutation = useMutation({mutationFn: ({userId,- permission,+ bundleId,}: {userId: string;- permission: "admin" | "write" | "read";- }) => addShareApi(calendarId, userId, permission),- onMutate: async ({ userId, permission }) => {+ bundleId: string;+ }) => addShareApi(calendarId, userId, bundleId),+ onMutate: async ({ userId, bundleId }) => {await queryClient.cancelQueries({queryKey: queryKeys.shares.byCalendar(calendarId),});@@ -184,12 +191,14 @@ export function useCalendarShares(calendarId: string) {queryKeys.shares.byCalendar(calendarId));- // Optimistic update+ // Optimistic update — the bundle's name/seedKey are filled in once the+ // real response/refetch lands, a brief "…" is an acceptable approximation.const optimisticShare: CalendarShare = {id: `temp-${generateTempId()}`,calendarId,userId,- permission,+ bundleId,+ bundle: placeholderBundle(bundleId),sharedBy: "current-user",createdAt: new Date(),user: {@@ -237,12 +246,12 @@ export function useCalendarShares(calendarId: string) {const updateShareMutation = useMutation({mutationFn: ({shareId,- permission,+ bundleId,}: {shareId: string;- permission: "admin" | "write" | "read";- }) => updateShareApi(calendarId, shareId, permission),- onMutate: async ({ shareId, permission }) => {+ bundleId: string;+ }) => updateShareApi(calendarId, shareId, bundleId),+ onMutate: async ({ shareId, bundleId }) => {await queryClient.cancelQueries({queryKey: queryKeys.shares.byCalendar(calendarId),});@@ -250,11 +259,15 @@ export function useCalendarShares(calendarId: string) {queryKeys.shares.byCalendar(calendarId));- // Optimistic update+ // Optimistic update — bundle name/seedKey settle once the refetch lands.queryClient.setQueryData(queryKeys.shares.byCalendar(calendarId),(old: CalendarShare[] = []) =>- old.map((s) => (s.id === shareId ? { ...s, permission } : s))+ old.map((s) =>+ s.id === shareId+ ? { ...s, bundleId, bundle: placeholderBundle(bundleId) }+ : s+ ));return { previous };@@ -357,10 +370,10 @@ export function useCalendarShares(calendarId: string) {searchLoading,addShare: async (userId: string,- permission: "admin" | "write" | "read"+ bundleId: string): Promise<{ success: boolean }> => {try {- await addShareMutation.mutateAsync({ userId, permission });+ await addShareMutation.mutateAsync({ userId, bundleId });return { success: true };} catch {return { success: false };@@ -368,10 +381,10 @@ export function useCalendarShares(calendarId: string) {},updateShare: async (shareId: string,- permission: "admin" | "write" | "read"+ bundleId: string): Promise<{ success: boolean }> => {try {- await updateShareMutation.mutateAsync({ shareId, permission });+ await updateShareMutation.mutateAsync({ shareId, bundleId });return { success: true };} catch {return { success: false };diff --git a/hooks/useCalendarSubscriptions.ts b/hooks/useCalendarSubscriptions.tsindex ea332c8..4f55cfb 100644--- a/hooks/useCalendarSubscriptions.ts+++ b/hooks/useCalendarSubscriptions.ts@@ -6,6 +6,7 @@ import { useTranslations } from "next-intl";import { queryKeys } from "@/lib/query-keys";import { BACKGROUND_REFETCH_INTERVAL } from "@/lib/query-client";import { ApiError } from "@/lib/api-error";+import type { BundleRef, Capability } from "@/lib/permission-bundles";type CalendarSource = "guest" | "shared";@@ -13,8 +14,11 @@ export type AvailableCalendar = {id: string;name: string;color: string;- guestPermission: string;- permission?: string; // For shared calendars: actual share permission (owner/admin/write/read)+ // Effective (ceiling-filtered) capabilities the caller would get, and the+ // bundle behind them — see previewGuestCapabilities()/getEffectiveAccessSummary()+ // in app/api/calendars/subscriptions/route.ts.+ capabilities: Capability[];+ bundle: BundleRef | null;owner: {id: string;name: string;@@ -27,7 +31,8 @@ export type DismissedCalendar = {id: string;name: string;color: string;- permission: string;+ capabilities: Capability[];+ bundle: BundleRef | null;owner: {id: string;name: string;@@ -157,8 +162,8 @@ export function useCalendarSubscriptions(enabled = true) {id: dismissedCal.id,name: dismissedCal.name,color: dismissedCal.color,- guestPermission: dismissedCal.permission,- permission: dismissedCal.permission,+ capabilities: dismissedCal.capabilities,+ bundle: dismissedCal.bundle,owner: dismissedCal.owner,source: dismissedCal.source,isSubscribed: true,@@ -226,7 +231,8 @@ export function useCalendarSubscriptions(enabled = true) {id: calendar.id,name: calendar.name,color: calendar.color,- permission: calendar.permission || calendar.guestPermission,+ capabilities: calendar.capabilities,+ bundle: calendar.bundle,owner: calendar.owner,source: calendar.source,},diff --git a/hooks/useCalendarTokens.ts b/hooks/useCalendarTokens.tsindex 9fe9b1e..d14972c 100644--- a/hooks/useCalendarTokens.ts+++ b/hooks/useCalendarTokens.ts@@ -8,13 +8,15 @@ import { queryKeys } from "@/lib/query-keys";import { BACKGROUND_REFETCH_INTERVAL } from "@/lib/query-client";import { ApiError } from "@/lib/api-error";import { useIsCalendarAccessible } from "@/hooks/useCalendars";+import type { BundleRef } from "@/lib/permission-bundles";export interface CalendarAccessToken {id: string;tokenPreview: string; // First 6 chars (e.g., "abcxyz")token?: string; // Full token only provided on creationname: string | null;- permission: "read" | "write";+ bundleId: string;+ bundle: BundleRef | null;expiresAt: string | null;createdBy: string;createdAt: string;@@ -25,7 +27,7 @@ export interface CalendarAccessToken {export interface CreateTokenParams {name?: string;- permission: "read" | "write";+ bundleId: string;expiresAt?: string | null;}@@ -96,7 +98,7 @@ async function createTokenApi(async function updateTokenApi(calendarId: string,tokenId: string,- updates: { isActive?: boolean }+ updates: { isActive?: boolean; bundleId?: string }): Promise<CalendarAccessToken> {const response = await fetch(`/api/calendars/${calendarId}/tokens/${tokenId}`,@@ -199,7 +201,7 @@ export function useCalendarTokens(calendarId: string | null) {updates,}: {tokenId: string;- updates: { isActive?: boolean };+ updates: { isActive?: boolean; bundleId?: string };}) => updateTokenApi(calendarId!, tokenId, updates),onMutate: async ({ tokenId, updates }) => {await queryClient.cancelQueries({@@ -326,7 +328,7 @@ export function useCalendarTokens(calendarId: string | null) {},updateToken: async (tokenId: string,- updates: { isActive?: boolean }+ updates: { isActive?: boolean; bundleId?: string }): Promise<boolean> => {if (!calendarId) return false;try {diff --git a/hooks/useCalendars.ts b/hooks/useCalendars.tsindex a98147a..3b77b72 100644--- a/hooks/useCalendars.ts+++ b/hooks/useCalendars.ts@@ -21,9 +21,9 @@ import { ApiError } from "@/lib/api-error";export interface CalendarUpdateInput {name?: string;color?: string;- guestPermission?: "none" | "read" | "write";+ /** null = no guest access. Must be a guest-eligible bundle id (E7), enforced server-side. */+ guestBundleId?: string | null;viewSettings?: CalendarViewSettings | null;- allowSelfSignup?: boolean;signupsEnabled?: boolean;}@@ -54,11 +54,7 @@ async function createCalendarApi(const response = await fetch("/api/calendars", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({- name,- color,- guestPermission: "none",- }),+ body: JSON.stringify({ name, color }),});// Check for rate-limit error first@@ -177,7 +173,7 @@ export function useCalendars(initialCalendarId?: string | null) {}, [selectedCalendar]);// Access can disappear while the app is open: a dismissed subscription, a- // withdrawn share, guestPermission set to none, an expired token. The id would+ // withdrawn share, guest access turned off, an expired token. The id would// otherwise stick and every per-calendar query would keep asking for it.useEffect(() => {if (!isFetched || isFetching || !selectedCalendar || mutating > 0) return;@@ -211,7 +207,6 @@ export function useCalendars(initialCalendarId?: string | null) {id: `temp-${generateTempId()}`,name,color,- guestPermission: "none",ownerId: null,createdAt: new Date(),updatedAt: new Date(),diff --git a/hooks/useNotes.ts b/hooks/useNotes.tsindex 3b91fb5..4765111 100644--- a/hooks/useNotes.ts+++ b/hooks/useNotes.ts@@ -161,6 +161,7 @@ export function useNotes(calendarId: string | undefined) {recurringPattern: formData.recurringPattern || "none",recurringInterval: formData.recurringInterval ?? null,calendarId: calendarId!,+ createdBy: null,createdAt: new Date(),updatedAt: new Date(),};diff --git a/hooks/usePermissionBundleForm.ts b/hooks/usePermissionBundleForm.tsnew file mode 100644index 0000000..bc0de0c--- /dev/null+++ b/hooks/usePermissionBundleForm.ts@@ -0,0 +1,56 @@+"use client";++import { useState } from "react";+import {+ normalizeCapabilities,+ type Capability,+} from "@/lib/permission-bundles";+import type { PermissionBundleWithUsage } from "@/hooks/useCalendarBundles";++function sameCapabilities(a: Capability[], b: Capability[]): boolean {+ if (a.length !== b.length) return false;+ const setB = new Set(b);+ return a.every((c) => setB.has(c));+}++/** Draft state for editing one bundle's name/capabilities (Gruppen tab). Instantiate keyed by bundle.id. */+export function usePermissionBundleForm(bundle: PermissionBundleWithUsage) {+ const [name, setName] = useState(bundle.name);+ const [capabilities, setCapabilities] = useState<Capability[]>(bundle.capabilities);++ // E7: a bundle reachable by a guest/link source can't hold admin-only capabilities.+ const isGuestBound = bundle.usage.isGuestBundle || bundle.usage.tokenCount > 0;++ // S4: "only stamp presets" is bypassable by creating an arbitrary preset first.+ const stampPresetBypassWarning =+ capabilities.includes("stampPreset") &&+ !capabilities.includes("createShift") &&+ capabilities.includes("createPreset");++ const toggle = (capability: Capability, checked: boolean) => {+ const next = checked+ ? [...capabilities, capability]+ : capabilities.filter((c) => c !== capability);+ // S3: dependencies are re-applied on every toggle so they stay visibly ticked.+ setCapabilities(normalizeCapabilities(next));+ };++ const dirty =+ name.trim() !== bundle.name || !sameCapabilities(capabilities, bundle.capabilities);++ const reset = () => {+ setName(bundle.name);+ setCapabilities(bundle.capabilities);+ };++ return {+ name,+ setName,+ capabilities,+ toggle,+ dirty,+ isGuestBound,+ stampPresetBypassWarning,+ reset,+ };+}diff --git a/hooks/useAccessLinkForm.ts b/hooks/usePermissionLinkForm.tssimilarity index 64%rename from hooks/useAccessLinkForm.tsrename to hooks/usePermissionLinkForm.tsindex 102cfdc..4d31252 100644--- a/hooks/useAccessLinkForm.ts+++ b/hooks/usePermissionLinkForm.ts@@ -1,16 +1,17 @@"use client";-import { useState } from "react";+import { useMemo, useState } from "react";import { useCalendarTokens } from "@/hooks/useCalendarTokens";+import { useCalendarBundles } from "@/hooks/useCalendarBundles";+import { isGuestEligible } from "@/lib/permission-bundles";export type LinkValidity = "1" | "7" | "30" | "never";-export type LinkPermission = "read" | "write";export interface CreatedAccessLink {token: string;link: string;name: string;- permission: LinkPermission;+ bundleId: string;validity: LinkValidity;}@@ -32,11 +33,16 @@ function expiryFor(validity: LinkValidity): Date | null {const DEFAULT_VALIDITY: LinkValidity = "7";/** Form state for creating an access link; the full token is only available right after creation. */-export function useAccessLinkForm(calendarId: string) {+export function usePermissionLinkForm(calendarId: string) {const { createToken, getShareLink } = useCalendarTokens(calendarId);+ const { bundles, isError: bundlesError } = useCalendarBundles(calendarId);+ const guestEligibleBundles = useMemo(+ () => bundles.filter((b) => isGuestEligible(b.capabilities)),+ [bundles]+ );const [name, setName] = useState("");- const [permission, setPermission] = useState<LinkPermission>("read");+ const [bundleId, setBundleId] = useState("");const [validity, setValidityState] = useState<LinkValidity>(DEFAULT_VALIDITY);const [expiresAt, setExpiresAt] = useState<Date | null>(() =>expiryFor(DEFAULT_VALIDITY)@@ -44,10 +50,19 @@ export function useAccessLinkForm(calendarId: string) {const [creating, setCreating] = useState(false);const [created, setCreated] = useState<CreatedAccessLink | null>(null);+ // A calendar's default seeded "Read" bundle is a sensible default once bundles+ // have loaded; falls back to the first guest-eligible bundle otherwise. Kept+ // as a derived value (not an effect) so an explicit pick always wins.+ const effectiveBundleId =+ bundleId ||+ guestEligibleBundles.find((b) => b.seedKey === "read")?.id ||+ guestEligibleBundles[0]?.id ||+ "";+// A created link counts as saved; the one-time token view is not unsaved input.const dirty =!created &&- (name.trim() !== "" || permission !== "read" || validity !== DEFAULT_VALIDITY);+ (name.trim() !== "" || bundleId !== "" || validity !== DEFAULT_VALIDITY);const setValidity = (value: LinkValidity) => {setValidityState(value);@@ -55,12 +70,13 @@ export function useAccessLinkForm(calendarId: string) {};const create = async () => {+ if (!effectiveBundleId) return;setCreating(true);// Recomputed so a form left open for a while still gets the full period.const expiry = expiryFor(validity);const result = await createToken({name: name.trim() || undefined,- permission,+ bundleId: effectiveBundleId,expiresAt: expiry?.toISOString() ?? null,});setCreating(false);@@ -70,7 +86,7 @@ export function useAccessLinkForm(calendarId: string) {token: result.token,link: getShareLink(result.token),name: name.trim(),- permission,+ bundleId: effectiveBundleId,validity,});}@@ -78,7 +94,7 @@ export function useAccessLinkForm(calendarId: string) {const reset = () => {setName("");- setPermission("read");+ setBundleId("");setValidity(DEFAULT_VALIDITY);setCreated(null);};@@ -86,8 +102,10 @@ export function useAccessLinkForm(calendarId: string) {return {name,setName,- permission,- setPermission,+ bundleId: effectiveBundleId,+ setBundleId,+ guestEligibleBundles,+ bundlesError,validity,setValidity,expiresAt,diff --git a/hooks/usePresets.ts b/hooks/usePresets.tsindex 83d2969..c28daf1 100644--- a/hooks/usePresets.ts+++ b/hooks/usePresets.ts@@ -117,6 +117,7 @@ function createOptimisticPreset(hideFromStats: formData.hideFromStats,defaultSignupCapacity: formData.defaultSignupCapacity ?? null,order: 999, // Will be corrected by server+ createdBy: null,createdAt: new Date(),updatedAt: new Date(),};diff --git a/hooks/useShiftSignups.ts b/hooks/useShiftSignups.tsindex 796196d..3f7f05f 100644--- a/hooks/useShiftSignups.ts+++ b/hooks/useShiftSignups.ts@@ -73,17 +73,14 @@ export function useShiftSignupPermission(calendarId: string | undefined) {const calendar = calendars.find((c) => c.id === calendarId);// Signups tie a shift to a real account, so without auth there is no one to sign up.const signupsEnabled = isAuthEnabled && (calendar?.signupsEnabled ?? true);- const allowSelfSignup = calendar?.allowSelfSignup ?? true;if (!user || !signupsEnabled) {return { canManageOwn: false, canManageOthers: false, signupsEnabled };}return {- canManageOwn:- calendarPermission.canView &&- (calendarPermission.canEdit || allowSelfSignup),- canManageOthers: calendarPermission.canEdit,+ canManageOwn: calendarPermission.can("signUpSelf"),+ canManageOthers: calendarPermission.can("signUpOthers"),signupsEnabled,};}diff --git a/hooks/useShiftStats.ts b/hooks/useShiftStats.tsindex e1774a5..90b9575 100644--- a/hooks/useShiftStats.ts+++ b/hooks/useShiftStats.ts@@ -78,6 +78,7 @@ export function useShiftStats({const {data: stats = null,isLoading: loading,+ error,refetch,} = useQuery({queryKey: queryKeys.stats.shifts(@@ -90,9 +91,12 @@ export function useShiftStats({refetchInterval: LIVE_REFETCH_INTERVAL,});+ const forbidden = error instanceof ApiError && error.status === 403;+return {stats,loading,+ forbidden,refetch,};}diff --git a/lib/admin-list.ts b/lib/admin-list.tsindex 471850f..ea90e2b 100644--- a/lib/admin-list.ts+++ b/lib/admin-list.ts@@ -69,7 +69,7 @@ export const CALENDAR_SORT_FIELDS = ["shiftsCount","sharesCount","externalSyncsCount",- "guestPermission",+ "guestBundle",] as const;export type CalendarContentFilter = (typeof CALENDAR_CONTENT_FILTERS)[number];diff --git a/lib/audit-log.ts b/lib/audit-log.tsindex c17f5f4..6b7872c 100644--- a/lib/audit-log.ts+++ b/lib/audit-log.ts@@ -71,14 +71,15 @@ export interface CalendarDeletedMetadata {export interface CalendarUpdatedMetadata {calendarName: string;- changes: string[]; // e.g., ["name", "color", "guestPermission", "viewSettings"]+ changes: string[]; // e.g., ["name", "color", "guestBundleId", "viewSettings"]viewSettings?: "enabled" | "updated" | "disabled";}export interface CalendarSharedMetadata {calendarName: string;sharedWith: string; // user email- permission: "read" | "write" | "admin";+ bundleId: string;+ bundleName: string;}export interface CalendarShareRemovedMetadata {@@ -90,14 +91,27 @@ export interface CalendarShareRemovedMetadata {export interface CalendarPermissionChangedMetadata {calendarName: string;user: string;- oldPermission: string;- newPermission: string;+ oldBundleId: string;+ oldBundleName: string;+ newBundleId: string;+ newBundleName: string;}-export interface CalendarGuestPermissionChangedMetadata {+export interface CalendarGuestBundleChangedMetadata {calendarName: string;- oldPermission: "none" | "read" | "write";- newPermission: "none" | "read" | "write";+ oldBundleId: string | null;+ oldBundleName: string | null;+ newBundleId: string | null;+ newBundleName: string | null;+}++export interface CalendarTokenCreatedMetadata {+ tokenId: string;+ tokenName: string;+ calendarName: string;+ bundleId: string;+ bundleName: string;+ expiresAt: string | null;}export interface SyncCreatedMetadata {@@ -154,6 +168,31 @@ export interface AdminUserCreateMetadata {createdBy: string;}+export interface CalendarBundleCreatedMetadata {+ calendarName: string;+ bundleName: string;+ capabilities: string[];+}++export interface CalendarBundleUpdatedMetadata {+ calendarName: string;+ bundleName: string;+ addedCapabilities: string[];+ removedCapabilities: string[];+ renamed?: { from: string; to: string };+}++export interface CalendarBundleClonedMetadata {+ calendarName: string;+ sourceBundleName: string;+ newBundleName: string;+}++export interface CalendarBundleDeletedMetadata {+ calendarName: string;+ bundleName: string;+}+// Union type for all metadataexport type AuditLogMetadata =| LoginFailedMetadata@@ -167,6 +206,8 @@ export type AuditLogMetadata =| CalendarSharedMetadata| CalendarShareRemovedMetadata| CalendarPermissionChangedMetadata+ | CalendarGuestBundleChangedMetadata+ | CalendarTokenCreatedMetadata| SyncCreatedMetadata| SyncDeletedMetadata| SyncExecutedMetadata@@ -175,7 +216,11 @@ export type AuditLogMetadata =| AdminUserCreateMetadata| AdminCalendarTransferMetadata| AdminPasswordResetMetadata- | AdminSystemSettingsUpdatedMetadata;+ | AdminSystemSettingsUpdatedMetadata+ | CalendarBundleCreatedMetadata+ | CalendarBundleUpdatedMetadata+ | CalendarBundleClonedMetadata+ | CalendarBundleDeletedMetadata;// =====================================================// Audit Log Typesdiff --git a/lib/auth/admin.ts b/lib/auth/admin.tsindex b896cc2..0db16f6 100644--- a/lib/auth/admin.ts+++ b/lib/auth/admin.ts@@ -222,7 +222,7 @@ export function canResetPassword(* @param operation - The operation being performed ('view' or 'delete')* @returns boolean - true if admin can perform the operation*/-export function canManageCalendar(+export function siteAdminCanManageCalendar(adminUser: User | null | undefined,operation: "view" | "delete"): boolean {@@ -245,7 +245,7 @@ export function canManageCalendar(* @param adminUser - The admin performing the action* @returns boolean - true if admin can edit calendars*/-export function canEditCalendar(adminUser: User | null | undefined): boolean {+export function siteAdminCanEditCalendar(adminUser: User | null | undefined): boolean {return isAdmin(adminUser);}@@ -258,7 +258,7 @@ export function canEditCalendar(adminUser: User | null | undefined): boolean {* @param adminUser - The admin performing the action* @returns boolean - true if admin can delete calendars*/-export function canDeleteCalendar(adminUser: User | null | undefined): boolean {+export function siteAdminCanDeleteCalendar(adminUser: User | null | undefined): boolean {return isSuperAdmin(adminUser);}diff --git a/lib/auth/permission-bundles-service.ts b/lib/auth/permission-bundles-service.tsnew file mode 100644index 0000000..9c7ab5a--- /dev/null+++ b/lib/auth/permission-bundles-service.ts@@ -0,0 +1,476 @@+/**+ * CRUD for owner-defined permission bundles (Stufe 2 of+ * .LOCAL/calendar-permission-bundles-plan.md, section 7.3). Enforcement+ * itself lives in lib/auth/permissions.ts — this file only manages the+ * bundles a calendar owns.+ */+import { NextRequest, NextResponse } from "next/server";+import { db } from "@/lib/db";+import {+ calendars,+ calendarShares,+ calendarAccessTokens,+ calendarPermissionBundles,+ type CalendarPermissionBundle,+} from "@/lib/db/schema";+import { eq, and, count, sql } from "drizzle-orm";+import { getCalendarAccess, type CalendarAccess } from "@/lib/auth/permissions";+import { getSessionUser } from "@/lib/auth/sessions";+import {+ isGuestEligible,+ normalizeCapabilities,+ sanitizeBundle,+ type BundleSeedKey,+ type Capability,+} from "@/lib/permission-bundles";+import deMessages from "@/messages/de.json";+import enMessages from "@/messages/en.json";+import esMessages from "@/messages/es.json";+import frMessages from "@/messages/fr.json";+import itMessages from "@/messages/it.json";+import csMessages from "@/messages/cs.json";++/** Carries an HTTP status alongside the message so routes can map it directly. */+export class PermissionBundleServiceError extends Error {+ constructor(+ message: string,+ public readonly status: number,+ public readonly details?: unknown+ ) {+ super(message);+ this.name = "PermissionBundleServiceError";+ }+}++export interface BundleUsage {+ shareCount: number;+ tokenCount: number;+ isGuestBundle: boolean;+}++export type BundleWithUsage = CalendarPermissionBundle & { usage: BundleUsage };++// Every locale's seed labels, used only to keep a custom bundle name from+// colliding (case-insensitively) with a seeded bundle's *displayed* name in+// some other locale than the one the current request happens to be in.+const SEED_LABEL_SOURCES = [+ deMessages,+ enMessages,+ esMessages,+ frMessages,+ itMessages,+ csMessages,+] as const;++function seedLabelsFor(seedKey: BundleSeedKey): string[] {+ return SEED_LABEL_SOURCES.map(+ (messages) => messages.permissionBundles.seed[seedKey]+ );+}++/**+ * Requires manageShares or manageGuestAccess on the calendar — bundle CRUD is+ * reachable via either, per docs/PERMISSIONS.md's "Who can assign or edit+ * bundles". Returns the caller's userId and resolved access (reused by+ * callers that also need to cap what the bundle may contain), or a ready+ * 401/403 response.+ */+export async function requireManageSharesOrGuestAccess(+ request: NextRequest,+ calendarId: string+): Promise<{ userId: string; access: CalendarAccess } | NextResponse> {+ const user = await getSessionUser(request.headers);+ if (!user) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }+ const access = await getCalendarAccess(user.id, calendarId);+ if (!access || (!access.can("manageShares") && !access.can("manageGuestAccess"))) {+ return NextResponse.json(+ { error: "Insufficient permissions" },+ { status: 403 }+ );+ }+ return { userId: user.id, access };+}++/**+ * Prevents a non-owner manageShares/manageGuestAccess holder from+ * creating/assigning a bundle more powerful than what they hold themselves+ * (self-escalation ceiling). Owners are exempt — they already hold every+ * capability by definition, so this is a no-op for them, but it's still+ * called for consistency.+ */+export function assertBundleWithinCallerCapabilities(+ access: CalendarAccess,+ capabilities: Capability[]+): void {+ if (access.isOwner) return;+ const disallowed = capabilities.filter((cap) => !access.can(cap));+ if (disallowed.length > 0) {+ throw new PermissionBundleServiceError(+ "Cannot grant capabilities you don't hold yourself",+ 403,+ { forbiddenCapabilities: disallowed }+ );+ }+}++/** Maps a PermissionBundleServiceError to its HTTP shape, or falls back to a 500 for anything else. */+export function handleBundleServiceError(+ error: unknown,+ fallbackMessage: string+): NextResponse {+ if (error instanceof PermissionBundleServiceError) {+ return NextResponse.json(+ { error: error.message, details: error.details },+ { status: error.status }+ );+ }+ console.error(fallbackMessage, error);+ return NextResponse.json({ error: fallbackMessage }, { status: 500 });+}++/** Calendar name for audit-log metadata — "Unknown" if the calendar was deleted concurrently. */+export async function getCalendarName(calendarId: string): Promise<string> {+ const calendar = await db.query.calendars.findFirst({+ where: eq(calendars.id, calendarId),+ columns: { name: true },+ });+ return calendar?.name ?? "Unknown";+}++/**+ * Loads a bundle for the calendar and rejects it (400, with the forbidden+ * capabilities listed) if it isn't guest-eligible (E7) — shared by every+ * route about to attach a bundle to a guest/link source+ * (calendars.guestBundleId, calendarAccessTokens.bundleId).+ */+export async function resolveGuestEligibleBundle(+ calendarId: string,+ bundleId: string,+ ineligibleMessage: string+): Promise<CalendarPermissionBundle | NextResponse> {+ const bundle = await getBundleForCalendar(calendarId, bundleId);+ if (!bundle) {+ return NextResponse.json({ error: "Bundle not found" }, { status: 404 });+ }+ if (!isGuestEligible(bundle.capabilities)) {+ return NextResponse.json(+ {+ error: ineligibleMessage,+ forbiddenCapabilities: bundle.capabilities.filter(+ (c) => !isGuestEligible([c])+ ),+ },+ { status: 400 }+ );+ }+ return bundle;+}++/** Loads a bundle only if it belongs to the given calendar — closes the cross-calendar gap noted in the plan. */+export async function getBundleForCalendar(+ calendarId: string,+ bundleId: string+): Promise<CalendarPermissionBundle | null> {+ const bundle = await db.query.calendarPermissionBundles.findFirst({+ where: and(+ eq(calendarPermissionBundles.id, bundleId),+ eq(calendarPermissionBundles.calendarId, calendarId)+ ),+ });+ return bundle ? sanitizeBundle(bundle) : null;+}++export async function getBundleUsage(bundleId: string): Promise<BundleUsage> {+ const [[shareRow], [tokenRow], guestCalendar] = await Promise.all([+ db+ .select({ total: count() })+ .from(calendarShares)+ .where(eq(calendarShares.bundleId, bundleId)),+ db+ .select({ total: count() })+ .from(calendarAccessTokens)+ .where(eq(calendarAccessTokens.bundleId, bundleId)),+ db.query.calendars.findFirst({+ where: eq(calendars.guestBundleId, bundleId),+ columns: { id: true },+ }),+ ]);+ return {+ shareCount: shareRow.total,+ tokenCount: tokenRow.total,+ isGuestBundle: !!guestCalendar,+ };+}++/** listPermissionBundles() from lib/auth/permissions.ts, with usage attached in one query (no N+1). */+export async function listBundlesWithUsage(+ calendarId: string+): Promise<BundleWithUsage[]> {+ const rows = await db+ .select({+ id: calendarPermissionBundles.id,+ calendarId: calendarPermissionBundles.calendarId,+ name: calendarPermissionBundles.name,+ seedKey: calendarPermissionBundles.seedKey,+ capabilities: calendarPermissionBundles.capabilities,+ createdAt: calendarPermissionBundles.createdAt,+ updatedAt: calendarPermissionBundles.updatedAt,+ // Correlated column must be qualified as a literal — a tagged-template+ // reference here renders unqualified and SQLite resolves it against the+ // subquery's own table instead of the correlated outer bundle row.+ shareCount: sql<number>`(select count(*) from ${calendarShares} where ${calendarShares.bundleId} = "calendar_permission_bundles"."id")`,+ tokenCount: sql<number>`(select count(*) from ${calendarAccessTokens} where ${calendarAccessTokens.bundleId} = "calendar_permission_bundles"."id")`,+ guestCount: sql<number>`(select count(*) from ${calendars} where ${calendars.guestBundleId} = "calendar_permission_bundles"."id")`,+ })+ .from(calendarPermissionBundles)+ .where(eq(calendarPermissionBundles.calendarId, calendarId))+ .orderBy(calendarPermissionBundles.createdAt);++ return rows.map(({ shareCount, tokenCount, guestCount, ...bundle }) => ({+ ...sanitizeBundle(bundle),+ usage: {+ shareCount: Number(shareCount),+ tokenCount: Number(tokenCount),+ isGuestBundle: Number(guestCount) > 0,+ },+ }));+}++/**+ * Case-insensitive uniqueness check within a calendar, against every other+ * bundle's literal name AND — for every other seeded bundle — that seedKey's+ * translated label in all six locales (so a German "Lesen" can't be created+ * alongside a seeded "read" bundle just because the request happens to run+ * in English).+ */+export async function isNameTaken(+ calendarId: string,+ name: string,+ excludeBundleId?: string+): Promise<boolean> {+ const target = name.trim().toLowerCase();+ const bundles = await db.query.calendarPermissionBundles.findMany({+ where: eq(calendarPermissionBundles.calendarId, calendarId),+ columns: { id: true, name: true, seedKey: true },+ });+ for (const bundle of bundles) {+ if (bundle.id === excludeBundleId) continue;+ if (bundle.name.trim().toLowerCase() === target) return true;+ if (bundle.seedKey) {+ const labels = seedLabelsFor(bundle.seedKey);+ if (labels.some((label) => label.trim().toLowerCase() === target)) {+ return true;+ }+ }+ }+ return false;+}++function assertValidName(name: string): string {+ const trimmed = name.trim();+ if (!trimmed) {+ throw new PermissionBundleServiceError("Name must not be empty", 400);+ }+ return trimmed;+}++/** E7: a bundle reachable by a guest/link source may never hold a guest-ineligible capability. */+function assertGuestEligibleIfNeeded(+ usage: BundleUsage,+ capabilities: Capability[]+): void {+ if (!usage.isGuestBundle && usage.tokenCount === 0) return;+ if (isGuestEligible(capabilities)) return;+ const forbidden = capabilities.filter((c) => !isGuestEligible([c]));+ throw new PermissionBundleServiceError(+ "Bundle is assigned to guest access or a link and cannot hold these capabilities",+ 400,+ { forbiddenCapabilities: forbidden }+ );+}++export async function createPermissionBundle(+ calendarId: string,+ input: { name: string; capabilities: unknown },+ callerAccess: CalendarAccess+): Promise<CalendarPermissionBundle> {+ const name = assertValidName(input.name);+ if (await isNameTaken(calendarId, name)) {+ throw new PermissionBundleServiceError(+ "A bundle with this name already exists",+ 409+ );+ }+ const capabilities = normalizeCapabilities(input.capabilities);+ assertBundleWithinCallerCapabilities(callerAccess, capabilities);+ const [created] = await db+ .insert(calendarPermissionBundles)+ .values({ calendarId, name, seedKey: null, capabilities })+ .returning();+ return sanitizeBundle(created);+}++export async function updatePermissionBundle(+ calendarId: string,+ bundleId: string,+ input: { name?: string; capabilities?: unknown },+ callerAccess: CalendarAccess+): Promise<CalendarPermissionBundle> {+ const existing = await getBundleForCalendar(calendarId, bundleId);+ if (!existing) {+ throw new PermissionBundleServiceError("Bundle not found", 404);+ }++ const patch: Partial<+ Pick<+ typeof calendarPermissionBundles.$inferInsert,+ "name" | "seedKey" | "capabilities"+ >+ > = {};++ if (input.name !== undefined) {+ const name = assertValidName(input.name);+ if (name !== existing.name) {+ if (await isNameTaken(calendarId, name, bundleId)) {+ throw new PermissionBundleServiceError(+ "A bundle with this name already exists",+ 409+ );+ }+ patch.name = name;+ // 4.2: renaming a seeded bundle detaches it from the translated display name.+ patch.seedKey = null;+ }+ }++ let capabilities: Capability[] | undefined;+ if (input.capabilities !== undefined) {+ capabilities = normalizeCapabilities(input.capabilities);+ assertBundleWithinCallerCapabilities(callerAccess, capabilities);+ patch.capabilities = capabilities;+ }++ if (Object.keys(patch).length === 0) {+ return existing;+ }++ if (capabilities !== undefined) {+ // Re-check guest-eligibility inside the same transaction as the write —+ // otherwise a concurrent request could reassign the bundle to a+ // token/guest slot between the check and the update (mirrors+ // deletePermissionBundle's re-check of usage inside its transaction).+ const updated = db.transaction((tx) => {+ const usage: BundleUsage = {+ shareCount: tx+ .select({ total: count() })+ .from(calendarShares)+ .where(eq(calendarShares.bundleId, bundleId))+ .get()!.total,+ tokenCount: tx+ .select({ total: count() })+ .from(calendarAccessTokens)+ .where(eq(calendarAccessTokens.bundleId, bundleId))+ .get()!.total,+ isGuestBundle: !!tx+ .select({ id: calendars.id })+ .from(calendars)+ .where(eq(calendars.guestBundleId, bundleId))+ .get(),+ };+ assertGuestEligibleIfNeeded(usage, capabilities!);+ return tx+ .update(calendarPermissionBundles)+ .set(patch)+ .where(eq(calendarPermissionBundles.id, bundleId))+ .returning()+ .get();+ });+ return sanitizeBundle(updated);+ }++ const [updated] = await db+ .update(calendarPermissionBundles)+ .set(patch)+ .where(eq(calendarPermissionBundles.id, bundleId))+ .returning();+ return sanitizeBundle(updated);+}++export async function clonePermissionBundle(+ calendarId: string,+ bundleId: string,+ name: string+): Promise<CalendarPermissionBundle> {+ const source = await getBundleForCalendar(calendarId, bundleId);+ if (!source) {+ throw new PermissionBundleServiceError("Bundle not found", 404);+ }+ const trimmedName = assertValidName(name);+ if (await isNameTaken(calendarId, trimmedName)) {+ throw new PermissionBundleServiceError(+ "A bundle with this name already exists",+ 409+ );+ }+ const [created] = await db+ .insert(calendarPermissionBundles)+ .values({+ calendarId,+ name: trimmedName,+ seedKey: null,+ capabilities: source.capabilities,+ })+ .returning();+ return sanitizeBundle(created);+}++export async function deletePermissionBundle(+ calendarId: string,+ bundleId: string+): Promise<void> {+ const existing = await getBundleForCalendar(calendarId, bundleId);+ if (!existing) {+ throw new PermissionBundleServiceError("Bundle not found", 404);+ }+ const usage = await getBundleUsage(bundleId);+ if (usage.shareCount > 0 || usage.tokenCount > 0 || usage.isGuestBundle) {+ throw new PermissionBundleServiceError(+ "Bundle is still in use and cannot be deleted",+ 409,+ { usage }+ );+ }+ // Synchronous callback — better-sqlite3 transactions must not return a+ // promise (see seedPermissionBundles() in lib/auth/permissions.ts and the+ // Stufe 1b gotcha in commit b7fb903). Re-check usage inside the+ // transaction to close the race between the check above and the delete.+ db.transaction((tx) => {+ const stillUsed =+ tx+ .select({ total: count() })+ .from(calendarShares)+ .where(eq(calendarShares.bundleId, bundleId))+ .get()!.total > 0 ||+ tx+ .select({ total: count() })+ .from(calendarAccessTokens)+ .where(eq(calendarAccessTokens.bundleId, bundleId))+ .get()!.total > 0 ||+ !!tx+ .select({ id: calendars.id })+ .from(calendars)+ .where(eq(calendars.guestBundleId, bundleId))+ .get();+ if (stillUsed) {+ throw new PermissionBundleServiceError(+ "Bundle is still in use and cannot be deleted",+ 409+ );+ }+ tx.delete(calendarPermissionBundles).where(+ eq(calendarPermissionBundles.id, bundleId)+ ).run();+ });+}diff --git a/lib/auth/permissions.ts b/lib/auth/permissions.tsindex d0a0c52..d784303 100644--- a/lib/auth/permissions.ts+++ b/lib/auth/permissions.ts@@ -2,136 +2,133 @@ import { db } from "@/lib/db";import {calendars,calendarShares,+ calendarPermissionBundles,userCalendarSubscriptions,+ type CalendarPermissionBundle,} from "@/lib/db/schema";import { eq, and, isNull } from "drizzle-orm";import { allowGuestAccess, isAuthEnabled } from "@/lib/auth/feature-flags";import {- getTokenPermission,+ getTokenBundleId,getTokensFromCookie,validateAccessToken,} from "@/lib/auth/token-auth";-import type { CalendarMember } from "@/lib/types";+import type { CalendarBundleRef, CalendarMember } from "@/lib/types";+import {+ applyGuestCeiling,+ CAPABILITIES,+ sanitizeBundle,+ type BundleDefinition,+ type Capability,+} from "@/lib/permission-bundles";++async function getBundleById(+ bundleId: string+): Promise<CalendarPermissionBundle | null> {+ const bundle = await db.query.calendarPermissionBundles.findFirst({+ where: eq(calendarPermissionBundles.id, bundleId),+ });+ return bundle ? sanitizeBundle(bundle) : null;+}-/**- * Calendar permission levels- * - owner: Full control, can delete calendar- * - admin: Can manage calendar settings and shares- * - write: Can create/edit/delete shifts, presets, notes- * - read: Can only view calendar data- */-export type CalendarPermission = "owner" | "admin" | "write" | "read";+interface ResolvedCalendarAccess {+ isOwner: boolean;+ source: "owner" | "share" | "token" | "guestBundle";+ capabilities: Capability[];+ calendar: typeof calendars.$inferSelect;+ /** null for the owner/auth-disabled branches, which never go through a bundle. */+ bundle: CalendarBundleRef | null;+}-/**- * Guest permission levels (subset of CalendarPermission)- * - none: No guest access- * - read: Guests can view calendar data- * - write: Guests can create/edit/delete shifts, presets, notes- */-export type GuestPermission = "none" | "read" | "write";+function ownerAccess(calendar: typeof calendars.$inferSelect): ResolvedCalendarAccess {+ return {+ isOwner: true,+ source: "owner",+ capabilities: [...CAPABILITIES],+ calendar,+ bundle: null,+ };+}-/**- * Get user's permission level for a specific calendar- * Returns null if user has no access to the calendar- *- * Permission priority (highest to lowest):- * 1. Owner (calendar.ownerId matches userId)- * 2. Shared permission (via calendarShares)- * 3. Access token (via cookie)- * 4. Public/Guest permission (for subscribed users or when guest access enabled)- *- * For guest users (userId = null), checks:- * - Access token permission- * - Guest permission (if auth enabled + guest access enabled + calendar allows it)- */-export async function getUserCalendarPermission(- userId: string | null | undefined,- calendarId: string-): Promise<CalendarPermission | null> {- return (await getUserCalendarPermissionWithCalendar(userId, calendarId))- .permission;+function bundleAccess(+ calendar: typeof calendars.$inferSelect,+ source: "share" | "token" | "guestBundle",+ bundle: CalendarPermissionBundle+): ResolvedCalendarAccess {+ return {+ isOwner: false,+ source,+ capabilities: bundle.capabilities,+ calendar,+ bundle: { id: bundle.id, name: bundle.name, seedKey: bundle.seedKey },+ };}/**- * Same resolution as getUserCalendarPermission, but also returns the calendar- * row it already fetched — lets callers that need calendar columns (e.g.- * getShiftSignupPermission) avoid a second round trip for the same row.+ * Resolves what a caller may do on a calendar: owner (everything), or the+ * capability set of whichever bundle they hold (share > token > guest bundle+ * for authenticated users; token > guest bundle for guests). Returns null+ * when the calendar doesn't exist, is orphaned, or grants no access at all.*/-async function getUserCalendarPermissionWithCalendar(+async function resolveCalendarAccess(userId: string | null | undefined,calendarId: string-): Promise<{- permission: CalendarPermission | null;- calendar: typeof calendars.$inferSelect | null;-}> {- // If auth is disabled, grant full owner access (backwards compatibility)- if (!isAuthEnabled()) {- const calendar = await db.query.calendars.findFirst({- where: eq(calendars.id, calendarId),- });- return { permission: calendar ? "owner" : null, calendar: calendar ?? null };- }-- // Fetch calendar first (needed for all checks)+): Promise<ResolvedCalendarAccess | null> {+ // guestBundle fetched alongside the calendar (one hop via the relation)+ // since almost every branch below may need it.const calendar = await db.query.calendars.findFirst({where: eq(calendars.id, calendarId),+ with: { guestBundle: true },});+ if (!calendar) return null;- if (!calendar) {- return { permission: null, calendar: null };+ // If auth is disabled, grant full owner access (backwards compatibility)+ if (!isAuthEnabled()) {+ return ownerAccess(calendar);}- // CRITICAL: Orphaned calendars (ownerId=null) are invisible to ALL users- // They can only be accessed via dedicated admin panel API routes- if (calendar.ownerId === null) {- return { permission: null, calendar };- }+ // CRITICAL: Orphaned calendars (ownerId=null) are invisible to ALL users.+ // They can only be accessed via dedicated admin panel API routes.+ if (calendar.ownerId === null) return null;++ const guestBundle = calendar.guestBundle ? sanitizeBundle(calendar.guestBundle) : null;- // If no user ID, check token and guest permissionsif (!userId) {- // Check for access token first (higher priority than guest)- const tokenPermission = await getTokenPermission(calendarId);- if (tokenPermission) {- return { permission: tokenPermission, calendar };+ const tokenBundleId = await getTokenBundleId(calendarId);+ if (tokenBundleId) {+ const bundle = await getBundleById(tokenBundleId);+ if (bundle) return bundleAccess(calendar, "token", bundle);}-// Guest access only works when explicitly enabled- if ((await allowGuestAccess()) && calendar.guestPermission !== "none") {- return {- permission: calendar.guestPermission as CalendarPermission,- calendar,- };+ if ((await allowGuestAccess()) && guestBundle) {+ return bundleAccess(calendar, "guestBundle", guestBundle);}- return { permission: null, calendar };+ return null;}- // Owner has full controlif (calendar.ownerId === userId) {- return { permission: "owner", calendar };+ return ownerAccess(calendar);}- // Check shared permissions (higher priority than tokens)const share = await db.query.calendarShares.findFirst({where: and(eq(calendarShares.calendarId, calendarId),eq(calendarShares.userId, userId)),+ with: { bundle: true },});-- if (share) {- return {- permission: share.permission as CalendarPermission,- calendar,- };+ if (share?.bundle) {+ return bundleAccess(calendar, "share", sanitizeBundle(share.bundle));}- // Check for access token (authenticated users can also use tokens)- const tokenPermission = await getTokenPermission(calendarId);- if (tokenPermission) {- return { permission: tokenPermission, calendar };+ const tokenBundleId = await getTokenBundleId(calendarId);+ if (tokenBundleId) {+ const bundle = await getBundleById(tokenBundleId);+ if (bundle) return bundleAccess(calendar, "token", bundle);}- // Check if user is subscribed to this public calendar+ // Authenticated users can always access public calendars they're+ // subscribed to, regardless of the allowGuestAccess() setting.const subscription = await db.query.userCalendarSubscriptions.findFirst({where: and(eq(userCalendarSubscriptions.calendarId, calendarId),@@ -139,69 +136,150 @@ async function getUserCalendarPermissionWithCalendar(eq(userCalendarSubscriptions.status, "subscribed")),});-- // If subscribed and calendar has public access (guestPermission != "none"), return that permission- // Authenticated users can always access public calendars, regardless of allowGuestAccess setting- if (subscription && calendar.guestPermission !== "none") {- return {- permission: calendar.guestPermission as CalendarPermission,- calendar,- };+ if (subscription && guestBundle) {+ return bundleAccess(calendar, "guestBundle", guestBundle);}- return { permission: null, calendar };+ return null;+}++export interface CalendarAccess {+ isOwner: boolean;+ /** Whether the caller may perform a specific capability on the calendar. */+ can(capability: Capability): boolean;+ /**+ * Whether the caller may act on a specific resource (a shift, preset or+ * note) given the two capabilities that gate it and who created it (E1).+ * `any` covers every resource regardless of creator; `own` only covers+ * resources with no known creator or created by the caller (E8) — for an+ * anonymous guest (no userId) that means only creator-less resources+ * count as "own" (E9's authenticated-guest exception doesn't apply here,+ * this is ownership, not signup eligibility).+ */+ canOwned(own: Capability, any: Capability, createdBy: string | null): boolean;}/**- * Check if user has at least the required permission level+ * Applies the hard ceiling that keeps guest/link access from ever reaching+ * administrative capabilities (manageShares, manageGuestAccess,+ * manageCalendarSettings, manageExternalSync, deleteSyncLogs), 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+ * legitimately hold admin-only capabilities).*/-export async function checkPermission(- userId: string | null | undefined,- calendarId: string,- required: CalendarPermission-): Promise<boolean> {- const userPermission = await getUserCalendarPermission(userId, calendarId);+function ceilingFilteredCapabilities(access: ResolvedCalendarAccess): Capability[] {+ if (access.isOwner) return [...CAPABILITIES];+ if (access.source === "share") return access.capabilities;+ return applyGuestCeiling(access.capabilities);+}- if (!userPermission) {- return false;- }+/**+ * Resolves a caller's access to a calendar once and returns an object with+ * `can()`/`canOwned()` so routes that need several checks don't re-resolve+ * calendar/share/token/guest-bundle lookups per check. `hasCapability()` and+ * `hasOwnedCapability()` below are thin single-check convenience wrappers.+ */+export async function getCalendarAccess(+ userId: string | null | undefined,+ calendarId: string+): Promise<CalendarAccess | null> {+ const access = await resolveCalendarAccess(userId, calendarId);+ if (!access) return null;++ const effective = ceilingFilteredCapabilities(access);+ const can = (capability: Capability): boolean => effective.includes(capability);++ const canOwned = (+ own: Capability,+ any: Capability,+ createdBy: string | null+ ): boolean => {+ if (access.isOwner) return true;+ if (can(any)) return true;+ if (!can(own)) return false;+ return createdBy === null || createdBy === (userId ?? null);+ };- // Permission hierarchy: owner > admin > write > read- const hierarchy: CalendarPermission[] = ["owner", "admin", "write", "read"];- const userLevel = hierarchy.indexOf(userPermission);- const requiredLevel = hierarchy.indexOf(required);+ return { isOwner: access.isOwner, can, canOwned };+}- return userLevel <= requiredLevel;+export interface EffectiveAccessSummary {+ isOwner: boolean;+ capabilities: Capability[];+ /** null for the owner and for auth-disabled — every other source resolves through a bundle. */+ bundle: CalendarBundleRef | null;}/**- * Check if user can view a calendar+ * Ceiling-filtered capabilities plus the bundle they came from, for API+ * responses that hand the client its own effective access (calendar list,+ * subscriptions) instead of the old sharePermission/tokenPermission/+ * guestPermission enum fields. Client-side gating should check these+ * capabilities directly rather than re-deriving a coarse level.*/-export async function canViewCalendar(+export async function getEffectiveAccessSummary(userId: string | null | undefined,calendarId: string-): Promise<boolean> {- return checkPermission(userId, calendarId, "read");+): Promise<EffectiveAccessSummary | null> {+ const access = await resolveCalendarAccess(userId, calendarId);+ if (!access) return null;+ return {+ isOwner: access.isOwner,+ capabilities: ceilingFilteredCapabilities(access),+ bundle: access.isOwner ? null : access.bundle,+ };}/**- * Check if user can edit calendar data (shifts, presets, notes)+ * Whether the caller may perform a specific capability on a calendar. This+ * is the primary enforcement API for calendar-wide capabilities — route+ * handlers should check exactly the capability their action needs, not a+ * coarse level. For own/any-gated resources use hasOwnedCapability(), and+ * for several checks on the same request prefer getCalendarAccess() once.*/-export async function canEditCalendar(+export async function hasCapability(userId: string | null | undefined,- calendarId: string+ calendarId: string,+ capability: Capability+): Promise<boolean> {+ const access = await getCalendarAccess(userId, calendarId);+ return access ? access.can(capability) : false;+}++/** Single-check convenience wrapper around CalendarAccess.canOwned() — see there. */+export async function hasOwnedCapability(+ userId: string | null | undefined,+ calendarId: string,+ own: Capability,+ any: Capability,+ createdBy: string | null): Promise<boolean> {- return checkPermission(userId, calendarId, "write");+ const access = await getCalendarAccess(userId, calendarId);+ return access ? access.canOwned(own, any, createdBy) : false;}/**- * Check if user can manage calendar settings and shares+ * Whether the caller has any access to a calendar at all (works for both+ * authenticated users and guests). Used by GET routes that only need to+ * gate presence, not a specific capability — viewShifts/viewNotesEvents/+ * viewStats are in every seeded and migrated bundle, so this is normally+ * equivalent to "has view access", without depending on a custom bundle+ * having ticked a specific view capability.*/-export async function canManageCalendar(+export async function canViewCalendar(userId: string | null | undefined,calendarId: string): Promise<boolean> {- return checkPermission(userId, calendarId, "admin");+ return (await resolveCalendarAccess(userId, calendarId)) !== null;+}++export async function isCalendarOwner(+ userId: string | null | undefined,+ calendarId: string+): Promise<boolean> {+ const access = await getCalendarAccess(userId, calendarId);+ return access?.isOwner ?? false;}/**@@ -211,7 +289,7 @@ export async function canDeleteCalendar(userId: string | null | undefined,calendarId: string): Promise<boolean> {- return checkPermission(userId, calendarId, "owner");+ return isCalendarOwner(userId, calendarId);}/**@@ -219,66 +297,68 @@ export async function canDeleteCalendar(* - canManageOwn: may add/remove themselves* - canManageOthers: may add/remove any other member*- * Only logged-in users (userId set) can hold signups at all — guests never do,- * even when a share/access-token grants them "write" on the calendar itself.- * The calendar-wide signupsEnabled switch (owner/admin only) overrides- * everything else. A "read"-level member can only self-manage, and only while- * allowSelfSignup is on; write/admin/owner can always manage anyone.+ * Only logged-in users (userId set) can hold signups at all — guests never+ * do, even when a token/guest bundle grants them signUpSelf/signUpOthers on+ * the calendar itself. The calendar-wide signupsEnabled switch (gated by+ * manageCalendarSettings) overrides everything else.*/export async function getShiftSignupPermission(userId: string | null | undefined,calendarId: string): Promise<{ canManageOwn: boolean; canManageOthers: boolean }> {- if (!userId) {+ const access = await resolveCalendarAccess(userId, calendarId);+ if (!access || !access.calendar.signupsEnabled) {return { canManageOwn: false, canManageOthers: false };}-- const { permission, calendar } = await getUserCalendarPermissionWithCalendar(- userId,- calendarId- );- if (!permission) {- return { canManageOwn: false, canManageOthers: false };+ if (access.isOwner) {+ return { canManageOwn: true, canManageOthers: true };}-- if (!calendar?.signupsEnabled) {+ if (!userId) {return { canManageOwn: false, canManageOthers: false };}-- if (permission !== "read") {- // owner / admin / write- return { canManageOwn: true, canManageOthers: true };- }-return {- canManageOwn: !!calendar.allowSelfSignup,- canManageOthers: false,+ canManageOwn: access.capabilities.includes("signUpSelf"),+ canManageOthers: access.capabilities.includes("signUpOthers"),};}/**- * Get all calendar IDs accessible to a user (or guest)- * Returns array of calendar IDs with their permission levels+ * Resolves which of the given bundle ids still exist. guestBundleId has no+ * DB-level FK (see lib/db/schema.ts), so a bundle deletion (Stufe 2) can+ * leave it pointing at nothing — callers must treat that the same as "no+ * guest access" rather than resolving it anyway (4.2/4.3 of the design doc).+ */+async function existingBundleIds(+ ids: Iterable<string>+): Promise<Set<string>> {+ const idList = Array.from(new Set(ids));+ if (idList.length === 0) return new Set();+ const rows = await db.query.calendarPermissionBundles.findMany({+ where: (b, { inArray }) => inArray(b.id, idList),+ columns: { id: true },+ });+ return new Set(rows.map((row) => row.id));+}++/**+ * Get all calendar IDs accessible to a user (or guest), with an isOwner flag.** For guest users (userId = null), returns:* - Calendars accessible via access tokens (always, regardless of allowGuestAccess)- * - Calendars with guestPermission != "none" (only if guest access is enabled)+ * - Calendars with a guestBundleId set (only if guest access is enabled)*/export async function getUserAccessibleCalendars(userId: string | null | undefined-): Promise<Array<{ id: string; permission: CalendarPermission }>> {- // If auth is disabled, return all calendars with owner permission (backwards compatibility)+): Promise<Array<{ id: string; isOwner: boolean }>> {if (!isAuthEnabled()) {- const allCalendars = await db.query.calendars.findMany();- return allCalendars.map((cal) => ({- id: cal.id,- permission: "owner" as const,- }));+ const allCalendars = await db.query.calendars.findMany({+ columns: { id: true },+ });+ return allCalendars.map((cal) => ({ id: cal.id, isOwner: true }));}- // Guest access: return calendars accessible via tokens or guest permissionsif (!userId) {- const results: Array<{ id: string; permission: CalendarPermission }> = [];+ const results: Array<{ id: string; isOwner: boolean }> = [];const existingIds = new Set<string>();// Token-based access and the guest-access flag don't depend on each@@ -290,114 +370,84 @@ export async function getUserAccessibleCalendars(// First, check for token-based access (always works, regardless of allowGuestAccess)for (const tokenData of tokens) {- // Validate token is still validconst validation = await validateAccessToken(tokenData.token);if (validation && validation.calendarId === tokenData.calendarId) {- results.push({- id: tokenData.calendarId,- permission: tokenData.permission as CalendarPermission,- });+ results.push({ id: tokenData.calendarId, isOwner: false });existingIds.add(tokenData.calendarId);}}- // Then, check for guest permissions (only if guest access is enabled)+ // Then, check for guest bundle access (only if guest access is enabled)if (guestAccessEnabled) {const guestAccessibleCalendars = await db.query.calendars.findMany({- where: (calendars, { ne }) => ne(calendars.guestPermission, "none"),+ where: (calendars, { isNotNull }) => isNotNull(calendars.guestBundleId),+ columns: { id: true, guestBundleId: true },});-+ const liveBundleIds = await existingBundleIds(+ guestAccessibleCalendars.map((cal) => cal.guestBundleId!)+ );for (const cal of guestAccessibleCalendars) {- if (!existingIds.has(cal.id)) {- results.push({- id: cal.id,- permission: cal.guestPermission as CalendarPermission,- });- existingIds.add(cal.id);- }+ if (existingIds.has(cal.id)) continue;+ if (!liveBundleIds.has(cal.guestBundleId!)) continue;+ results.push({ id: cal.id, isOwner: false });+ existingIds.add(cal.id);}}return results;}- const results: Array<{ id: string; permission: CalendarPermission }> = [];-- // Get owned calendars (ALWAYS visible, cannot be dismissed)- const ownedCalendars = await db.query.calendars.findMany({- where: eq(calendars.ownerId, userId),- });-- results.push(- ...ownedCalendars.map((cal) => ({- id: cal.id,- permission: "owner" as const,- }))- );-- // Get all subscriptions for this user (including dismissed)- const subscriptions = await db.query.userCalendarSubscriptions.findMany({- where: eq(userCalendarSubscriptions.userId, userId),- with: {- calendar: true,- },- });-- // Get shared calendars (not owned by user)- const sharedCalendars = await db.query.calendarShares.findMany({- where: eq(calendarShares.userId, userId),- with: {- calendar: true,- },- });+ const results: Array<{ id: string; isOwner: boolean }> = [];++ const [ownedCalendars, subscriptions, sharedCalendars] = await Promise.all([+ db.query.calendars.findMany({+ where: eq(calendars.ownerId, userId),+ columns: { id: true },+ }),+ db.query.userCalendarSubscriptions.findMany({+ where: eq(userCalendarSubscriptions.userId, userId),+ with: { calendar: true },+ }),+ db.query.calendarShares.findMany({+ where: eq(calendarShares.userId, userId),+ }),+ ]);+ results.push(...ownedCalendars.map((cal) => ({ id: cal.id, isOwner: true })));- // Track which calendars exist to prevent duplicatesconst existingIds = new Set(results.map((r) => r.id));- // Add shared calendars (share permission takes precedence over guest permission)for (const share of sharedCalendars) {- if (existingIds.has(share.calendarId)) continue; // Skip if owned-- // Check if user has dismissed this shared calendar+ if (existingIds.has(share.calendarId)) continue;const isDismissed = subscriptions.find((sub) => sub.calendarId === share.calendarId && sub.status === "dismissed");-if (!isDismissed) {- results.push({- id: share.calendarId,- permission: share.permission as CalendarPermission,- });+ results.push({ id: share.calendarId, isOwner: false });existingIds.add(share.calendarId);}}- // Add guest-subscribed calendars (only if not already included via shares and not dismissed)+ const subscriptionGuestBundleIds = await existingBundleIds(+ subscriptions+ .map((sub) => sub.calendar.guestBundleId)+ .filter((id): id is string => id !== null)+ );for (const sub of subscriptions) {if (existingIds.has(sub.calendarId)) continue;- if (sub.calendar.guestPermission === "none") continue;+ if (!sub.calendar.guestBundleId) continue;+ if (!subscriptionGuestBundleIds.has(sub.calendar.guestBundleId)) continue;if (sub.source !== "guest") continue;- if (sub.status === "dismissed") continue; // Skip dismissed guest subscriptions-- results.push({- id: sub.calendarId,- permission: sub.calendar.guestPermission as CalendarPermission,- });+ if (sub.status === "dismissed") continue;+ results.push({ id: sub.calendarId, isOwner: false });existingIds.add(sub.calendarId);}- // Add token-accessible calendars (authenticated users can also use access tokens)const tokens = await getTokensFromCookie();for (const tokenData of tokens) {if (existingIds.has(tokenData.calendarId)) continue;-- // Validate token is still validconst validation = await validateAccessToken(tokenData.token);if (validation && validation.calendarId === tokenData.calendarId) {- results.push({- id: tokenData.calendarId,- permission: tokenData.permission as CalendarPermission,- });+ results.push({ id: tokenData.calendarId, isOwner: false });existingIds.add(tokenData.calendarId);}}@@ -433,7 +483,6 @@ export async function dismissCalendar(userId: string,calendarId: string): Promise<void> {- // Check if user owns the calendarconst calendar = await db.query.calendars.findFirst({where: eq(calendars.id, calendarId),});@@ -446,7 +495,6 @@ export async function dismissCalendar(throw new Error("Cannot dismiss your own calendar");}- // Check if it's a shared calendarconst share = await db.query.calendarShares.findFirst({where: and(eq(calendarShares.calendarId, calendarId),@@ -454,7 +502,6 @@ export async function dismissCalendar(),});- // Check if subscription already existsconst existingSub = await db.query.userCalendarSubscriptions.findFirst({where: and(eq(userCalendarSubscriptions.userId, userId),@@ -463,7 +510,6 @@ export async function dismissCalendar(});if (existingSub) {- // Update existing subscription to dismissedawait db.update(userCalendarSubscriptions).set({@@ -473,7 +519,6 @@ export async function dismissCalendar(}).where(eq(userCalendarSubscriptions.id, existingSub.id));} else {- // Create new dismissal entryawait db.insert(userCalendarSubscriptions).values({userId,calendarId,@@ -504,7 +549,6 @@ export async function undismissCalendar(throw new Error("Cannot subscribe to your own calendar");}- // Check if it's a shared calendarconst share = await db.query.calendarShares.findFirst({where: and(eq(calendarShares.calendarId, calendarId),@@ -512,12 +556,14 @@ export async function undismissCalendar(),});- // For guest calendars, verify it's public- if (!share && calendar.guestPermission === "none") {+ const hasLiveGuestBundle =+ !!calendar.guestBundleId &&+ (await existingBundleIds([calendar.guestBundleId])).size > 0;++ if (!share && !hasLiveGuestBundle) {throw new Error("Calendar is not public");}- // Check if subscription existsconst existingSub = await db.query.userCalendarSubscriptions.findFirst({where: and(eq(userCalendarSubscriptions.userId, userId),@@ -526,7 +572,6 @@ export async function undismissCalendar(});if (existingSub) {- // Update to subscribedawait db.update(userCalendarSubscriptions).set({@@ -536,7 +581,6 @@ export async function undismissCalendar(}).where(eq(userCalendarSubscriptions.id, existingSub.id));} else {- // Create new subscriptionawait db.insert(userCalendarSubscriptions).values({userId,calendarId,@@ -607,3 +651,45 @@ export async function getOrphanedCalendars() {return orphanedCalendars;}++// =====================================================+// Permission bundle seeding+// =====================================================++export async function listPermissionBundles(+ calendarId: string+): Promise<CalendarPermissionBundle[]> {+ const rows = await db.query.calendarPermissionBundles.findMany({+ where: eq(calendarPermissionBundles.calendarId, calendarId),+ orderBy: (bundles, { asc }) => [asc(bundles.createdAt)],+ });+ return rows.map(sanitizeBundle);+}++/**+ * Inserts the given bundle definitions for a calendar and returns the+ * created rows. Synchronous (not async) so a caller can seed bundles+ * atomically with the calendar row itself inside a db.transaction()+ * callback (see POST /api/calendars) — better-sqlite3 transactions must be+ * fully synchronous, they reject a callback that returns a promise.+ * Accepts an optional transaction executor, defaulting to the module-level+ * db for callers outside a transaction.+ */+export function seedPermissionBundles(+ calendarId: string,+ definitions: BundleDefinition[],+ executor: Pick<typeof db, "insert"> = db+): CalendarPermissionBundle[] {+ return executor+ .insert(calendarPermissionBundles)+ .values(+ definitions.map((def) => ({+ calendarId,+ name: def.name,+ seedKey: def.seedKey,+ capabilities: def.capabilities,+ }))+ )+ .returning()+ .all();+}diff --git a/lib/auth/token-auth.ts b/lib/auth/token-auth.tsindex 4c67253..7e81902 100644--- a/lib/auth/token-auth.ts+++ b/lib/auth/token-auth.ts@@ -26,7 +26,7 @@ const TOKEN_COOKIE_OPTIONS = {export interface TokenCookieData {token: string;calendarId: string;- permission: "read" | "write";+ bundleId: string;}/**@@ -43,7 +43,7 @@ export async function validateAccessToken(): Promise<{id: string;calendarId: string;- permission: "read" | "write";+ bundleId: string;calendarName: string;} | null> {try {@@ -51,7 +51,7 @@ export async function validateAccessToken(.select({id: calendarAccessTokens.id,calendarId: calendarAccessTokens.calendarId,- permission: calendarAccessTokens.permission,+ bundleId: calendarAccessTokens.bundleId,expiresAt: calendarAccessTokens.expiresAt,isActive: calendarAccessTokens.isActive,calendarName: calendars.name,@@ -78,7 +78,7 @@ export async function validateAccessToken(return {id: tokenData.id,calendarId: tokenData.calendarId,- permission: tokenData.permission as "read" | "write",+ bundleId: tokenData.bundleId,calendarName: tokenData.calendarName,};} catch (error) {@@ -124,14 +124,14 @@ export async function updateTokenUsage(tokenId: string): Promise<void> {** @param token - The token string* @param calendarId - The calendar ID- * @param permission - The permission level+ * @param bundleId - The permission bundle id* @param response - The NextResponse to set the cookie on* @param request - Optional NextRequest to read existing tokens from*/export function storeTokenInCookie(token: string,calendarId: string,- permission: "read" | "write",+ bundleId: string,response: NextResponse,request?: NextRequest): void {@@ -148,7 +148,7 @@ export function storeTokenInCookie(// Add new tokenconst newTokens: TokenCookieData[] = [...existingTokens,- { token, calendarId, permission },+ { token, calendarId, bundleId },];// Store in cookie@@ -189,7 +189,7 @@ export async function getTokensFromCookie(): Promise<TokenCookieData[]> {(t) =>typeof t.token === "string" &&typeof t.calendarId === "string" &&- (t.permission === "read" || t.permission === "write")+ typeof t.bundleId === "string");// Validate each token against the database@@ -250,7 +250,7 @@ export function getTokensFromRequest(request: NextRequest): TokenCookieData[] {(t) =>typeof t.token === "string" &&typeof t.calendarId === "string" &&- (t.permission === "read" || t.permission === "write")+ typeof t.bundleId === "string");} catch (error) {console.error("[token-auth] getTokensFromRequest error:", error);@@ -283,7 +283,7 @@ function getTokensFromResponse(response: NextResponse): TokenCookieData[] {(t) =>typeof t.token === "string" &&typeof t.calendarId === "string" &&- (t.permission === "read" || t.permission === "write")+ typeof t.bundleId === "string");} catch (error) {console.error("[token-auth] getTokensFromResponse error:", error);@@ -308,15 +308,15 @@ export function generateAccessToken(): string {}/**- * Get calendar permission from access token- * Used by permission checks to grant token-based access+ * Get the permission bundle granted by an access token for a calendar.+ * Used by permission checks to grant token-based access.** @param calendarId - The calendar ID to check- * @returns Permission level or null if no token grants access+ * @returns Bundle id or null if no token grants access*/-export async function getTokenPermission(+export async function getTokenBundleId(calendarId: string-): Promise<"read" | "write" | null> {+): Promise<string | null> {try {const tokens = await getTokensFromCookie();@@ -333,15 +333,15 @@ export async function getTokenPermission(const validation = await validateAccessToken(tokenData.token);if (validation && validation.calendarId === calendarId) {- // Found a valid token - return its permission- return validation.permission;+ // Found a valid token - return its bundle+ return validation.bundleId;}}// No valid tokens foundreturn null;} catch (error) {- console.error("[token-auth] getTokenPermission error:", error);+ console.error("[token-auth] getTokenBundleId error:", error);return null;}}diff --git a/lib/db/schema.ts b/lib/db/schema.tsindex 33f4923..54214a7 100644--- a/lib/db/schema.ts+++ b/lib/db/schema.ts@@ -10,6 +10,7 @@ import type {CalendarViewSettings,PersonalViewSettings,} from "../view-settings";+import type { Capability } from "../permission-bundles";// =====================================================// Better Auth Tables (generated by @better-auth/cli)@@ -122,16 +123,13 @@ export const calendars = sqliteTable(ownerId: text("owner_id").references(() => user.id, {onDelete: "set null",}),- guestPermission: text("guest_permission", {- enum: ["none", "read", "write"],- })- .notNull()- .default("none"),- // Whether read-only members may sign themselves up for a shift without- // write access. Owner/admin can turn this off to require assignment instead.- allowSelfSignup: integer("allow_self_signup", { mode: "boolean" })- .notNull()- .default(true),+ // Bundle granted to guests/subscribed users via the public-access link;+ // null = no guest access (replaces the old guestPermission enum below).+ // Not a typed FK — calendarPermissionBundles.calendarId already points+ // back at this table, and Drizzle/TS can't infer a two-table reference+ // cycle. Bundles can't be deleted while assigned (enforced at the app+ // layer), so integrity holds without a DB-level constraint here.+ guestBundleId: text("guest_bundle_id"),// Master switch for the whole shift-signup feature on this calendar.// Owner/admin only; off hides capacity, signup lists and badges everywhere.signupsEnabled: integer("signups_enabled", { mode: "boolean" })@@ -151,6 +149,43 @@ export const calendars = sqliteTable((table) => [index("calendars_ownerId_idx").on(table.ownerId)]);+// Owner-defined, per-calendar capability bundle. Replaces the old fixed+// read/write/admin ladder — see lib/permission-bundles.ts for the catalog.+export const calendarPermissionBundles = sqliteTable(+ "calendar_permission_bundles",+ {+ id: text("id")+ .primaryKey()+ .$defaultFn(() => crypto.randomUUID()),+ calendarId: text("calendar_id")+ .notNull()+ .references(() => calendars.id, { onDelete: "cascade" }),+ name: text("name").notNull(),+ // Set for the four seeded bundles (read/contribute/manage/admin), null+ // once renamed. While set, the UI shows the translated standard name+ // instead of `name` (which stays as an English fallback).+ seedKey: text("seed_key", {+ enum: ["read", "contribute", "manage", "admin"],+ }),+ capabilities: text("capabilities", { mode: "json" })+ .$type<Capability[]>()+ .notNull(),+ 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_permission_bundles_calendarId_idx").on(table.calendarId),+ uniqueIndex("calendar_permission_bundles_calendarId_seedKey_idx")+ .on(table.calendarId, table.seedKey)+ .where(sql`${table.seedKey} is not null`),+ ]+);+export const calendarShares = sqliteTable("calendar_shares",{@@ -163,9 +198,13 @@ export const calendarShares = sqliteTable(userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),- permission: text("permission", { enum: ["admin", "write", "read"] })+ // restrict, not cascade: deleting a bundle must never silently delete+ // shares — the app checks usage first and rejects deletion (see plan).+ bundleId: text("bundle_id").notNull()- .default("read"),+ .references(() => calendarPermissionBundles.id, {+ onDelete: "restrict",+ }),sharedBy: text("shared_by").notNull().references(() => user.id, { onDelete: "cascade" }),@@ -176,6 +215,7 @@ export const calendarShares = sqliteTable((table) => [index("calendar_shares_calendarId_idx").on(table.calendarId),index("calendar_shares_userId_idx").on(table.userId),+ index("calendar_shares_bundleId_idx").on(table.bundleId),]);@@ -304,6 +344,12 @@ export const shifts = sqliteTable("shifts", {syncedFromExternal: integer("synced_from_external", { mode: "boolean" }).notNull().default(false),+ // null = no known creator (pre-migration data, anonymous guest, or the+ // creating user was later deleted) — counts as "own" for anyone with the+ // Own capability, see hasOwnedCapability().+ createdBy: text("created_by").references(() => user.id, {+ onDelete: "set null",+ }),createdAt: integer("created_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),@@ -335,6 +381,10 @@ export const shiftPresets = sqliteTable("shift_presets", {// Copied into signupCapacity on shifts created from this presetdefaultSignupCapacity: integer("default_signup_capacity"),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`),@@ -356,6 +406,10 @@ export const calendarNotes = sqliteTable("calendar_notes", {color: text("color"), // for events onlyrecurringPattern: text("recurring_pattern").notNull().default("none"), // none, custom-weeks, custom-monthsrecurringInterval: integer("recurring_interval"), // for custom pattern (e.g., every 3 months)+ // 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`),@@ -432,9 +486,12 @@ export const calendarAccessTokens = sqliteTable(.references(() => calendars.id, { onDelete: "cascade" }),token: text("token").notNull().unique(), // base64url encoded, 43 charsname: text("name"), // Optional label (e.g., "Family Link")- permission: text("permission", { enum: ["read", "write"] })+ // restrict, not cascade: see calendarShares.bundleId above.+ bundleId: text("bundle_id").notNull()- .default("read"),+ .references(() => calendarPermissionBundles.id, {+ onDelete: "restrict",+ }),expiresAt: integer("expires_at", { mode: "timestamp" }), // null = never expirescreatedBy: text("created_by").notNull()@@ -453,6 +510,7 @@ export const calendarAccessTokens = sqliteTable(table.isActive),index("calendar_access_tokens_createdBy_idx").on(table.createdBy),+ index("calendar_access_tokens_bundleId_idx").on(table.bundleId),]);@@ -493,6 +551,11 @@ export type NewCalendar = typeof calendars.$inferInsert;export type CalendarAccessToken = typeof calendarAccessTokens.$inferSelect;export type NewCalendarAccessToken = typeof calendarAccessTokens.$inferInsert;+export type CalendarPermissionBundle =+ typeof calendarPermissionBundles.$inferSelect;+export type NewCalendarPermissionBundle =+ typeof calendarPermissionBundles.$inferInsert;+export type ExternalSync = typeof externalSyncs.$inferSelect;export type NewExternalSync = typeof externalSyncs.$inferInsert;@@ -559,6 +622,11 @@ export const calendarsRelations = relations(calendars, ({ one, many }) => ({shares: many(calendarShares),subscriptions: many(userCalendarSubscriptions),accessTokens: many(calendarAccessTokens),+ permissionBundles: many(calendarPermissionBundles),+ guestBundle: one(calendarPermissionBundles, {+ fields: [calendars.guestBundleId],+ references: [calendarPermissionBundles.id],+ }),shifts: many(shifts),presets: many(shiftPresets),notes: many(calendarNotes),@@ -566,6 +634,18 @@ export const calendarsRelations = relations(calendars, ({ one, many }) => ({syncLogs: many(syncLogs),}));+export const calendarPermissionBundlesRelations = relations(+ calendarPermissionBundles,+ ({ one, many }) => ({+ calendar: one(calendars, {+ fields: [calendarPermissionBundles.calendarId],+ references: [calendars.id],+ }),+ shares: many(calendarShares),+ accessTokens: many(calendarAccessTokens),+ })+);+export const shiftsRelations = relations(shifts, ({ one, many }) => ({calendar: one(calendars, {fields: [shifts.calendarId],@@ -576,6 +656,32 @@ export const shiftsRelations = relations(shifts, ({ one, many }) => ({references: [shiftPresets.id],}),signups: many(shiftSignups),+ creator: one(user, {+ fields: [shifts.createdBy],+ references: [user.id],+ }),+}));++export const shiftPresetsRelations = relations(shiftPresets, ({ one }) => ({+ calendar: one(calendars, {+ fields: [shiftPresets.calendarId],+ references: [calendars.id],+ }),+ creator: one(user, {+ fields: [shiftPresets.createdBy],+ references: [user.id],+ }),+}));++export const calendarNotesRelations = relations(calendarNotes, ({ one }) => ({+ calendar: one(calendars, {+ fields: [calendarNotes.calendarId],+ references: [calendars.id],+ }),+ creator: one(user, {+ fields: [calendarNotes.createdBy],+ references: [user.id],+ }),}));export const shiftSignupsRelations = relations(shiftSignups, ({ one }) => ({@@ -606,6 +712,10 @@ export const calendarSharesRelations = relations(calendarShares, ({ one }) => ({fields: [calendarShares.sharedBy],references: [user.id],}),+ bundle: one(calendarPermissionBundles, {+ fields: [calendarShares.bundleId],+ references: [calendarPermissionBundles.id],+ }),}));export const userCalendarSubscriptionsRelations = relations(@@ -650,5 +760,9 @@ export const calendarAccessTokensRelations = relations(fields: [calendarAccessTokens.createdBy],references: [user.id],}),+ bundle: one(calendarPermissionBundles, {+ fields: [calendarAccessTokens.bundleId],+ references: [calendarPermissionBundles.id],+ }),}));diff --git a/lib/permission-bundles.ts b/lib/permission-bundles.tsnew file mode 100644index 0000000..a7238f6--- /dev/null+++ b/lib/permission-bundles.ts@@ -0,0 +1,279 @@+/**+ * Capability catalog for calendar permission bundles.+ *+ * Replaces the old fixed read/write/admin ladder: an owner defines what a+ * named bundle means per calendar by ticking capabilities, instead of the+ * app hard-coding what "write" bundles together. See docs/PERMISSIONS.md+ * for the full design.+ */++export const CAPABILITIES = [+ // View+ "viewShifts",+ "viewNotesEvents",+ "viewStats",+ // Shifts+ "stampPreset",+ "createShift",+ "editOwnShift",+ "editAnyShift",+ "deleteOwnShift",+ "deleteAnyShift",+ // Notes & events+ "manageOwnNotesEvents",+ "manageAnyNotesEvents",+ // Signups+ "signUpSelf",+ "signUpOthers",+ // Presets+ "createPreset",+ "manageOwnPresets",+ "manageAnyPresets",+ // External sync+ "manageExternalSync",+ "deleteSyncLogs",+ // Administrative — never assignable to a guest/link source, see isGuestEligible()+ "manageShares",+ "manageGuestAccess",+ "manageCalendarSettings",+] as const;++export type Capability = (typeof CAPABILITIES)[number];++export type CapabilityGroupKey =+ | "view"+ | "shifts"+ | "notesEvents"+ | "signups"+ | "presets"+ | "externalSync"+ | "administration";++/** Groups CAPABILITIES for display (Bundle editor, 5.1) — order matches the catalog above. */+export const CAPABILITY_GROUPS: ReadonlyArray<{+ key: CapabilityGroupKey;+ capabilities: readonly Capability[];+}> = [+ { key: "view", capabilities: ["viewShifts", "viewNotesEvents", "viewStats"] },+ {+ key: "shifts",+ capabilities: [+ "stampPreset",+ "createShift",+ "editOwnShift",+ "editAnyShift",+ "deleteOwnShift",+ "deleteAnyShift",+ ],+ },+ { key: "notesEvents", capabilities: ["manageOwnNotesEvents", "manageAnyNotesEvents"] },+ { key: "signups", capabilities: ["signUpSelf", "signUpOthers"] },+ { key: "presets", capabilities: ["createPreset", "manageOwnPresets", "manageAnyPresets"] },+ { key: "externalSync", capabilities: ["manageExternalSync", "deleteSyncLogs"] },+ {+ key: "administration",+ capabilities: ["manageShares", "manageGuestAccess", "manageCalendarSettings"],+ },+];++const CAPABILITY_SET: ReadonlySet<string> = new Set(CAPABILITIES);++/**+ * Capabilities a bundle may never hold if it's reachable by a guest/link+ * source (access token, or calendars.guestBundleId) — enforced both when+ * offering bundles for assignment and again in hasCapability() itself.+ * manageExternalSync/deleteSyncLogs joined this set alongside the three+ * original administrative capabilities: external sync touches credentials+ * and URLs, which is a deliberate behavior change for pre-existing+ * guest/link access at the "write" level (see the Stufe-1b data migration).+ */+const GUEST_INELIGIBLE: ReadonlySet<Capability> = new Set([+ "manageShares",+ "manageGuestAccess",+ "manageCalendarSettings",+ "manageExternalSync",+ "deleteSyncLogs",+]);++export function isGuestEligible(capabilities: readonly Capability[]): boolean {+ return capabilities.every((c) => !GUEST_INELIGIBLE.has(c));+}++export function isAdminOnlyCapability(capability: Capability): boolean {+ return GUEST_INELIGIBLE.has(capability);+}++/** Whether this capability set can change a shift at all — shared by useCalendarPermission's canEdit and calendar-switcher's read-only badge. */+export function hasEditCapability(capabilities: readonly Capability[]): boolean {+ return (+ capabilities.includes("createShift") ||+ capabilities.includes("editOwnShift") ||+ capabilities.includes("editAnyShift")+ );+}++/** Strips admin-only capabilities from a guest/link-sourced capability list — the GUEST_INELIGIBLE ceiling. */+export function applyGuestCeiling(capabilities: readonly Capability[]): Capability[] {+ return capabilities.filter((c) => !isAdminOnlyCapability(c));+}++/** Whitelists a JSON value down to known capability keys, deduped. Unknown/malformed input yields []. */+export function sanitizeCapabilities(input: unknown): Capability[] {+ if (!Array.isArray(input)) return [];+ const result = new Set<Capability>();+ for (const value of input) {+ if (typeof value === "string" && CAPABILITY_SET.has(value)) {+ result.add(value as Capability);+ }+ }+ return Array.from(result);+}++/** Applies sanitizeCapabilities() to a bundle row read straight from the DB. */+export function sanitizeBundle<T extends { capabilities: unknown }>(+ bundle: T+): T & { capabilities: Capability[] } {+ return { ...bundle, capabilities: sanitizeCapabilities(bundle.capabilities) };+}++/**+ * Capability dependencies (S3 — enforced server-side, the UI just reflects+ * them by ticking the dependency visibly). Applied to a fixed point by+ * normalizeCapabilities() below, so listing a capability once here is+ * enough even if the dependency chain is more than one hop.+ */+const CAPABILITY_DEPENDENCIES: Partial<Record<Capability, Capability[]>> = {+ stampPreset: ["viewShifts"],+ createShift: ["viewShifts"],+ editOwnShift: ["viewShifts"],+ editAnyShift: ["editOwnShift"],+ deleteOwnShift: ["viewShifts"],+ deleteAnyShift: ["deleteOwnShift"],+ manageOwnNotesEvents: ["viewNotesEvents"],+ manageAnyNotesEvents: ["manageOwnNotesEvents"],+ signUpSelf: ["viewShifts"],+ signUpOthers: ["viewShifts"],+ createPreset: ["viewShifts"],+ manageOwnPresets: ["viewShifts"],+ manageAnyPresets: ["manageOwnPresets"],+ manageExternalSync: ["viewShifts"],+};++/**+ * Sanitizes a raw capability list and expands it to satisfy every+ * dependency in CAPABILITY_DEPENDENCIES (S3). Use this instead of+ * sanitizeCapabilities() whenever a bundle's capabilities are being saved;+ * use plain sanitizeCapabilities() for read-only display where dependencies+ * are already guaranteed to hold.+ */+/**+ * Which of the currently-ticked capabilities directly require `capability`+ * — i.e. removing it would immediately be undone by normalizeCapabilities().+ * Empty when `capability` can be safely removed. Only direct dependents need+ * checking: since `capabilities` is always already normalized (closed under+ * CAPABILITY_DEPENDENCIES), anything depending on `capability` transitively+ * has its own direct link to it already ticked too, and that direct link is+ * what triggers the re-add.+ */+export function getBlockingDependents(+ capability: Capability,+ capabilities: readonly Capability[]+): Capability[] {+ return capabilities.filter(+ (c) => c !== capability && (CAPABILITY_DEPENDENCIES[c] ?? []).includes(capability)+ );+}++export function normalizeCapabilities(input: unknown): Capability[] {+ const result = new Set<Capability>(sanitizeCapabilities(input));+ let changed = true;+ while (changed) {+ changed = false;+ for (const capability of result) {+ for (const dependency of CAPABILITY_DEPENDENCIES[capability] ?? []) {+ if (!result.has(dependency)) {+ result.add(dependency);+ changed = true;+ }+ }+ }+ }+ return CAPABILITIES.filter((c) => result.has(c));+}++export type BundleSeedKey = "read" | "contribute" | "manage" | "admin";++/** Client-safe bundle identity — id/name/seedKey only, no capabilities. */+export interface BundleRef {+ id: string;+ name: string;+ seedKey: BundleSeedKey | null;+}++export interface BundleDefinition {+ name: string;+ seedKey: BundleSeedKey;+ capabilities: Capability[];+}++const READ_BASE: Capability[] = [+ "viewShifts",+ "viewNotesEvents",+ "viewStats",+ // E5: new calendars' Read bundle grants self-signup out of the box,+ // matching the old default of allowSelfSignup = true.+ "signUpSelf",+];+const CONTRIBUTE_BASE: Capability[] = [+ ...READ_BASE,+ "stampPreset",+ "createShift",+ "createPreset",+ "editOwnShift",+ "deleteOwnShift",+ "manageOwnPresets",+ "manageOwnNotesEvents",+];+const MANAGE_BASE: Capability[] = [+ ...CONTRIBUTE_BASE,+ "editAnyShift",+ "deleteAnyShift",+ "manageAnyPresets",+ "manageAnyNotesEvents",+ "signUpOthers",+];+const ADMIN_BASE: Capability[] = [+ ...MANAGE_BASE,+ "manageExternalSync",+ "deleteSyncLogs",+ "manageShares",+ "manageGuestAccess",+ "manageCalendarSettings",+];++/**+ * Recommended defaults for a newly created calendar (5.4): creating shifts+ * and presets stays available at Contribute, editing/deleting someone+ * else's entry requires Manage, and external sync config/sync-log deletion+ * require Admin (touches external credentials/URLs).+ */+export function defaultBundleDefinitionsForNewCalendar(): BundleDefinition[] {+ return [+ { name: "Read", seedKey: "read", capabilities: [...READ_BASE] },+ {+ name: "Contribute",+ seedKey: "contribute",+ capabilities: [...CONTRIBUTE_BASE],+ },+ { name: "Manage", seedKey: "manage", capabilities: [...MANAGE_BASE] },+ { name: "Admin", seedKey: "admin", capabilities: [...ADMIN_BASE] },+ ];+}++// Existing-calendar migration bundles are hand-written directly into+// drizzle/0020_backfill_permission_bundles.sql (a frozen, one-time SQL+// snapshot of an earlier version of this same shape) rather than generated+// from this file at migration time — see that file's header comment for+// why. The Own/Any rename and guest lockout for pre-existing bundles is a+// second, equally frozen snapshot in+// drizzle/0023_permission_bundles_own_any.sql.diff --git a/lib/query-keys.ts b/lib/query-keys.tsindex e737aca..1fab139 100644--- a/lib/query-keys.ts+++ b/lib/query-keys.ts@@ -55,6 +55,8 @@ export const queryKeys = {list: (params: object) => ["admin", "calendars", "list", params] as const,detail: (calendarId: string) =>["admin", "calendars", "detail", calendarId] as const,+ bundles: (calendarId: string) =>+ ["admin", "calendars", "bundles", calendarId] as const,},auditLogsAll: ["admin", "audit-logs"] as const,auditLogs: (filters?: object) => ["admin", "audit-logs", filters] as const,@@ -68,6 +70,10 @@ export const queryKeys = {tokens: {byCalendar: (calendarId: string) => ["tokens", calendarId] as const,},+ permissionBundles: {+ byCalendar: (calendarId: string) =>+ ["permission-bundles", calendarId] as const,+ },subscriptions: {all: ["subscriptions"] as const,},diff --git a/lib/rate-limiter.ts b/lib/rate-limiter.tsindex 645dbce..bc93a35 100644--- a/lib/rate-limiter.ts+++ b/lib/rate-limiter.ts@@ -27,6 +27,8 @@* - RATE_LIMIT_TOKEN_CREATION_WINDOW* - RATE_LIMIT_USER_SEARCH_REQUESTS - User directory search (per user)* - RATE_LIMIT_USER_SEARCH_WINDOW+ * - RATE_LIMIT_BUNDLE_MUTATIONS_REQUESTS - Permission bundle create/update/delete/clone (per calendar)+ * - RATE_LIMIT_BUNDLE_MUTATIONS_WINDOW*/import { NextRequest, NextResponse } from "next/server";@@ -177,6 +179,18 @@ const config = {10) * 1000, // 1 minute},+ // Permission bundle create/update/delete/clone, keyed per calendar like+ // tokenCreation/externalSync — an owner editing their group setup is+ // bursty, but shouldn't be able to hammer the endpoint.+ bundleMutations: {+ requests: parseInt(+ process.env.RATE_LIMIT_BUNDLE_MUTATIONS_REQUESTS || "30",+ 10+ ),+ windowMs:+ parseInt(process.env.RATE_LIMIT_BUNDLE_MUTATIONS_WINDOW || "3600", 10) *+ 1000, // 1 hour+ },};/**@@ -203,6 +217,7 @@ const limitsByType = {"admin-user-create": config.adminUserCreate,"admin-bulk-operations": config.adminBulkOperations,"admin-calendar-mutations": config.adminCalendarMutations,+ "bundle-mutations": config.bundleMutations,} as const;export type RateLimitType = keyof typeof limitsByType;@@ -406,7 +421,9 @@ export function rateLimit(// Special handling for resource-based limits (e.g., token-creation per calendar)let identifier: string;if (- (type === "token-creation" || type === "external-sync") &&+ (type === "token-creation" ||+ type === "external-sync" ||+ type === "bundle-mutations") &&resourceId) {identifier = `calendar:${resourceId}`;diff --git a/lib/shift-signups.ts b/lib/shift-signups.tsindex ea5fe94..b7656fa 100644--- a/lib/shift-signups.ts+++ b/lib/shift-signups.ts@@ -1,10 +1,7 @@import { db } from "@/lib/db";import { shifts, shiftSignups } from "@/lib/db/schema";import { eq, inArray } from "drizzle-orm";-import {- getShiftSignupPermission,- getUserCalendarPermission,-} from "@/lib/auth/permissions";+import { getShiftSignupPermission, canViewCalendar } from "@/lib/auth/permissions";import type { CalendarMember, ShiftSignupUser } from "@/lib/types";export type AddShiftSignupResult =@@ -82,11 +79,8 @@ export async function addShiftSignup(// The assigned user must already have access to the calendar, otherwise// they would have no way to see a shift they are signed up for.if (targetUserId !== requestingUserId) {- const targetPermission = await getUserCalendarPermission(- targetUserId,- calendarId- );- if (!targetPermission) {+ const targetHasAccess = await canViewCalendar(targetUserId, calendarId);+ if (!targetHasAccess) {return {ok: false,error: "Target user has no access to this calendar",diff --git a/lib/types.ts b/lib/types.tsindex 138073f..cd37666 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -1,26 +1,32 @@import type { CalendarViewSettings } from "./view-settings";+import type { BundleRef, Capability } from "./permission-bundles";// Re-export types from Drizzle schemaexport type { Calendar, Shift, ExternalSync } from "./db/schema";+/** The bundle identity behind a caller's effective access — null for the owner. */+export type CalendarBundleRef = BundleRef;+export interface CalendarWithCount {id: string;name: string;color: string;ownerId?: string | null;- guestPermission?: "none" | "read" | "write";- allowSelfSignup?: boolean;+ guestBundleId?: string | null;signupsEnabled?: boolean;/** The calendar's own view; null means everyone sees their personal view */viewSettings?: CalendarViewSettings | null;createdAt: Date | null;updatedAt: Date | null;_count?: number;- // Permission metadata (only for authenticated users)- sharePermission?: "owner" | "admin" | "write" | "read";- tokenPermission?: "read" | "write"; // Permission from access token+ // Effective access for the current caller (Stufe 2) — replaces the old+ // sharePermission/tokenPermission/guestPermission enum fields.+ capabilities?: Capability[];+ bundle?: CalendarBundleRef | null;isSubscribed?: boolean;subscriptionSource?: "guest" | "shared" | "token";+ canSignUpSelf?: boolean;+ canSignUpOthers?: boolean;}export interface ShiftWithCalendar {@@ -43,6 +49,9 @@ export interface ShiftWithCalendar {externalSyncId?: string | null;signupCapacity?: number | null;signups?: ShiftSignupUser[];+ // 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;createdAt: Date | null;updatedAt: Date | null;}diff --git a/messages/cs.json b/messages/cs.jsonindex 51404fa..ff81e7e 100644--- a/messages/cs.json+++ b/messages/cs.json@@ -69,9 +69,6 @@"severity": "Závažnost","permission": "Oprávnění","permissions": {- "admin": "Správce",- "read": "Čtení",- "write": "Zápis","none": "Bez přístupu"},"notes": "Poznámky",@@ -263,6 +260,7 @@"month": "Měsíc","year": "Rok","noData": "V tomto období žádné směny",+ "noPermission": "Nemáte oprávnění zobrazit statistiky tohoto kalendáře","hours": "Hodiny","overview": "Přehled","distribution": "Rozložení",@@ -421,13 +419,11 @@},"share": {"publicAccess": "Veřejný přístup",- "public": "Veřejné","links": "Odkazy","share": "sdílení","searchUser": "Hledat uživatele","searchUserPlaceholder": "Zadejte jméno nebo e-mail...","noSharesDescription": "Sdílejte tento kalendář s ostatními uživateli pro spolupráci",- "publicPermissionNoneDesc": "Přístup máte jen vy, pozvaní lidé a držitelé přístupového odkazu.","shareAdded": "Kalendář byl úspěšně sdílen","shareUpdated": "Oprávnění bylo úspěšně aktualizováno","shareRemoved": "Přístup byl úspěšně odebrán",@@ -436,10 +432,6 @@"removeShareConfirmDesc": "Opravdu chcete odebrat přístup uživateli {user}? Už nebude moci tento kalendář zobrazit ani upravovat.","you": "Vy","sharedWithYou": "Sdíleno s vámi",- "publicPermissionReadDescGuestsOn": "Kalendář může zobrazit kdokoli, i bez účtu. Přihlášení uživatelé si ho přidají přes „Sdílené kalendáře“.",- "publicPermissionWriteDescGuestsOn": "Kalendář může zobrazit a upravovat kdokoli, i bez účtu. Přihlášení uživatelé si ho přidají přes „Sdílené kalendáře“.",- "publicPermissionReadDescGuestsOff": "Přihlášení uživatelé této instance si kalendář mohou přidat a zobrazit přes „Sdílené kalendáře“. Bez účtu přístup není možný, protože přístup pro hosty je na této instanci vypnutý.",- "publicPermissionWriteDescGuestsOff": "Přihlášení uživatelé této instance si kalendář mohou přidat, zobrazit a upravovat přes „Sdílené kalendáře“. Bez účtu přístup není možný, protože přístup pro hosty je na této instanci vypnutý.","publicAccessDescriptionGuestsOn": "Určete veřejný přístup pro přihlášené uživatele a návštěvníky bez účtu.","publicAccessDescriptionGuestsOff": "Určete veřejný přístup pro přihlášené uživatele této instance."},@@ -772,8 +764,8 @@"presetsHint": "{count, plural, =0 {Zatím žádné šablony} one {# šablona} few {# šablony} other {# šablon}}","external": "Externí kalendáře","externalHint": "{count, plural, =0 {Odběr, zobrazení, interval} one {# odběr, zobrazení, interval} few {# odběry, zobrazení, interval} other {# odběrů, zobrazení, interval}}",- "sharing": "Sdílení",- "sharingHint": "{count, plural, =0 {Lidé, veřejný přístup, odkazy} one {Lidé, veřejný přístup, # aktivní odkaz} few {Lidé, veřejný přístup, # aktivní odkazy} other {Lidé, veřejný přístup, # aktivních odkazů}}",+ "permissions": "Oprávnění",+ "permissionsHint": "{count, plural, =0 {Skupiny, přiřazení, odkazy} one {Skupiny, přiřazení, # aktivní odkaz} few {Skupiny, přiřazení, # aktivní odkazy} other {Skupiny, přiřazení, # aktivních odkazů}}","export": "Export","exportHint": "Soubor ICS nebo PDF","view": "Zobrazení kalendáře",@@ -834,18 +826,10 @@"statusSuccess": "Úspěšné"},"sharingSheet": {- "tabPeople": "Lidé","invite": "Pozvat",- "haveAccess": "Mají přístup","owner": "Vlastník",- "permRead": "Jen čtení",- "permWrite": "Úpravy",- "permReadDesc": "Prohlížet kalendář, nic neměnit",- "permWriteDesc": "Vytvářet a mazat směny",- "permAdminDesc": "Navíc spravovat sdílení a nastavení","changePermission": "Změnit oprávnění pro {name}","accessNone": "Bez přístupu",- "guestNoneShort": "Jen pozvaní a odkazy","activeLinks": "Aktivní odkazy","inactiveLinks": "Deaktivované nebo prošlé","noActiveLinks": "Žádný aktivní odkaz",@@ -867,14 +851,8 @@"copyNowBody": "Po zavření už token nepůjde znovu zobrazit. Pokud se ztratí, vytvořte nový a tento zrušte.","shareLinkLabel": "Odkaz ke sdílení","copied": "Zkopírováno",- "guestReadShortGuestsOn": "Všichni mohou prohlížet",- "guestWriteShortGuestsOn": "Všichni mohou upravovat",- "guestReadShortGuestsOff": "Přihlášení mohou prohlížet",- "guestWriteShortGuestsOff": "Přihlášení mohou upravovat","linkInfoGuestsOn": "Odkaz otevře kalendář přímo, bez přihlášení. V seznamu ho můžete kdykoli zrušit — pak okamžitě přestane platit.","linkInfoGuestsOff": "Odkaz otevře kalendář přímo. Přístup pro hosty je na této instanci vypnutý, takže se příjemci musí přihlásit. V seznamu ho můžete kdykoli zrušit — pak okamžitě přestane platit.",- "allowSelfSignupLabel": "Samostatné přihlašování na směny",- "allowSelfSignupDesc": "Členové jen se čtením se mohou sami přihlásit i odhlásit ze směny","signupsEnabledLabel": "Povolit přihlašování na směny","signupsEnabledDesc": "Umožní lidem přihlásit se na směny. Po vypnutí zmizí seznamy přihlášených, avatary i maximální počet osob."},@@ -1072,10 +1050,9 @@"filterShared": "Sdílené","filterSynced": "Se synchronizací","guestColumn": "Přístup hosta",+ "guestBundleHint": "Kdokoli s odkazem má přístup ke kalendáři podle této skupiny","guestNoneHint": "Kalendář vidí jen lidé, se kterými je sdílený","guestPermissionValue": "Oprávnění hosta: {permission}",- "guestReadHint": "Kdokoli s odkazem kalendář uvidí",- "guestWriteHint": "Kdokoli s odkazem může kalendář upravovat","publicAccess": "Veřejný přístup","selectAll": "Vybrat vše","selectedCount": "Vybráno: {count}",@@ -1107,5 +1084,93 @@"removeFailed": "Odhlášení se nezdařilo"},"addOtherHint": "Nemůžete někoho najít? Nejdřív s ním sdílejte kalendář, pak ho tu budete moct vybrat."+ },+ "permissionBundles": {+ "bundle": "Skupina oprávnění",+ "title": "Oprávnění",+ "tabGroups": "Skupiny",+ "tabAssignments": "Přiřazení",+ "tabMore": "Další",+ "people": "Lidé",+ "inviteAs": "Pozvat jako",+ "cloneSuffix": "(Kopie)",+ "newBundle": "Vytvořit novou skupinu",+ "newBundleNamePlaceholder": "např. Jen víkend",+ "usedByCount": "{count, plural, =0 {Nepřiřazeno} one {Použito v # přiřazení} few {Použito v # přiřazeních} other {Použito v # přiřazeních}}",+ "clone": "Duplikovat",+ "deleteConfirmTitle": "Smazat skupinu?",+ "deleteConfirmDesc": "Opravdu smazat skupinu „{name}“? Tuto akci nelze vrátit zpět.",+ "guestLockedHint": "Tato skupina je přiřazena k hostovskému přístupu nebo odkazu. Správcovská práva nelze hostům nikdy udělit.",+ "stampPresetBypassWarning": "Bez „Vytvářet směny“ lze toto omezení obejít: kdo smí vytvářet předvolby, může vytvořit libovolnou a poté ji použít jako razítko.",+ "requiredByHint": "Nelze odebrat, dokud je aktivní „{capability}“",+ "signupsCapabilityHint": "Kdo se smí přihlásit sám nebo přihlásit ostatní na směny, se nastavuje po skupinách na kartě „Skupiny“ (práva „Přihlásit se“ / „Přihlásit ostatní“).",+ "signupsLocked": "Zapnout nebo vypnout přihlašování může jen ten, kdo smí spravovat nastavení kalendáře.",+ "usageShares": "{count, plural, one {# sdílení} few {# sdílení} other {# sdílení}}",+ "usageTokens": "{count, plural, one {# odkaz} few {# odkazy} other {# odkazů}}",+ "usageGuestAccess": "hostovský přístup",+ "deleteInUse": "Stále používáno: {usage}",+ "nameTaken": "Skupina s tímto názvem už existuje",+ "bundlesUnavailable": "Skupiny oprávnění se nepodařilo načíst, tato akce proto není k dispozici.",+ "seed": {+ "read": "Čtení",+ "contribute": "Přispívání",+ "manage": "Správa",+ "admin": "Administrace"+ },+ "groups": {+ "view": "Zobrazení",+ "shifts": "Směny",+ "notesEvents": "Poznámky a události",+ "signups": "Přihlášky",+ "presets": "Předvolby",+ "externalSync": "Externí synchronizace",+ "administration": "Administrace"+ },+ "capabilityLabels": {+ "viewShifts": "Zobrazit směny",+ "viewNotesEvents": "Zobrazit poznámky a události",+ "viewStats": "Zobrazit statistiky",+ "stampPreset": "Razítkovat předvolby",+ "createShift": "Vytvářet směny",+ "editOwnShift": "Upravovat vlastní směny",+ "editAnyShift": "Upravovat všechny směny",+ "deleteOwnShift": "Mazat vlastní směny",+ "deleteAnyShift": "Mazat všechny směny",+ "manageOwnNotesEvents": "Spravovat vlastní poznámky a události",+ "manageAnyNotesEvents": "Spravovat všechny poznámky a události",+ "signUpSelf": "Přihlásit se sám",+ "signUpOthers": "Přihlašovat ostatní",+ "createPreset": "Vytvářet předvolby",+ "manageOwnPresets": "Spravovat vlastní předvolby",+ "manageAnyPresets": "Spravovat všechny předvolby",+ "manageExternalSync": "Spravovat externí synchronizaci",+ "deleteSyncLogs": "Mazat protokoly synchronizace",+ "manageShares": "Spravovat sdílení",+ "manageGuestAccess": "Spravovat hostovský přístup a odkazy",+ "manageCalendarSettings": "Spravovat nastavení kalendáře"+ },+ "capabilityHints": {+ "viewShifts": "Vidět kalendář a jeho směny",+ "viewNotesEvents": "Vidět poznámky a události v kalendáři",+ "viewStats": "Vidět souhrny a přehledy",+ "stampPreset": "Přidat existující předvolbu jako směnu",+ "createShift": "Volně vytvářet nové směny",+ "editOwnShift": "Upravovat směny, které sám vytvořil",+ "editAnyShift": "Upravovat i směny vytvořené jinými",+ "deleteOwnShift": "Mazat směny, které sám vytvořil",+ "deleteAnyShift": "Mazat i směny vytvořené jinými",+ "manageOwnNotesEvents": "Upravovat nebo mazat poznámky a události, které sám vytvořil",+ "manageAnyNotesEvents": "Upravovat nebo mazat i ty vytvořené jinými",+ "signUpSelf": "Přihlašovat se a odhlašovat ze směn s volnými místy",+ "signUpOthers": "Přihlašovat a odhlašovat jiné osoby ze směn",+ "createPreset": "Vytvářet nové předvolby",+ "manageOwnPresets": "Upravovat nebo mazat předvolby, které sám vytvořil",+ "manageAnyPresets": "Upravovat i předvolby vytvořené jinými; řídí také společné pořadí",+ "manageExternalSync": "Nastavovat a upravovat externí odběry kalendáře",+ "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í"+ }}}diff --git a/messages/de.json b/messages/de.jsonindex 84151f4..8c2de78 100644--- a/messages/de.json+++ b/messages/de.json@@ -69,9 +69,6 @@"severity": "Schweregrad","permission": "Berechtigung","permissions": {- "admin": "Admin",- "read": "Lesen",- "write": "Schreiben","none": "Keinen Zugriff"},"notes": "Notizen",@@ -263,6 +260,7 @@"month": "Monat","year": "Jahr","noData": "Keine Schichten in diesem Zeitraum",+ "noPermission": "Du hast keine Berechtigung, Statistiken für diesen Kalender anzusehen","hours": "Stunden","overview": "Übersicht","distribution": "Verteilung",@@ -421,13 +419,11 @@},"share": {"publicAccess": "Öffentlicher Zugriff",- "public": "Öffentlich","links": "Links","share": "Freigabe","searchUser": "Benutzer suchen","searchUserPlaceholder": "Name oder E-Mail eingeben...","noSharesDescription": "Teile diesen Kalender mit anderen Benutzern zur Zusammenarbeit",- "publicPermissionNoneDesc": "Nur du, eingeladene Personen und Inhaber eines Zugangslinks haben Zugriff.","shareAdded": "Kalender erfolgreich geteilt","shareUpdated": "Berechtigung erfolgreich aktualisiert","shareRemoved": "Zugriff erfolgreich entfernt",@@ -436,10 +432,6 @@"removeShareConfirmDesc": "Bist du sicher, dass du den Zugriff für {user} entfernen möchtest? Diese Person kann den Kalender dann nicht mehr sehen oder bearbeiten.","you": "Du","sharedWithYou": "Mit dir geteilt",- "publicPermissionReadDescGuestsOn": "Jeder kann den Kalender ansehen, auch ohne Konto. Angemeldete Nutzer fügen ihn über „Geteilte Kalender“ hinzu.",- "publicPermissionWriteDescGuestsOn": "Jeder kann den Kalender ansehen und bearbeiten, auch ohne Konto. Angemeldete Nutzer fügen ihn über „Geteilte Kalender“ hinzu.",- "publicPermissionReadDescGuestsOff": "Angemeldete Nutzer dieser Instanz können den Kalender über „Geteilte Kalender“ hinzufügen und ansehen. Ohne Konto ist kein Zugriff möglich, weil der Gastzugang auf dieser Instanz aus ist.",- "publicPermissionWriteDescGuestsOff": "Angemeldete Nutzer dieser Instanz können den Kalender über „Geteilte Kalender“ hinzufügen, ansehen und bearbeiten. Ohne Konto ist kein Zugriff möglich, weil der Gastzugang auf dieser Instanz aus ist.","publicAccessDescriptionGuestsOn": "Bestimme den öffentlichen Zugriff für angemeldete Nutzer und Besucher ohne Konto.","publicAccessDescriptionGuestsOff": "Bestimme den öffentlichen Zugriff für angemeldete Nutzer dieser Instanz."},@@ -772,8 +764,8 @@"presetsHint": "{count, plural, =0 {Noch keine Vorlagen} one {# Vorlage} other {# Vorlagen}}","external": "Externe Kalender","externalHint": "{count, plural, =0 {Abo, Anzeigemodus, Intervall} one {# Abo, Anzeigemodus, Intervall} other {# Abos, Anzeigemodus, Intervall}}",- "sharing": "Freigaben",- "sharingHint": "{count, plural, =0 {Personen, öffentlicher Zugriff, Links} one {Personen, öffentlicher Zugriff, # aktiver Link} other {Personen, öffentlicher Zugriff, # aktive Links}}",+ "permissions": "Berechtigungen",+ "permissionsHint": "{count, plural, =0 {Gruppen, Zuweisungen, Links} one {Gruppen, Zuweisungen, # aktiver Link} other {Gruppen, Zuweisungen, # aktive Links}}","export": "Exportieren","exportHint": "ICS-Datei oder PDF","view": "Kalenderansicht",@@ -834,18 +826,10 @@"statusSuccess": "Erfolgreich"},"sharingSheet": {- "tabPeople": "Personen","invite": "Einladen",- "haveAccess": "Zugriff haben","owner": "Eigentümer",- "permRead": "Nur lesen",- "permWrite": "Bearbeiten",- "permReadDesc": "Kalender ansehen, nichts ändern",- "permWriteDesc": "Schichten anlegen und löschen",- "permAdminDesc": "Zusätzlich Freigaben und Einstellungen verwalten","changePermission": "Berechtigung für {name} ändern","accessNone": "Kein Zugriff",- "guestNoneShort": "Nur Eingeladene und Links","activeLinks": "Aktive Links","inactiveLinks": "Deaktiviert oder abgelaufen","noActiveLinks": "Kein aktiver Link",@@ -867,14 +851,8 @@"copyNowBody": "Nach dem Schließen ist der Token nicht mehr abrufbar. Wer ihn verliert, erzeugt einen neuen und widerruft diesen.","shareLinkLabel": "Link zum Weitergeben","copied": "Kopiert",- "guestReadShortGuestsOn": "Alle können ansehen",- "guestWriteShortGuestsOn": "Alle können ändern",- "guestReadShortGuestsOff": "Angemeldete können ansehen",- "guestWriteShortGuestsOff": "Angemeldete können ändern","linkInfoGuestsOn": "Der Link öffnet den Kalender direkt, ohne Anmeldung. Er lässt sich jederzeit in der Liste widerrufen — dann ist er sofort ungültig.","linkInfoGuestsOff": "Der Link öffnet den Kalender direkt. Weil der Gastzugang auf dieser Instanz aus ist, müssen sich Empfänger anmelden. Er lässt sich jederzeit in der Liste widerrufen — dann ist er sofort ungültig.",- "allowSelfSignupLabel": "Selbstanmeldung für Schichten",- "allowSelfSignupDesc": "Nutzer mit Nur-Lese-Zugriff dürfen sich selbst für Schichten ein- und austragen","signupsEnabledLabel": "Schicht-Anmeldungen aktivieren","signupsEnabledDesc": "Erlaubt, dass sich Personen für Schichten eintragen. Ausgeschaltet verschwinden Anmeldelisten, Avatare und die maximale Personenanzahl aus der Ansicht."},@@ -1072,10 +1050,9 @@"filterShared": "Geteilt","filterSynced": "Mit Sync","guestColumn": "Gastrecht",+ "guestBundleHint": "Wer den Link kennt, hat gemäß dieser Gruppe Zugriff auf den Kalender","guestNoneHint": "Nur Personen mit Freigabe sehen den Kalender","guestPermissionValue": "Gastberechtigung: {permission}",- "guestReadHint": "Wer den Link kennt, sieht den Kalender",- "guestWriteHint": "Wer den Link kennt, kann den Kalender bearbeiten","publicAccess": "Öffentlicher Zugriff","selectAll": "Alle auswählen","selectedCount": "Ausgewählt: {count}",@@ -1107,5 +1084,93 @@"removeFailed": "Austragen ist fehlgeschlagen"},"addOtherHint": "Person nicht in der Liste? Teile den Kalender zuerst mit ihr, dann kannst du sie hier auswählen."+ },+ "permissionBundles": {+ "bundle": "Berechtigungsgruppe",+ "title": "Berechtigungen",+ "tabGroups": "Gruppen",+ "tabAssignments": "Zuweisungen",+ "tabMore": "Weiteres",+ "people": "Personen",+ "inviteAs": "Einladen als",+ "cloneSuffix": "(Kopie)",+ "newBundle": "Neue Gruppe anlegen",+ "newBundleNamePlaceholder": "z. B. Nur Wochenende",+ "usedByCount": "{count, plural, =0 {Nicht zugewiesen} one {Verwendet von # Zuweisung} other {Verwendet von # Zuweisungen}}",+ "clone": "Duplizieren",+ "deleteConfirmTitle": "Gruppe löschen?",+ "deleteConfirmDesc": "Soll die Gruppe „{name}“ wirklich gelöscht werden? Das kann nicht rückgängig gemacht werden.",+ "guestLockedHint": "Diese Gruppe ist einem Gastzugang oder Link zugewiesen. Verwaltungsrechte lassen sich Gästen nie geben.",+ "stampPresetBypassWarning": "Ohne „Schichten anlegen“ lässt sich diese Einschränkung umgehen: Wer Presets anlegen darf, kann ein beliebiges Preset erstellen und es dann stempeln.",+ "requiredByHint": "Kann nicht entfernt werden, solange „{capability}“ aktiviert ist",+ "signupsCapabilityHint": "Wer sich selbst oder andere für Schichten eintragen darf, wird pro Gruppe im Tab „Gruppen“ festgelegt (Rechte „Sich selbst eintragen“ / „Andere eintragen“).",+ "signupsLocked": "Nur wer Kalendereinstellungen verwalten darf, kann Anmeldungen ein- oder ausschalten.",+ "usageShares": "{count, plural, one {# Freigabe} other {# Freigaben}}",+ "usageTokens": "{count, plural, one {# Link} other {# Links}}",+ "usageGuestAccess": "dem Gastzugang",+ "deleteInUse": "Wird noch verwendet von: {usage}",+ "nameTaken": "Es gibt bereits eine Gruppe mit diesem Namen",+ "bundlesUnavailable": "Berechtigungsgruppen konnten nicht geladen werden. Diese Aktion ist deshalb nicht möglich.",+ "seed": {+ "read": "Lesen",+ "contribute": "Mitwirken",+ "manage": "Verwalten",+ "admin": "Administration"+ },+ "groups": {+ "view": "Ansehen",+ "shifts": "Schichten",+ "notesEvents": "Notizen & Events",+ "signups": "Anmeldungen",+ "presets": "Presets",+ "externalSync": "Externer Sync",+ "administration": "Verwaltung"+ },+ "capabilityLabels": {+ "viewShifts": "Schichten ansehen",+ "viewNotesEvents": "Notizen & Events ansehen",+ "viewStats": "Statistiken ansehen",+ "stampPreset": "Presets stempeln",+ "createShift": "Schichten anlegen",+ "editOwnShift": "Eigene Schichten bearbeiten",+ "editAnyShift": "Alle Schichten bearbeiten",+ "deleteOwnShift": "Eigene Schichten löschen",+ "deleteAnyShift": "Alle Schichten löschen",+ "manageOwnNotesEvents": "Eigene Notizen & Events verwalten",+ "manageAnyNotesEvents": "Alle Notizen & Events verwalten",+ "signUpSelf": "Sich selbst eintragen",+ "signUpOthers": "Andere eintragen",+ "createPreset": "Presets anlegen",+ "manageOwnPresets": "Eigene Presets verwalten",+ "manageAnyPresets": "Alle Presets verwalten",+ "manageExternalSync": "Externen Sync verwalten",+ "deleteSyncLogs": "Sync-Protokolle löschen",+ "manageShares": "Freigaben verwalten",+ "manageGuestAccess": "Gastzugang & Links verwalten",+ "manageCalendarSettings": "Kalendereinstellungen verwalten"+ },+ "capabilityHints": {+ "viewShifts": "Kalender und Schichten sehen",+ "viewNotesEvents": "Notizen und Events im Kalender sehen",+ "viewStats": "Auswertungen und Zusammenfassungen sehen",+ "stampPreset": "Vorhandene Presets als Schicht eintragen",+ "createShift": "Neue Schichten frei anlegen",+ "editOwnShift": "Selbst erstellte Schichten ändern",+ "editAnyShift": "Auch von anderen erstellte Schichten ändern",+ "deleteOwnShift": "Selbst erstellte Schichten löschen",+ "deleteAnyShift": "Auch von anderen erstellte Schichten löschen",+ "manageOwnNotesEvents": "Selbst erstellte Notizen und Events bearbeiten oder löschen",+ "manageAnyNotesEvents": "Auch von anderen erstellte Notizen und Events bearbeiten oder löschen",+ "signUpSelf": "Für Schichten mit offenen Plätzen ein- und austragen",+ "signUpOthers": "Andere Personen für Schichten ein- und austragen",+ "createPreset": "Neue Presets erstellen",+ "manageOwnPresets": "Selbst erstellte Presets bearbeiten oder löschen",+ "manageAnyPresets": "Auch von anderen erstellte Presets bearbeiten; steuert zusätzlich die gemeinsame Reihenfolge",+ "manageExternalSync": "Externe Kalenderabos einrichten und bearbeiten",+ "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"+ }}}diff --git a/messages/en.json b/messages/en.jsonindex 9c1aa6c..598726d 100644--- a/messages/en.json+++ b/messages/en.json@@ -69,9 +69,6 @@"severity": "Severity","permission": "Permission","permissions": {- "admin": "Admin",- "read": "Read",- "write": "Write","none": "No Access"},"notes": "Notes",@@ -263,6 +260,7 @@"month": "Month","year": "Year","noData": "No shifts in this period",+ "noPermission": "You don't have permission to view statistics for this calendar","hours": "Hours","overview": "Overview","distribution": "Distribution",@@ -421,13 +419,11 @@},"share": {"publicAccess": "Public Access",- "public": "Public","links": "Links","share": "share","searchUser": "Search user","searchUserPlaceholder": "Enter name or email...","noSharesDescription": "Share this calendar with other users to collaborate",- "publicPermissionNoneDesc": "Only you, invited people and holders of an access link have access.","shareAdded": "Calendar shared successfully","shareUpdated": "Permission updated successfully","shareRemoved": "Access removed successfully",@@ -436,10 +432,6 @@"removeShareConfirmDesc": "Are you sure you want to remove access for {user}? They will no longer be able to view or edit this calendar.","you": "You","sharedWithYou": "Shared with you",- "publicPermissionReadDescGuestsOn": "Anyone can view the calendar, even without an account. Signed-in users add it via “Shared Calendars”.",- "publicPermissionWriteDescGuestsOn": "Anyone can view and edit the calendar, even without an account. Signed-in users add it via “Shared Calendars”.",- "publicPermissionReadDescGuestsOff": "Signed-in users of this instance can add and view the calendar via “Shared Calendars”. There is no access without an account, because guest access is off on this instance.",- "publicPermissionWriteDescGuestsOff": "Signed-in users of this instance can add, view and edit the calendar via “Shared Calendars”. There is no access without an account, because guest access is off on this instance.","publicAccessDescriptionGuestsOn": "Control public access for signed-in users and visitors without an account.","publicAccessDescriptionGuestsOff": "Control public access for signed-in users of this instance."},@@ -772,8 +764,8 @@"presetsHint": "{count, plural, =0 {No presets yet} one {# preset} other {# presets}}","external": "External calendars","externalHint": "{count, plural, =0 {Subscription, display mode, interval} one {# subscription, display mode, interval} other {# subscriptions, display mode, interval}}",- "sharing": "Sharing",- "sharingHint": "{count, plural, =0 {People, public access, links} one {People, public access, # active link} other {People, public access, # active links}}",+ "permissions": "Permissions",+ "permissionsHint": "{count, plural, =0 {Groups, assignments, links} one {Groups, assignments, # active link} other {Groups, assignments, # active links}}","export": "Export","exportHint": "ICS file or PDF","view": "Calendar view",@@ -834,18 +826,10 @@"statusSuccess": "Successful"},"sharingSheet": {- "tabPeople": "People","invite": "Invite",- "haveAccess": "Have access","owner": "Owner",- "permRead": "Read only",- "permWrite": "Edit",- "permReadDesc": "View the calendar, change nothing",- "permWriteDesc": "Create and delete shifts",- "permAdminDesc": "Also manage sharing and settings","changePermission": "Change permission for {name}","accessNone": "No access",- "guestNoneShort": "Invited people and links only","activeLinks": "Active links","inactiveLinks": "Disabled or expired","noActiveLinks": "No active link",@@ -867,14 +851,8 @@"copyNowBody": "Once closed, the token cannot be retrieved again. If it gets lost, create a new one and revoke this one.","shareLinkLabel": "Link to share","copied": "Copied",- "guestReadShortGuestsOn": "Everyone can view",- "guestWriteShortGuestsOn": "Everyone can edit",- "guestReadShortGuestsOff": "Signed-in users can view",- "guestWriteShortGuestsOff": "Signed-in users can edit","linkInfoGuestsOn": "The link opens the calendar directly, without signing in. You can revoke it from the list at any time — it stops working immediately.","linkInfoGuestsOff": "The link opens the calendar directly. Guest access is off on this instance, so recipients need to sign in. You can revoke it from the list at any time — it stops working immediately.",- "allowSelfSignupLabel": "Self-signup for shifts",- "allowSelfSignupDesc": "Read-only members may sign themselves up for and withdraw from shifts","signupsEnabledLabel": "Enable shift signups","signupsEnabledDesc": "Lets people sign up for shifts. Turning this off hides signup lists, avatars, and the maximum headcount everywhere."},@@ -1072,10 +1050,9 @@"filterShared": "Shared","filterSynced": "With sync","guestColumn": "Guest access",+ "guestBundleHint": "Anyone with the link has access to the calendar according to this group","guestNoneHint": "Only people it is shared with can see the calendar","guestPermissionValue": "Guest permission: {permission}",- "guestReadHint": "Anyone with the link can see the calendar",- "guestWriteHint": "Anyone with the link can edit the calendar","publicAccess": "Public access","selectAll": "Select all","selectedCount": "Selected: {count}",@@ -1107,5 +1084,93 @@"removeFailed": "Withdrawing failed"},"addOtherHint": "Can't find someone? Share the calendar with them first, then you can pick them here."+ },+ "permissionBundles": {+ "bundle": "Permission bundle",+ "title": "Permissions",+ "tabGroups": "Groups",+ "tabAssignments": "Assignments",+ "tabMore": "More",+ "people": "People",+ "inviteAs": "Invite as",+ "cloneSuffix": "(Copy)",+ "newBundle": "Create new group",+ "newBundleNamePlaceholder": "e.g. Weekend only",+ "usedByCount": "{count, plural, =0 {Not assigned} one {Used by # assignment} other {Used by # assignments}}",+ "clone": "Duplicate",+ "deleteConfirmTitle": "Delete group?",+ "deleteConfirmDesc": "Delete the group “{name}”? This cannot be undone.",+ "guestLockedHint": "This group is assigned to guest access or a link. Administrative rights can never be given to guests.",+ "stampPresetBypassWarning": "Without “Create shifts”, this restriction can be bypassed: anyone who may create presets can create an arbitrary one and then stamp it.",+ "requiredByHint": "Can't be removed while “{capability}” is enabled",+ "signupsCapabilityHint": "Who may sign themselves or others up for shifts is set per group in the “Groups” tab (the “Sign up self” / “Sign up others” capabilities).",+ "signupsLocked": "Only someone who can manage calendar settings can turn sign-ups on or off.",+ "usageShares": "{count, plural, one {# share} other {# shares}}",+ "usageTokens": "{count, plural, one {# link} other {# links}}",+ "usageGuestAccess": "guest access",+ "deleteInUse": "Still used by: {usage}",+ "nameTaken": "A group with this name already exists",+ "bundlesUnavailable": "Permission groups could not be loaded, so this action isn't available.",+ "seed": {+ "read": "Read",+ "contribute": "Contribute",+ "manage": "Manage",+ "admin": "Admin"+ },+ "groups": {+ "view": "View",+ "shifts": "Shifts",+ "notesEvents": "Notes & Events",+ "signups": "Signups",+ "presets": "Presets",+ "externalSync": "External Sync",+ "administration": "Administration"+ },+ "capabilityLabels": {+ "viewShifts": "View shifts",+ "viewNotesEvents": "View notes & events",+ "viewStats": "View statistics",+ "stampPreset": "Stamp presets",+ "createShift": "Create shifts",+ "editOwnShift": "Edit own shifts",+ "editAnyShift": "Edit any shift",+ "deleteOwnShift": "Delete own shifts",+ "deleteAnyShift": "Delete any shift",+ "manageOwnNotesEvents": "Manage own notes & events",+ "manageAnyNotesEvents": "Manage any notes & events",+ "signUpSelf": "Sign up self",+ "signUpOthers": "Sign up others",+ "createPreset": "Create presets",+ "manageOwnPresets": "Manage own presets",+ "manageAnyPresets": "Manage any preset",+ "manageExternalSync": "Manage external sync",+ "deleteSyncLogs": "Delete sync logs",+ "manageShares": "Manage sharing",+ "manageGuestAccess": "Manage guest access & links",+ "manageCalendarSettings": "Manage calendar settings"+ },+ "capabilityHints": {+ "viewShifts": "See the calendar and its shifts",+ "viewNotesEvents": "See notes and events on the calendar",+ "viewStats": "See summaries and reports",+ "stampPreset": "Add an existing preset as a shift",+ "createShift": "Create new shifts freely",+ "editOwnShift": "Change shifts they created themselves",+ "editAnyShift": "Also change shifts created by others",+ "deleteOwnShift": "Delete shifts they created themselves",+ "deleteAnyShift": "Also delete shifts created by others",+ "manageOwnNotesEvents": "Edit or delete notes and events they created themselves",+ "manageAnyNotesEvents": "Also edit or delete notes and events created by others",+ "signUpSelf": "Sign up for and withdraw from shifts with open spots",+ "signUpOthers": "Sign other people up for and withdraw them from shifts",+ "createPreset": "Create new presets",+ "manageOwnPresets": "Edit or delete presets they created themselves",+ "manageAnyPresets": "Also edit presets created by others; also controls the shared sort order",+ "manageExternalSync": "Set up and edit external calendar subscriptions",+ "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"+ }}}diff --git a/messages/es.json b/messages/es.jsonindex 3656926..1c08884 100644--- a/messages/es.json+++ b/messages/es.json@@ -69,9 +69,6 @@"severity": "Severidad","permission": "Permiso","permissions": {- "admin": "Admin",- "read": "Lectura",- "write": "Escritura","none": "Sin acceso"},"notes": "Notas",@@ -263,6 +260,7 @@"month": "Mes","year": "Año","noData": "No hay turnos en este periodo",+ "noPermission": "No tienes permiso para ver las estadísticas de este calendario","hours": "Horas","overview": "Resumen","distribution": "Distribución",@@ -421,13 +419,11 @@},"share": {"publicAccess": "Acceso público",- "public": "Público","links": "Enlaces","share": "compartir","searchUser": "Buscar usuario","searchUserPlaceholder": "Introduce nombre o email...","noSharesDescription": "Comparte este calendario con otros usuarios para colaborar",- "publicPermissionNoneDesc": "Solo tú, las personas invitadas y quienes tengan un enlace de acceso pueden acceder.","shareAdded": "Calendario compartido con éxito","shareUpdated": "Permiso actualizado con éxito","shareRemoved": "Acceso eliminado con éxito",@@ -436,10 +432,6 @@"removeShareConfirmDesc": "¿Estás seguro de que quieres eliminar el acceso para {user}? Ya no podrá ver ni editar este calendario.","you": "Tú","sharedWithYou": "Compartido contigo",- "publicPermissionReadDescGuestsOn": "Cualquiera puede ver el calendario, incluso sin cuenta. Los usuarios autenticados lo añaden desde «Calendarios compartidos».",- "publicPermissionWriteDescGuestsOn": "Cualquiera puede ver y editar el calendario, incluso sin cuenta. Los usuarios autenticados lo añaden desde «Calendarios compartidos».",- "publicPermissionReadDescGuestsOff": "Los usuarios autenticados de esta instancia pueden añadir y ver el calendario desde «Calendarios compartidos». Sin cuenta no hay acceso, porque el acceso de invitados está desactivado en esta instancia.",- "publicPermissionWriteDescGuestsOff": "Los usuarios autenticados de esta instancia pueden añadir, ver y editar el calendario desde «Calendarios compartidos». Sin cuenta no hay acceso, porque el acceso de invitados está desactivado en esta instancia.","publicAccessDescriptionGuestsOn": "Controla el acceso público para usuarios autenticados y visitantes sin cuenta.","publicAccessDescriptionGuestsOff": "Controla el acceso público para los usuarios autenticados de esta instancia."},@@ -772,8 +764,8 @@"presetsHint": "{count, plural, =0 {Aún no hay plantillas} one {# plantilla} other {# plantillas}}","external": "Calendarios externos","externalHint": "{count, plural, =0 {Suscripción, modo de vista, intervalo} one {# suscripción, modo de vista, intervalo} other {# suscripciones, modo de vista, intervalo}}",- "sharing": "Compartir",- "sharingHint": "{count, plural, =0 {Personas, acceso público, enlaces} one {Personas, acceso público, # enlace activo} other {Personas, acceso público, # enlaces activos}}",+ "permissions": "Permisos",+ "permissionsHint": "{count, plural, =0 {Grupos, asignaciones, enlaces} one {Grupos, asignaciones, # enlace activo} other {Grupos, asignaciones, # enlaces activos}}","export": "Exportar","exportHint": "Archivo ICS o PDF","view": "Vista del calendario",@@ -834,18 +826,10 @@"statusSuccess": "Correcto"},"sharingSheet": {- "tabPeople": "Personas","invite": "Invitar",- "haveAccess": "Tienen acceso","owner": "Propietario",- "permRead": "Solo lectura",- "permWrite": "Editar",- "permReadDesc": "Ver el calendario sin cambiar nada",- "permWriteDesc": "Crear y eliminar turnos",- "permAdminDesc": "Además gestionar compartidos y ajustes","changePermission": "Cambiar el permiso de {name}","accessNone": "Sin acceso",- "guestNoneShort": "Solo invitados y enlaces","activeLinks": "Enlaces activos","inactiveLinks": "Desactivados o caducados","noActiveLinks": "Ningún enlace activo",@@ -867,14 +851,8 @@"copyNowBody": "Después de cerrar, el token ya no se puede recuperar. Si se pierde, crea uno nuevo y revoca este.","shareLinkLabel": "Enlace para compartir","copied": "Copiado",- "guestReadShortGuestsOn": "Todos pueden ver",- "guestWriteShortGuestsOn": "Todos pueden editar",- "guestReadShortGuestsOff": "Usuarios con cuenta pueden ver",- "guestWriteShortGuestsOff": "Usuarios con cuenta pueden editar","linkInfoGuestsOn": "El enlace abre el calendario directamente, sin iniciar sesión. Puedes revocarlo en la lista en cualquier momento; deja de funcionar al instante.","linkInfoGuestsOff": "El enlace abre el calendario directamente. El acceso de invitados está desactivado en esta instancia, así que los destinatarios deben iniciar sesión. Puedes revocarlo en la lista en cualquier momento; deja de funcionar al instante.",- "allowSelfSignupLabel": "Autoinscripcion a turnos",- "allowSelfSignupDesc": "Los miembros de solo lectura pueden inscribirse y darse de baja de turnos","signupsEnabledLabel": "Activar inscripciones a turnos","signupsEnabledDesc": "Permite que las personas se inscriban en turnos. Al desactivarlo desaparecen las listas de inscripción, los avatares y el número máximo de personas."},@@ -1072,10 +1050,9 @@"filterShared": "Compartidos","filterSynced": "Con sincronización","guestColumn": "Acceso invitado",+ "guestBundleHint": "Cualquiera con el enlace tiene acceso al calendario según este grupo","guestNoneHint": "Solo las personas con las que se comparte pueden ver el calendario","guestPermissionValue": "Permiso de invitado: {permission}",- "guestReadHint": "Cualquiera con el enlace puede ver el calendario",- "guestWriteHint": "Cualquiera con el enlace puede editar el calendario","publicAccess": "Acceso público","selectAll": "Seleccionar todo","selectedCount": "Seleccionados: {count}",@@ -1107,5 +1084,93 @@"removeFailed": "La baja ha fallado"},"addOtherHint": "¿No encuentras a alguien? Comparte primero el calendario con esa persona; luego podrás seleccionarla aquí."+ },+ "permissionBundles": {+ "bundle": "Grupo de permisos",+ "title": "Permisos",+ "tabGroups": "Grupos",+ "tabAssignments": "Asignaciones",+ "tabMore": "Más",+ "people": "Personas",+ "inviteAs": "Invitar como",+ "cloneSuffix": "(Copia)",+ "newBundle": "Crear nuevo grupo",+ "newBundleNamePlaceholder": "p. ej. Solo fin de semana",+ "usedByCount": "{count, plural, =0 {Sin asignar} one {Usado por # asignación} other {Usado por # asignaciones}}",+ "clone": "Duplicar",+ "deleteConfirmTitle": "¿Eliminar grupo?",+ "deleteConfirmDesc": "¿Eliminar el grupo «{name}»? Esta acción no se puede deshacer.",+ "guestLockedHint": "Este grupo está asignado a un acceso de invitado o a un enlace. Los derechos de administración nunca pueden darse a invitados.",+ "stampPresetBypassWarning": "Sin «Crear turnos», esta restricción se puede eludir: quien pueda crear plantillas puede crear una cualquiera y luego usarla para fichar.",+ "requiredByHint": "No se puede quitar mientras «{capability}» esté activado",+ "signupsCapabilityHint": "Quién puede inscribirse a sí mismo o a otros en turnos se define por grupo en la pestaña «Grupos» (permisos «Inscribirse» / «Inscribir a otros»).",+ "signupsLocked": "Solo quien puede gestionar los ajustes del calendario puede activar o desactivar las inscripciones.",+ "usageShares": "{count, plural, one {# compartido} other {# compartidos}}",+ "usageTokens": "{count, plural, one {# enlace} other {# enlaces}}",+ "usageGuestAccess": "el acceso de invitados",+ "deleteInUse": "Todavía en uso por: {usage}",+ "nameTaken": "Ya existe un grupo con este nombre",+ "bundlesUnavailable": "No se pudieron cargar los grupos de permisos, por lo que esta acción no está disponible.",+ "seed": {+ "read": "Lectura",+ "contribute": "Colaborar",+ "manage": "Gestionar",+ "admin": "Administración"+ },+ "groups": {+ "view": "Ver",+ "shifts": "Turnos",+ "notesEvents": "Notas y eventos",+ "signups": "Inscripciones",+ "presets": "Plantillas",+ "externalSync": "Sincronización externa",+ "administration": "Administración"+ },+ "capabilityLabels": {+ "viewShifts": "Ver turnos",+ "viewNotesEvents": "Ver notas y eventos",+ "viewStats": "Ver estadísticas",+ "stampPreset": "Fichar plantillas",+ "createShift": "Crear turnos",+ "editOwnShift": "Editar turnos propios",+ "editAnyShift": "Editar cualquier turno",+ "deleteOwnShift": "Eliminar turnos propios",+ "deleteAnyShift": "Eliminar cualquier turno",+ "manageOwnNotesEvents": "Gestionar notas y eventos propios",+ "manageAnyNotesEvents": "Gestionar cualquier nota o evento",+ "signUpSelf": "Inscribirse",+ "signUpOthers": "Inscribir a otros",+ "createPreset": "Crear plantillas",+ "manageOwnPresets": "Gestionar plantillas propias",+ "manageAnyPresets": "Gestionar cualquier plantilla",+ "manageExternalSync": "Gestionar sincronización externa",+ "deleteSyncLogs": "Eliminar registros de sincronización",+ "manageShares": "Gestionar comparticiones",+ "manageGuestAccess": "Gestionar acceso de invitados y enlaces",+ "manageCalendarSettings": "Gestionar ajustes del calendario"+ },+ "capabilityHints": {+ "viewShifts": "Ver el calendario y sus turnos",+ "viewNotesEvents": "Ver notas y eventos del calendario",+ "viewStats": "Ver resúmenes e informes",+ "stampPreset": "Añadir una plantilla existente como turno",+ "createShift": "Crear turnos nuevos libremente",+ "editOwnShift": "Modificar turnos que ha creado",+ "editAnyShift": "También modificar turnos creados por otros",+ "deleteOwnShift": "Eliminar turnos que ha creado",+ "deleteAnyShift": "También eliminar turnos creados por otros",+ "manageOwnNotesEvents": "Editar o eliminar notas y eventos que ha creado",+ "manageAnyNotesEvents": "También editar o eliminar notas y eventos creados por otros",+ "signUpSelf": "Inscribirse y darse de baja en turnos con plazas libres",+ "signUpOthers": "Inscribir y dar de baja a otras personas en turnos",+ "createPreset": "Crear plantillas nuevas",+ "manageOwnPresets": "Editar o eliminar plantillas que ha creado",+ "manageAnyPresets": "También editar plantillas creadas por otros; controla además el orden compartido",+ "manageExternalSync": "Configurar y editar suscripciones de calendario externas",+ "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"+ }}}diff --git a/messages/fr.json b/messages/fr.jsonindex 7311423..2c626d4 100755--- a/messages/fr.json+++ b/messages/fr.json@@ -69,9 +69,6 @@"severity": "Gravité","permission": "Permission","permissions": {- "admin": "Admin",- "read": "Lecture",- "write": "Écriture","none": "Aucun accès"},"notes": "Notes",@@ -263,6 +260,7 @@"month": "Mois","year": "Année","noData": "Aucun créneau sur cette période",+ "noPermission": "Vous n'avez pas le droit de consulter les statistiques de ce calendrier","hours": "Heures","overview": "Vue d'ensemble","distribution": "Répartition",@@ -421,13 +419,11 @@},"share": {"publicAccess": "Accès public",- "public": "Public","links": "Liens","share": "partage","searchUser": "Rechercher un utilisateur","searchUserPlaceholder": "Saisir un nom ou un e-mail...","noSharesDescription": "Partagez ce calendrier avec d'autres utilisateurs pour collaborer",- "publicPermissionNoneDesc": "Seuls vous, les personnes invitées et les détenteurs d’un lien d’accès y ont accès.","shareAdded": "Calendrier partagé avec succès","shareUpdated": "Permission mise à jour avec succès","shareRemoved": "Accès retiré avec succès",@@ -436,10 +432,6 @@"removeShareConfirmDesc": "Voulez-vous vraiment retirer l'accès à {user} ? Cette personne ne pourra plus consulter ni modifier ce calendrier.","you": "Vous","sharedWithYou": "Partagé avec vous",- "publicPermissionReadDescGuestsOn": "Tout le monde peut consulter le calendrier, même sans compte. Les utilisateurs connectés l’ajoutent via « Calendriers partagés ».",- "publicPermissionWriteDescGuestsOn": "Tout le monde peut consulter et modifier le calendrier, même sans compte. Les utilisateurs connectés l’ajoutent via « Calendriers partagés ».",- "publicPermissionReadDescGuestsOff": "Les utilisateurs connectés de cette instance peuvent ajouter et consulter le calendrier via « Calendriers partagés ». Sans compte, aucun accès n’est possible, car l’accès invité est désactivé sur cette instance.",- "publicPermissionWriteDescGuestsOff": "Les utilisateurs connectés de cette instance peuvent ajouter, consulter et modifier le calendrier via « Calendriers partagés ». Sans compte, aucun accès n’est possible, car l’accès invité est désactivé sur cette instance.","publicAccessDescriptionGuestsOn": "Contrôlez l’accès public pour les utilisateurs connectés et les visiteurs sans compte.","publicAccessDescriptionGuestsOff": "Contrôlez l’accès public pour les utilisateurs connectés de cette instance."},@@ -772,8 +764,8 @@"presetsHint": "{count, plural, =0 {Aucun modèle} one {# modèle} other {# modèles}}","external": "Calendriers externes","externalHint": "{count, plural, =0 {Abonnement, affichage, intervalle} one {# abonnement, affichage, intervalle} other {# abonnements, affichage, intervalle}}",- "sharing": "Partage",- "sharingHint": "{count, plural, =0 {Personnes, accès public, liens} one {Personnes, accès public, # lien actif} other {Personnes, accès public, # liens actifs}}",+ "permissions": "Autorisations",+ "permissionsHint": "{count, plural, =0 {Groupes, attributions, liens} one {Groupes, attributions, # lien actif} other {Groupes, attributions, # liens actifs}}","export": "Exporter","exportHint": "Fichier ICS ou PDF","view": "Affichage du calendrier",@@ -834,18 +826,10 @@"statusSuccess": "Réussi"},"sharingSheet": {- "tabPeople": "Personnes","invite": "Inviter",- "haveAccess": "Ont accès","owner": "Propriétaire",- "permRead": "Lecture seule",- "permWrite": "Modifier",- "permReadDesc": "Voir le calendrier sans rien modifier",- "permWriteDesc": "Créer et supprimer des postes",- "permAdminDesc": "Gérer aussi les partages et les paramètres","changePermission": "Modifier l’autorisation de {name}","accessNone": "Aucun accès",- "guestNoneShort": "Invités et liens uniquement","activeLinks": "Liens actifs","inactiveLinks": "Désactivés ou expirés","noActiveLinks": "Aucun lien actif",@@ -867,14 +851,8 @@"copyNowBody": "Une fois fermé, le jeton n’est plus récupérable. En cas de perte, créez-en un nouveau et révoquez celui-ci.","shareLinkLabel": "Lien à partager","copied": "Copié",- "guestReadShortGuestsOn": "Tout le monde peut voir",- "guestWriteShortGuestsOn": "Tout le monde peut modifier",- "guestReadShortGuestsOff": "Les utilisateurs connectés peuvent voir",- "guestWriteShortGuestsOff": "Les utilisateurs connectés peuvent modifier","linkInfoGuestsOn": "Le lien ouvre directement le calendrier, sans connexion. Vous pouvez le révoquer à tout moment dans la liste ; il cesse alors immédiatement de fonctionner.","linkInfoGuestsOff": "Le lien ouvre directement le calendrier. L’accès invité est désactivé sur cette instance : les destinataires doivent se connecter. Vous pouvez le révoquer à tout moment dans la liste ; il cesse alors immédiatement de fonctionner.",- "allowSelfSignupLabel": "Inscription autonome aux gardes",- "allowSelfSignupDesc": "Les membres en lecture seule peuvent s'inscrire et se desinscrire des gardes","signupsEnabledLabel": "Activer les inscriptions aux gardes","signupsEnabledDesc": "Permet aux personnes de s'inscrire aux gardes. La désactivation masque les listes d'inscription, les avatars et l'effectif maximal partout."},@@ -1072,10 +1050,9 @@"filterShared": "Partagés","filterSynced": "Avec synchro","guestColumn": "Accès invité",+ "guestBundleHint": "Toute personne disposant du lien a accès au calendrier selon ce groupe","guestNoneHint": "Seules les personnes avec qui il est partagé voient le calendrier","guestPermissionValue": "Autorisation invité : {permission}",- "guestReadHint": "Toute personne disposant du lien voit le calendrier",- "guestWriteHint": "Toute personne disposant du lien peut modifier le calendrier","publicAccess": "Accès public","selectAll": "Tout sélectionner","selectedCount": "Sélectionnés : {count}",@@ -1107,5 +1084,93 @@"removeFailed": "La desinscription a echoue"},"addOtherHint": "Vous ne trouvez pas quelqu'un ? Partagez d'abord le calendrier avec cette personne, vous pourrez ensuite la sélectionner ici."+ },+ "permissionBundles": {+ "bundle": "Groupe de permissions",+ "title": "Autorisations",+ "tabGroups": "Groupes",+ "tabAssignments": "Attributions",+ "tabMore": "Plus",+ "people": "Personnes",+ "inviteAs": "Inviter en tant que",+ "cloneSuffix": "(Copie)",+ "newBundle": "Créer un nouveau groupe",+ "newBundleNamePlaceholder": "p. ex. Week-end uniquement",+ "usedByCount": "{count, plural, =0 {Non attribué} one {Utilisé par # attribution} other {Utilisé par # attributions}}",+ "clone": "Dupliquer",+ "deleteConfirmTitle": "Supprimer le groupe ?",+ "deleteConfirmDesc": "Supprimer le groupe « {name} » ? Cette action est irréversible.",+ "guestLockedHint": "Ce groupe est attribué à un accès invité ou à un lien. Les droits d'administration ne peuvent jamais être accordés aux invités.",+ "stampPresetBypassWarning": "Sans « Créer des créneaux », cette restriction peut être contournée : quiconque peut créer des modèles peut en créer un quelconque puis le pointer.",+ "requiredByHint": "Ne peut pas être retiré tant que « {capability} » est activé",+ "signupsCapabilityHint": "Qui peut s'inscrire ou inscrire d'autres personnes aux créneaux se définit par groupe dans l'onglet « Groupes » (droits « S'inscrire » / « Inscrire d'autres personnes »).",+ "signupsLocked": "Seule une personne pouvant gérer les paramètres du calendrier peut activer ou désactiver les inscriptions.",+ "usageShares": "{count, plural, one {# partage} other {# partages}}",+ "usageTokens": "{count, plural, one {# lien} other {# liens}}",+ "usageGuestAccess": "l'accès invité",+ "deleteInUse": "Encore utilisé par : {usage}",+ "nameTaken": "Un groupe portant ce nom existe déjà",+ "bundlesUnavailable": "Les groupes de permissions n'ont pas pu être chargés, cette action n'est donc pas disponible.",+ "seed": {+ "read": "Lecture",+ "contribute": "Contribuer",+ "manage": "Gérer",+ "admin": "Administration"+ },+ "groups": {+ "view": "Consultation",+ "shifts": "Créneaux",+ "notesEvents": "Notes et événements",+ "signups": "Inscriptions",+ "presets": "Modèles",+ "externalSync": "Synchronisation externe",+ "administration": "Administration"+ },+ "capabilityLabels": {+ "viewShifts": "Voir les créneaux",+ "viewNotesEvents": "Voir les notes et événements",+ "viewStats": "Voir les statistiques",+ "stampPreset": "Pointer des modèles",+ "createShift": "Créer des créneaux",+ "editOwnShift": "Modifier ses propres créneaux",+ "editAnyShift": "Modifier tous les créneaux",+ "deleteOwnShift": "Supprimer ses propres créneaux",+ "deleteAnyShift": "Supprimer tous les créneaux",+ "manageOwnNotesEvents": "Gérer ses propres notes et événements",+ "manageAnyNotesEvents": "Gérer toutes les notes et événements",+ "signUpSelf": "S'inscrire",+ "signUpOthers": "Inscrire d'autres personnes",+ "createPreset": "Créer des modèles",+ "manageOwnPresets": "Gérer ses propres modèles",+ "manageAnyPresets": "Gérer tous les modèles",+ "manageExternalSync": "Gérer la synchronisation externe",+ "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"+ },+ "capabilityHints": {+ "viewShifts": "Voir le calendrier et ses créneaux",+ "viewNotesEvents": "Voir les notes et événements du calendrier",+ "viewStats": "Voir les résumés et rapports",+ "stampPreset": "Ajouter un modèle existant comme créneau",+ "createShift": "Créer librement de nouveaux créneaux",+ "editOwnShift": "Modifier les créneaux qu'il a créés",+ "editAnyShift": "Modifier aussi les créneaux créés par d'autres",+ "deleteOwnShift": "Supprimer les créneaux qu'il a créés",+ "deleteAnyShift": "Supprimer aussi les créneaux créés par d'autres",+ "manageOwnNotesEvents": "Modifier ou supprimer les notes et événements qu'il a créés",+ "manageAnyNotesEvents": "Modifier ou supprimer aussi ceux créés par d'autres",+ "signUpSelf": "S'inscrire et se désinscrire des créneaux avec des places libres",+ "signUpOthers": "Inscrire et désinscrire d'autres personnes des créneaux",+ "createPreset": "Créer de nouveaux modèles",+ "manageOwnPresets": "Modifier ou supprimer les modèles qu'il a créés",+ "manageAnyPresets": "Modifier aussi les modèles créés par d'autres ; contrôle également l'ordre commun",+ "manageExternalSync": "Configurer et modifier les abonnements de calendrier externes",+ "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"+ }}}diff --git a/messages/it.json b/messages/it.jsonindex 3517c21..2b0087f 100644--- a/messages/it.json+++ b/messages/it.json@@ -69,9 +69,6 @@"severity": "Gravità","permission": "Permesso","permissions": {- "admin": "Admin",- "read": "Lettura",- "write": "Scrittura","none": "Nessun Accesso"},"notes": "Note",@@ -263,6 +260,7 @@"month": "Mese","year": "Anno","noData": "Nessun turno in questo periodo",+ "noPermission": "Non hai il permesso di visualizzare le statistiche di questo calendario","hours": "Ore","overview": "Panoramica","distribution": "Distribuzione",@@ -421,13 +419,11 @@},"share": {"publicAccess": "Accesso Pubblico",- "public": "Pubblico","links": "Link","share": "condivisione","searchUser": "Cerca utente","searchUserPlaceholder": "Inserisci nome o email...","noSharesDescription": "Condividi questo calendario con altri utenti per collaborare",- "publicPermissionNoneDesc": "Solo tu, le persone invitate e chi possiede un link di accesso hanno accesso.","shareAdded": "Calendario condiviso con successo","shareUpdated": "Permesso aggiornato con successo","shareRemoved": "Accesso rimosso con successo",@@ -436,10 +432,6 @@"removeShareConfirmDesc": "Sei sicuro di voler rimuovere l'accesso per {user}? Non potrà più visualizzare o modificare questo calendario.","you": "Tu","sharedWithYou": "Condiviso con te",- "publicPermissionReadDescGuestsOn": "Chiunque può visualizzare il calendario, anche senza account. Gli utenti autenticati lo aggiungono da «Calendari Condivisi».",- "publicPermissionWriteDescGuestsOn": "Chiunque può visualizzare e modificare il calendario, anche senza account. Gli utenti autenticati lo aggiungono da «Calendari Condivisi».",- "publicPermissionReadDescGuestsOff": "Gli utenti autenticati di questa istanza possono aggiungere e visualizzare il calendario da «Calendari Condivisi». Senza account non è possibile accedere, perché l’accesso ospite è disattivato su questa istanza.",- "publicPermissionWriteDescGuestsOff": "Gli utenti autenticati di questa istanza possono aggiungere, visualizzare e modificare il calendario da «Calendari Condivisi». Senza account non è possibile accedere, perché l’accesso ospite è disattivato su questa istanza.","publicAccessDescriptionGuestsOn": "Controlla l’accesso pubblico per utenti autenticati e visitatori senza account.","publicAccessDescriptionGuestsOff": "Controlla l’accesso pubblico per gli utenti autenticati di questa istanza."},@@ -772,8 +764,8 @@"presetsHint": "{count, plural, =0 {Nessun modello} one {# modello} other {# modelli}}","external": "Calendari esterni","externalHint": "{count, plural, =0 {Abbonamento, visualizzazione, intervallo} one {# abbonamento, visualizzazione, intervallo} other {# abbonamenti, visualizzazione, intervallo}}",- "sharing": "Condivisione",- "sharingHint": "{count, plural, =0 {Persone, accesso pubblico, link} one {Persone, accesso pubblico, # link attivo} other {Persone, accesso pubblico, # link attivi}}",+ "permissions": "Permessi",+ "permissionsHint": "{count, plural, =0 {Gruppi, assegnazioni, link} one {Gruppi, assegnazioni, # link attivo} other {Gruppi, assegnazioni, # link attivi}}","export": "Esporta","exportHint": "File ICS o PDF","view": "Vista del calendario",@@ -834,18 +826,10 @@"statusSuccess": "Riuscito"},"sharingSheet": {- "tabPeople": "Persone","invite": "Invita",- "haveAccess": "Hanno accesso","owner": "Proprietario",- "permRead": "Sola lettura",- "permWrite": "Modifica",- "permReadDesc": "Vedere il calendario senza modificare nulla",- "permWriteDesc": "Creare ed eliminare turni",- "permAdminDesc": "Gestire anche condivisioni e impostazioni","changePermission": "Modifica il permesso di {name}","accessNone": "Nessun accesso",- "guestNoneShort": "Solo invitati e link","activeLinks": "Link attivi","inactiveLinks": "Disattivati o scaduti","noActiveLinks": "Nessun link attivo",@@ -867,14 +851,8 @@"copyNowBody": "Dopo la chiusura il token non è più recuperabile. Se va perso, creane uno nuovo e revoca questo.","shareLinkLabel": "Link da condividere","copied": "Copiato",- "guestReadShortGuestsOn": "Tutti possono vedere",- "guestWriteShortGuestsOn": "Tutti possono modificare",- "guestReadShortGuestsOff": "Gli utenti autenticati possono vedere",- "guestWriteShortGuestsOff": "Gli utenti autenticati possono modificare","linkInfoGuestsOn": "Il link apre direttamente il calendario, senza accesso. Puoi revocarlo dalla lista in qualsiasi momento: smette subito di funzionare.","linkInfoGuestsOff": "Il link apre direttamente il calendario. L’accesso ospite è disattivato su questa istanza, quindi i destinatari devono accedere. Puoi revocarlo dalla lista in qualsiasi momento: smette subito di funzionare.",- "allowSelfSignupLabel": "Iscrizione autonoma ai turni",- "allowSelfSignupDesc": "I membri in sola lettura possono iscriversi e ritirarsi dai turni","signupsEnabledLabel": "Attiva le iscrizioni ai turni","signupsEnabledDesc": "Permette alle persone di iscriversi ai turni. Disattivandolo, elenchi di iscrizione, avatar e numero massimo di persone scompaiono ovunque."},@@ -1072,10 +1050,9 @@"filterShared": "Condivisi","filterSynced": "Con sync","guestColumn": "Accesso ospite",+ "guestBundleHint": "Chiunque abbia il link ha accesso al calendario in base a questo gruppo","guestNoneHint": "Solo le persone con cui è condiviso vedono il calendario","guestPermissionValue": "Permesso ospite: {permission}",- "guestReadHint": "Chiunque abbia il link vede il calendario",- "guestWriteHint": "Chiunque abbia il link può modificare il calendario","publicAccess": "Accesso pubblico","selectAll": "Seleziona tutto","selectedCount": "Selezionati: {count}",@@ -1107,5 +1084,93 @@"removeFailed": "Il ritiro non e riuscito"},"addOtherHint": "Non trovi qualcuno? Condividi prima il calendario con questa persona, poi potrai selezionarla qui."+ },+ "permissionBundles": {+ "bundle": "Gruppo di permessi",+ "title": "Permessi",+ "tabGroups": "Gruppi",+ "tabAssignments": "Assegnazioni",+ "tabMore": "Altro",+ "people": "Persone",+ "inviteAs": "Invita come",+ "cloneSuffix": "(Copia)",+ "newBundle": "Crea nuovo gruppo",+ "newBundleNamePlaceholder": "es. Solo weekend",+ "usedByCount": "{count, plural, =0 {Non assegnato} one {Usato da # assegnazione} other {Usato da # assegnazioni}}",+ "clone": "Duplica",+ "deleteConfirmTitle": "Eliminare il gruppo?",+ "deleteConfirmDesc": "Eliminare il gruppo «{name}»? Questa azione non può essere annullata.",+ "guestLockedHint": "Questo gruppo è assegnato a un accesso ospite o a un link. I diritti amministrativi non possono mai essere dati agli ospiti.",+ "stampPresetBypassWarning": "Senza «Creare turni», questa restrizione è aggirabile: chi può creare preset può crearne uno qualsiasi e poi timbrarlo.",+ "requiredByHint": "Non può essere rimosso finché «{capability}» è attivo",+ "signupsCapabilityHint": "Chi può iscrivere sé stesso o altri ai turni si stabilisce per gruppo nella scheda «Gruppi» (diritti «Iscriversi» / «Iscrivere altri»).",+ "signupsLocked": "Solo chi può gestire le impostazioni del calendario può attivare o disattivare le iscrizioni.",+ "usageShares": "{count, plural, one {# condivisione} other {# condivisioni}}",+ "usageTokens": "{count, plural, one {# link} other {# link}}",+ "usageGuestAccess": "l'accesso ospite",+ "deleteInUse": "Ancora usato da: {usage}",+ "nameTaken": "Esiste già un gruppo con questo nome",+ "bundlesUnavailable": "Impossibile caricare i gruppi di permessi, quindi questa azione non è disponibile.",+ "seed": {+ "read": "Lettura",+ "contribute": "Contribuire",+ "manage": "Gestire",+ "admin": "Amministrazione"+ },+ "groups": {+ "view": "Visualizzazione",+ "shifts": "Turni",+ "notesEvents": "Note ed eventi",+ "signups": "Iscrizioni",+ "presets": "Preset",+ "externalSync": "Sync esterno",+ "administration": "Amministrazione"+ },+ "capabilityLabels": {+ "viewShifts": "Visualizzare i turni",+ "viewNotesEvents": "Visualizzare note ed eventi",+ "viewStats": "Visualizzare le statistiche",+ "stampPreset": "Timbrare preset",+ "createShift": "Creare turni",+ "editOwnShift": "Modificare i propri turni",+ "editAnyShift": "Modificare qualsiasi turno",+ "deleteOwnShift": "Eliminare i propri turni",+ "deleteAnyShift": "Eliminare qualsiasi turno",+ "manageOwnNotesEvents": "Gestire le proprie note ed eventi",+ "manageAnyNotesEvents": "Gestire qualsiasi nota o evento",+ "signUpSelf": "Iscriversi",+ "signUpOthers": "Iscrivere altri",+ "createPreset": "Creare preset",+ "manageOwnPresets": "Gestire i propri preset",+ "manageAnyPresets": "Gestire qualsiasi preset",+ "manageExternalSync": "Gestire il sync esterno",+ "deleteSyncLogs": "Eliminare i log di sync",+ "manageShares": "Gestire le condivisioni",+ "manageGuestAccess": "Gestire accesso ospite e link",+ "manageCalendarSettings": "Gestire le impostazioni del calendario"+ },+ "capabilityHints": {+ "viewShifts": "Vedere il calendario e i suoi turni",+ "viewNotesEvents": "Vedere note ed eventi del calendario",+ "viewStats": "Vedere riepiloghi e report",+ "stampPreset": "Aggiungere un preset esistente come turno",+ "createShift": "Creare liberamente nuovi turni",+ "editOwnShift": "Modificare i turni creati da sé stesso",+ "editAnyShift": "Modificare anche i turni creati da altri",+ "deleteOwnShift": "Eliminare i turni creati da sé stesso",+ "deleteAnyShift": "Eliminare anche i turni creati da altri",+ "manageOwnNotesEvents": "Modificare o eliminare note ed eventi creati da sé stesso",+ "manageAnyNotesEvents": "Modificare o eliminare anche quelli creati da altri",+ "signUpSelf": "Iscriversi e ritirarsi dai turni con posti liberi",+ "signUpOthers": "Iscrivere e ritirare altre persone dai turni",+ "createPreset": "Creare nuovi preset",+ "manageOwnPresets": "Modificare o eliminare i preset creati da sé stesso",+ "manageAnyPresets": "Modificare anche i preset creati da altri; controlla anche l'ordine condiviso",+ "manageExternalSync": "Configurare e modificare gli abbonamenti calendario esterni",+ "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"+ }}}diff --git a/proxy.ts b/proxy.tsindex fa2b020..3806032 100644--- a/proxy.ts+++ b/proxy.ts@@ -238,7 +238,7 @@ export async function proxy(request: NextRequest) {storeTokenInCookie(token,validation.calendarId,- validation.permission,+ validation.bundleId,response,request // Pass request to read existing tokens);@@ -255,7 +255,7 @@ export async function proxy(request: NextRequest) {metadata: {tokenId: validation.id,calendarName: validation.calendarName,- permission: validation.permission,+ bundleId: validation.bundleId,},request,severity: "info",