Skip to content

Your favorite shift management application!

feat: implement iCloud sync functionality with CRUD operations (#7)

panteL4fa3614e099f
diff --git a/README.md b/README.md
index cfefc6c..bea1ad9 100644
--- a/README.md
+++ b/README.md
@@ -36,6 +36,7 @@
- **Shift Presets**: Create reusable shift templates with custom times, colors, and labels
- **Drag & Drop**: Reorder calendars and presets with intuitive drag-and-drop functionality
- **Calendar Notes**: Right-click any day to add custom notes (e.g., "Morning shift because afternoon hairdresser")
+- **ICloud Sync**: Import shifts from multiple iCloud calendars with individual sync management
### 🎨 Customization & Organization
diff --git a/app/api/icloud-syncs/[id]/route.ts b/app/api/icloud-syncs/[id]/route.ts
new file mode 100644
index 0000000..4184e13
--- /dev/null
+++ b/app/api/icloud-syncs/[id]/route.ts
@@ -0,0 +1,128 @@
+import { NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { icloudSyncs, shifts } from "@/lib/db/schema";
+import { eq } from "drizzle-orm";
+import { eventEmitter } from "@/lib/event-emitter";
+import { isValidICloudUrl } from "@/lib/icloud-utils";
+
+// GET single iCloud sync
+export async function GET(
+ request: Request,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id } = await params;
+
+ const [icloudSync] = await db
+ .select()
+ .from(icloudSyncs)
+ .where(eq(icloudSyncs.id, id))
+ .limit(1);
+
+ if (!icloudSync) {
+ return NextResponse.json(
+ { error: "iCloud sync not found" },
+ { status: 404 }
+ );
+ }
+
+ return NextResponse.json(icloudSync);
+ } catch (error) {
+ console.error("Failed to fetch iCloud sync:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch iCloud sync" },
+ { status: 500 }
+ );
+ }
+}
+
+// PATCH update iCloud sync
+export async function PATCH(
+ request: Request,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id } = await params;
+ const body = await request.json();
+ const { name, icloudUrl, color } = body;
+
+ // Validate iCloud URL if provided
+ if (icloudUrl !== undefined && !isValidICloudUrl(icloudUrl)) {
+ return NextResponse.json(
+ {
+ error:
+ "Invalid iCloud URL. URL must use webcal:// or https:// protocol and be from icloud.com domain",
+ },
+ { status: 400 }
+ );
+ }
+
+ const updateData: Record<string, unknown> = {
+ updatedAt: new Date(),
+ };
+
+ if (name !== undefined) updateData.name = name;
+ if (icloudUrl !== undefined) updateData.icloudUrl = icloudUrl;
+ if (color !== undefined) updateData.color = color;
+
+ const [updated] = await db
+ .update(icloudSyncs)
+ .set(updateData)
+ .where(eq(icloudSyncs.id, id))
+ .returning();
+
+ if (!updated) {
+ return NextResponse.json(
+ { error: "iCloud sync not found" },
+ { status: 404 }
+ );
+ }
+
+ // If color was updated, also update the color of all associated shifts
+ if (color !== undefined) {
+ await db
+ .update(shifts)
+ .set({
+ color: color,
+ updatedAt: new Date(),
+ })
+ .where(eq(shifts.icloudSyncId, id));
+
+ // Emit event to notify clients about shift updates
+ eventEmitter.emit("calendar-change", {
+ type: "shift",
+ action: "update",
+ calendarId: updated.calendarId,
+ data: { icloudSyncId: id, colorUpdated: true },
+ });
+ }
+
+ return NextResponse.json(updated);
+ } catch (error) {
+ console.error("Failed to update iCloud sync:", error);
+ return NextResponse.json(
+ { error: "Failed to update iCloud sync" },
+ { status: 500 }
+ );
+ }
+}
+
+// DELETE iCloud sync and all associated shifts
+export async function DELETE(
+ request: Request,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id } = await params;
+
+ await db.delete(icloudSyncs).where(eq(icloudSyncs.id, id));
+
+ return NextResponse.json({ success: true });
+ } catch (error) {
+ console.error("Failed to delete iCloud sync:", error);
+ return NextResponse.json(
+ { error: "Failed to delete iCloud sync" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/icloud-syncs/[id]/sync/route.ts b/app/api/icloud-syncs/[id]/sync/route.ts
new file mode 100644
index 0000000..4a2fea5
--- /dev/null
+++ b/app/api/icloud-syncs/[id]/sync/route.ts
@@ -0,0 +1,222 @@
+import { NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { icloudSyncs, shifts } from "@/lib/db/schema";
+import { eq, inArray } from "drizzle-orm";
+import ICAL from "ical.js";
+import { expandRecurringEvents, splitMultiDayEvent } from "@/lib/icloud-utils";
+
+export async function POST(
+ request: Request,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id: syncId } = await params;
+
+ // Get the iCloud sync configuration
+ const [icloudSync] = await db
+ .select()
+ .from(icloudSyncs)
+ .where(eq(icloudSyncs.id, syncId))
+ .limit(1);
+
+ if (!icloudSync) {
+ return NextResponse.json(
+ { error: "iCloud sync configuration not found" },
+ { status: 404 }
+ );
+ }
+
+ // Convert webcal:// to https:// for iCloud URLs
+ const fetchUrl = icloudSync.icloudUrl.replace(/^webcal:\/\//i, "https://");
+
+ // Fetch the calendar from the specified iCloud URL
+ let icsData: string;
+ try {
+ const response = await fetch(fetchUrl);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch calendar: ${response.statusText}`);
+ }
+ icsData = await response.text();
+ } catch (error) {
+ console.error("Error fetching iCloud calendar:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch iCloud calendar. Please check the URL." },
+ { status: 500 }
+ );
+ }
+
+ // Parse the ICS data
+ let jcalData;
+ try {
+ jcalData = ICAL.parse(icsData);
+ } catch (error) {
+ console.error("Error parsing ICS data:", error);
+ return NextResponse.json(
+ { error: "Failed to parse calendar data. Invalid ICS format." },
+ { status: 500 }
+ );
+ }
+
+ const comp = new ICAL.Component(jcalData);
+ const vevents = comp.getAllSubcomponents("vevent");
+
+ // Define sync window: 3 months back to 1 year forward
+ const syncWindowStart = new Date();
+ syncWindowStart.setMonth(syncWindowStart.getMonth() - 3);
+ const syncWindowEnd = new Date();
+ syncWindowEnd.setFullYear(syncWindowEnd.getFullYear() + 1);
+
+ // Get existing iCloud synced shifts for this sync
+ const existingShifts = await db
+ .select()
+ .from(shifts)
+ .where(eq(shifts.icloudSyncId, syncId));
+
+ const existingEventIds = new Set(
+ existingShifts
+ .filter((s) => s.icloudEventId)
+ .map((s) => s.icloudEventId as string)
+ );
+
+ const processedEventIds = new Set<string>();
+ const shiftsToInsert: (typeof shifts.$inferInsert)[] = [];
+ const shiftsToUpdate: Array<typeof shifts.$inferInsert & { id: string }> =
+ [];
+
+ // Process each vevent, expanding recurring events
+ for (const vevent of vevents) {
+ const occurrences = expandRecurringEvents(
+ vevent,
+ syncWindowStart,
+ syncWindowEnd
+ );
+
+ for (const occurrence of occurrences) {
+ const { event, startDate, endDate, recurrenceId } = occurrence;
+
+ // Create a unique ID for each occurrence
+ // For recurring events, append the recurrence date to make it unique
+ const baseEventId = recurrenceId
+ ? `${event.uid}_${recurrenceId.toICALString()}`
+ : event.uid;
+
+ if (!startDate || !endDate) {
+ continue; // Skip events without dates
+ }
+
+ const isAllDay = startDate.isDate;
+
+ // Convert ICAL.Time to JavaScript Date
+ const startJsDate = startDate.toJSDate();
+ const endJsDate = endDate.toJSDate();
+
+ // Split multi-day events into separate shifts for each day
+ const dayEntries = splitMultiDayEvent(startJsDate, endJsDate, isAllDay);
+
+ for (const dayEntry of dayEntries) {
+ // Create unique event ID for multi-day events by appending day index
+ const eventId =
+ dayEntries.length > 1
+ ? `${baseEventId}_day${dayEntry.dayIndex}`
+ : baseEventId;
+
+ processedEventIds.add(eventId);
+
+ const shiftData = {
+ calendarId: icloudSync.calendarId,
+ date: dayEntry.date,
+ startTime: dayEntry.startTime,
+ endTime: dayEntry.endTime,
+ title: event.summary || "Untitled Event",
+ color: icloudSync.color,
+ notes: event.description || null,
+ isAllDay,
+ isSecondary: false,
+ icloudEventId: eventId,
+ icloudSyncId: syncId,
+ syncedFromIcloud: true,
+ presetId: null,
+ };
+
+ // Check if this event already exists
+ const existingShift = existingShifts.find(
+ (s) => s.icloudEventId === eventId
+ );
+
+ if (existingShift) {
+ // Collect for batch update
+ shiftsToUpdate.push({
+ id: existingShift.id,
+ ...shiftData,
+ updatedAt: new Date(),
+ });
+ } else {
+ // Collect for batch insert
+ shiftsToInsert.push({
+ id: crypto.randomUUID(),
+ ...shiftData,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ });
+ }
+ }
+ }
+ }
+
+ // Calculate which shifts to delete before transaction
+ const shiftIdsToDelete = existingShifts
+ .filter((s) => s.icloudEventId && !processedEventIds.has(s.icloudEventId))
+ .map((s) => s.id);
+
+ // Perform batch operations in a transaction for atomicity and better performance
+ const transactionResult = db.transaction((tx) => {
+ // Insert new shifts in one batch
+ if (shiftsToInsert.length > 0) {
+ tx.insert(shifts).values(shiftsToInsert).run();
+ }
+
+ // Update existing shifts (SQLite doesn't support batch updates directly,
+ // but doing them in a transaction improves performance)
+ if (shiftsToUpdate.length > 0) {
+ for (const shiftUpdate of shiftsToUpdate) {
+ const { id, ...updateData } = shiftUpdate;
+ tx.update(shifts).set(updateData).where(eq(shifts.id, id)).run();
+ }
+ }
+
+ // Delete shifts that are no longer in the iCloud calendar in one batch
+ if (shiftIdsToDelete.length > 0) {
+ tx.delete(shifts).where(inArray(shifts.id, shiftIdsToDelete)).run();
+ }
+
+ // Update last sync time
+ tx.update(icloudSyncs)
+ .set({
+ lastSyncedAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .where(eq(icloudSyncs.id, syncId))
+ .run();
+
+ // Return transaction stats
+ return {
+ created: shiftsToInsert.length,
+ updated: shiftsToUpdate.length,
+ deleted: shiftIdsToDelete.length,
+ totalEvents: vevents.length,
+ totalOccurrences: shiftsToInsert.length + shiftsToUpdate.length,
+ };
+ });
+
+ return NextResponse.json({
+ success: true,
+ stats: transactionResult,
+ });
+ } catch (error) {
+ console.error("Error syncing iCloud calendar:", error);
+ return NextResponse.json(
+ { error: "Internal server error" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/icloud-syncs/route.ts b/app/api/icloud-syncs/route.ts
new file mode 100644
index 0000000..1f222b7
--- /dev/null
+++ b/app/api/icloud-syncs/route.ts
@@ -0,0 +1,81 @@
+import { NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { icloudSyncs } from "@/lib/db/schema";
+import { eq } from "drizzle-orm";
+import { isValidICloudUrl } from "@/lib/icloud-utils";
+
+// GET all iCloud syncs for a calendar
+export async function GET(request: Request) {
+ try {
+ const { searchParams } = new URL(request.url);
+ const calendarId = searchParams.get("calendarId");
+
+ if (!calendarId) {
+ return NextResponse.json(
+ { error: "Calendar ID is required" },
+ { status: 400 }
+ );
+ }
+
+ const syncs = await db
+ .select()
+ .from(icloudSyncs)
+ .where(eq(icloudSyncs.calendarId, calendarId))
+ .orderBy(icloudSyncs.createdAt);
+
+ return NextResponse.json(syncs);
+ } catch (error) {
+ console.error("Failed to fetch iCloud syncs:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch iCloud syncs" },
+ { status: 500 }
+ );
+ }
+}
+
+// POST create new iCloud sync
+export async function POST(request: Request) {
+ try {
+ const body = await request.json();
+ const { calendarId, name, icloudUrl, color } = body;
+
+ if (!calendarId || !name || !icloudUrl) {
+ return NextResponse.json(
+ { error: "Calendar ID, name, and iCloud URL are required" },
+ { status: 400 }
+ );
+ }
+
+ // Validate iCloud URL to prevent SSRF
+ if (!isValidICloudUrl(icloudUrl)) {
+ return NextResponse.json(
+ {
+ error:
+ "Invalid iCloud URL. URL must use webcal:// or https:// protocol and be from icloud.com domain",
+ },
+ { status: 400 }
+ );
+ }
+
+ const [icloudSync] = await db
+ .insert(icloudSyncs)
+ .values({
+ id: crypto.randomUUID(),
+ calendarId,
+ name,
+ icloudUrl,
+ color: color || "#3b82f6",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .returning();
+
+ return NextResponse.json(icloudSync, { status: 201 });
+ } catch (error) {
+ console.error("Failed to create iCloud sync:", error);
+ return NextResponse.json(
+ { error: "Failed to create iCloud sync" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/shifts/route.ts b/app/api/shifts/route.ts
index e3633e1..936aeba 100644
--- a/app/api/shifts/route.ts
+++ b/app/api/shifts/route.ts
@@ -30,6 +30,7 @@ export async function GET(request: Request) {
notes: shifts.notes,
isAllDay: shifts.isAllDay,
isSecondary: shifts.isSecondary,
+ icloudSyncId: shifts.icloudSyncId,
createdAt: shifts.createdAt,
updatedAt: shifts.updatedAt,
calendar: {
diff --git a/app/page.tsx b/app/page.tsx
index aa5d7e4..d03ecc0 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -8,6 +8,8 @@ import { ShiftDialog, ShiftFormData } from "@/components/shift-dialog";
import { PasswordDialog } from "@/components/password-dialog";
import { ManagePasswordDialog } from "@/components/manage-password-dialog";
import { DeleteCalendarDialog } from "@/components/delete-calendar-dialog";
+import { ICloudSyncManageDialog } from "@/components/icloud-sync-manage-dialog";
+import { DayShiftsDialog } from "@/components/day-shifts-dialog";
import { LanguageSwitcher } from "@/components/language-switcher";
import { ShiftStats } from "@/components/shift-stats";
import { NoteDialog } from "@/components/note-dialog";
@@ -35,6 +37,7 @@ import {
} from "date-fns";
import { de, enUS } from "date-fns/locale";
import { CalendarNote, ShiftPreset } from "@/lib/db/schema";
+import { ShiftWithCalendar } from "@/lib/types";
import { formatDateToLocal } from "@/lib/date-utils";
import { toast } from "sonner";
import { motion } from "motion/react";
@@ -97,6 +100,12 @@ function HomeContent() {
const [showNoteDialog, setShowNoteDialog] = useState(false);
const [showDeleteCalendarDialog, setShowDeleteCalendarDialog] =
useState(false);
+ const [showICloudSyncDialog, setShowICloudSyncDialog] = useState(false);
+ const [showDayShiftsDialog, setShowDayShiftsDialog] = useState(false);
+ const [selectedDayDate, setSelectedDayDate] = useState<Date | null>(null);
+ const [selectedDayShifts, setSelectedDayShifts] = useState<
+ ShiftWithCalendar[]
+ >([]);
const [calendarToDelete, setCalendarToDelete] = useState<
string | undefined
>();
@@ -151,6 +160,56 @@ function HomeContent() {
setShowDeleteCalendarDialog(true);
};
+ const handleICloudSyncClick = async () => {
+ if (!selectedCalendar) return;
+
+ const calendar = calendars.find((c) => c.id === selectedCalendar);
+ if (!calendar) return;
+
+ // Check if calendar is password protected
+ if (calendar.passwordHash) {
+ const storedPassword = localStorage.getItem(
+ `calendar_password_${selectedCalendar}`
+ );
+
+ if (storedPassword) {
+ // Verify stored password
+ try {
+ const response = await fetch(
+ `/api/calendars/${selectedCalendar}/verify-password`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ password: storedPassword }),
+ }
+ );
+
+ if (response.ok) {
+ setShowICloudSyncDialog(true);
+ return;
+ } else {
+ // Password invalid, remove from storage
+ localStorage.removeItem(`calendar_password_${selectedCalendar}`);
+ }
+ } catch (error) {
+ console.error("Password verification failed:", error);
+ }
+ }
+
+ // Show password dialog
+ setPendingAction({
+ type: "edit",
+ presetAction: async () => {
+ setShowICloudSyncDialog(true);
+ },
+ });
+ setShowPasswordDialog(true);
+ } else {
+ // No password protection
+ setShowICloudSyncDialog(true);
+ }
+ };
+
const handleDeleteCalendar = async (password?: string) => {
if (!calendarToDelete) return;
@@ -384,6 +443,19 @@ function HomeContent() {
}
};
+ const handleShowAllShifts = (date: Date, dayShifts: ShiftWithCalendar[]) => {
+ setSelectedDayDate(date);
+ setSelectedDayShifts(dayShifts);
+ setShowDayShiftsDialog(true);
+ };
+
+ const handleDeleteShiftFromDayDialog = async (shiftId: string) => {
+ setShowDayShiftsDialog(false);
+ await handleDeleteShift(shiftId);
+ // Refresh the shifts after deletion
+ refetchShifts();
+ };
+
const handleAddShift = async (date: Date) => {
if (!selectedPresetId) return;
@@ -596,6 +668,7 @@ function HomeContent() {
onCreateCalendar={() => setShowCalendarDialog(true)}
onManagePassword={() => setShowManagePasswordDialog(true)}
onDeleteCalendar={initiateDeleteCalendar}
+ onICloudSync={handleICloudSyncClick}
onPresetsChange={refetchPresets}
onShiftsChange={refetchShifts}
onPasswordRequired={handlePresetPasswordRequired}
@@ -650,6 +723,7 @@ function HomeContent() {
onDayRightClick={handleDayRightClick}
onNoteIconClick={handleNoteIconClick}
onLongPress={handleLongPressDay}
+ onShowAllShifts={handleShowAllShifts}
/>
{/* Note Hint */}
@@ -776,6 +850,28 @@ function HomeContent() {
onConfirm={handleDeleteCalendar}
/>
)}
+ {selectedCalendar && (
+ <ICloudSyncManageDialog
+ open={showICloudSyncDialog}
+ onOpenChange={setShowICloudSyncDialog}
+ calendarId={selectedCalendar}
+ onSyncComplete={() => {
+ refetchShifts();
+ refetchCalendars();
+ setStatsRefreshTrigger((prev) => prev + 1);
+ }}
+ />
+ )}
+
+ {/* Day Shifts Dialog */}
+ <DayShiftsDialog
+ open={showDayShiftsDialog}
+ onOpenChange={setShowDayShiftsDialog}
+ date={selectedDayDate}
+ shifts={selectedDayShifts}
+ locale={locale}
+ onDeleteShift={handleDeleteShiftFromDayDialog}
+ />
{/* Footer */}
<div className="border-t bg-background mt-auto">
diff --git a/components/app-header.tsx b/components/app-header.tsx
index fc37090..8197689 100644
--- a/components/app-header.tsx
+++ b/components/app-header.tsx
@@ -26,6 +26,7 @@ interface AppHeaderProps {
onCreateCalendar: () => void;
onManagePassword: () => void;
onDeleteCalendar: (id: string) => void;
+ onICloudSync: () => void;
onPresetsChange: () => void;
onShiftsChange: () => void;
onPasswordRequired: (action: () => Promise<void>) => void;
@@ -45,6 +46,7 @@ export function AppHeader({
onCreateCalendar,
onManagePassword,
onDeleteCalendar,
+ onICloudSync,
onPresetsChange,
onShiftsChange,
onPasswordRequired,
@@ -122,6 +124,7 @@ export function AppHeader({
onCreateNew={onCreateCalendar}
onManagePassword={onManagePassword}
onDelete={onDeleteCalendar}
+ onICloudSync={onICloudSync}
/>
</div>
</motion.div>
@@ -252,6 +255,10 @@ export function AppHeader({
onManagePassword();
}}
onDelete={onDeleteCalendar}
+ onICloudSync={() => {
+ onMobileCalendarDialogChange(false);
+ onICloudSync();
+ }}
/>
</div>
</DialogContent>
diff --git a/components/calendar-dialog.tsx b/components/calendar-dialog.tsx
index 2bb10db..0bc3660 100644
--- a/components/calendar-dialog.tsx
+++ b/components/calendar-dialog.tsx
@@ -14,6 +14,7 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
+import { PRESET_COLORS } from "@/lib/constants";
interface CalendarDialogProps {
open: boolean;
@@ -21,17 +22,6 @@ interface CalendarDialogProps {
onSubmit: (name: string, color: string, password?: string) => void;
}
-const PRESET_COLORS = [
- "#3b82f6", // blue
- "#ef4444", // red
- "#10b981", // green
- "#f59e0b", // amber
- "#8b5cf6", // violet
- "#ec4899", // pink
- "#06b6d4", // cyan
- "#f97316", // orange
-];
-
export function CalendarDialog({
open,
onOpenChange,
@@ -39,7 +29,7 @@ export function CalendarDialog({
}: CalendarDialogProps) {
const t = useTranslations();
const [name, setName] = useState("");
- const [selectedColor, setSelectedColor] = useState(PRESET_COLORS[0]);
+ const [selectedColor, setSelectedColor] = useState(PRESET_COLORS[0].value);
const [password, setPassword] = useState("");
const [usePassword, setUsePassword] = useState(false);
@@ -52,7 +42,7 @@ export function CalendarDialog({
usePassword && password ? password : undefined
);
setName("");
- setSelectedColor(PRESET_COLORS[0]);
+ setSelectedColor(PRESET_COLORS[0].value);
setPassword("");
setUsePassword(false);
onOpenChange(false);
@@ -96,30 +86,30 @@ export function CalendarDialog({
{t("calendar.color")}
</Label>
<div className="grid grid-cols-4 gap-3 p-4 bg-muted/30 rounded-xl border border-border/30">
- {PRESET_COLORS.map((color) => (
+ {PRESET_COLORS.map((colorObj) => (
<button
- key={color}
+ key={colorObj.value}
type="button"
- onClick={() => setSelectedColor(color)}
+ onClick={() => setSelectedColor(colorObj.value)}
className={`
relative w-full aspect-square rounded-xl transition-all duration-200
hover:scale-110 active:scale-95
${
- selectedColor === color
+ selectedColor === colorObj.value
? "ring-4 ring-primary/30 shadow-lg scale-105"
: "ring-2 ring-border/20 hover:ring-border/40"
}
`}
style={{
- backgroundColor: color,
+ backgroundColor: colorObj.value,
boxShadow:
- selectedColor === color
- ? `0 8px 24px ${color}40`
- : `0 2px 8px ${color}20`,
+ selectedColor === colorObj.value
+ ? `0 8px 24px ${colorObj.value}40`
+ : `0 2px 8px ${colorObj.value}20`,
}}
- aria-label={color}
+ aria-label={colorObj.name}
>
- {selectedColor === color && (
+ {selectedColor === colorObj.value && (
<motion.div
initial={{ scale: 0 }}
animate={{ scale: 1 }}
diff --git a/components/calendar-grid.tsx b/components/calendar-grid.tsx
index c7f7bb7..cc63a8f 100644
--- a/components/calendar-grid.tsx
+++ b/components/calendar-grid.tsx
@@ -18,6 +18,7 @@ interface CalendarGridProps {
onDayRightClick: (e: React.MouseEvent, date: Date) => void;
onNoteIconClick: (e: React.MouseEvent, date: Date) => void;
onLongPress: (date: Date) => void;
+ onShowAllShifts?: (date: Date, shifts: ShiftWithCalendar[]) => void;
}
export function CalendarGrid({
@@ -31,6 +32,7 @@ export function CalendarGrid({
onDayRightClick,
onNoteIconClick,
onLongPress,
+ onShowAllShifts,
}: CalendarGridProps) {
const t = useTranslations();
const pressTimerRef = useRef<Record<string, NodeJS.Timeout>>({});
@@ -201,7 +203,13 @@ export function CalendarGrid({
</div>
))}
{dayShifts.length > 2 && (
- <div className="text-[10px] sm:text-xs text-muted-foreground font-medium text-center pt-0.5">
+ <div
+ onClick={(e) => {
+ e.stopPropagation();
+ onShowAllShifts?.(day, dayShifts);
+ }}
+ className="text-[10px] sm:text-xs text-primary hover:text-primary/80 font-semibold text-center pt-0.5 hover:underline transition-colors cursor-pointer"
+ >
+{dayShifts.length - 2}
</div>
)}
diff --git a/components/calendar-selector.tsx b/components/calendar-selector.tsx
index 6a2d47d..48bd6ba 100644
--- a/components/calendar-selector.tsx
+++ b/components/calendar-selector.tsx
@@ -10,7 +10,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
-import { Plus, KeyRound, Trash2 } from "lucide-react";
+import { Plus, KeyRound, Trash2, Cloud } from "lucide-react";
interface CalendarSelectorProps {
calendars: CalendarWithCount[];
@@ -19,6 +19,7 @@ interface CalendarSelectorProps {
onCreateNew: () => void;
onManagePassword?: () => void;
onDelete?: (id: string) => void;
+ onICloudSync?: () => void;
}
export function CalendarSelector({
@@ -28,6 +29,7 @@ export function CalendarSelector({
onCreateNew,
onManagePassword,
onDelete,
+ onICloudSync,
}: CalendarSelectorProps) {
const t = useTranslations();
@@ -62,6 +64,17 @@ export function CalendarSelector({
<KeyRound className="h-4 w-4" />
</Button>
)}
+ {onICloudSync && selectedId && (
+ <Button
+ onClick={onICloudSync}
+ size="icon"
+ variant="outline"
+ className="h-9 w-9 sm:h-10 sm:w-10"
+ title={t("icloud.manageTitle")}
+ >
+ <Cloud className="h-4 w-4" />
+ </Button>
+ )}
{onDelete && selectedId && (
<Button
onClick={() => onDelete(selectedId)}
diff --git a/components/day-shifts-dialog.tsx b/components/day-shifts-dialog.tsx
new file mode 100644
index 0000000..6864a09
--- /dev/null
+++ b/components/day-shifts-dialog.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+} from "@/components/ui/dialog";
+import { ShiftWithCalendar } from "@/lib/types";
+import { useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { de, enUS } from "date-fns/locale";
+import { Button } from "@/components/ui/button";
+import { Trash2 } from "lucide-react";
+
+interface DayShiftsDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ date: Date | null;
+ shifts: ShiftWithCalendar[];
+ locale: string;
+ onDeleteShift?: (shiftId: string) => void;
+}
+
+export function DayShiftsDialog({
+ open,
+ onOpenChange,
+ date,
+ shifts,
+ locale,
+ onDeleteShift,
+}: DayShiftsDialogProps) {
+ const t = useTranslations();
+
+ if (!date) return null;
+
+ const dateLocale = locale === "de" ? de : enUS;
+ const formattedDate = format(date, "EEEE, d. MMMM yyyy", {
+ locale: dateLocale,
+ });
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[500px] max-w-[95vw] max-h-[85vh] flex flex-col p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">
+ <DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5">
+ <DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
+ {formattedDate}
+ </DialogTitle>
+ <DialogDescription className="text-sm text-muted-foreground">
+ {shifts.length}{" "}
+ {shifts.length === 1 ? t("shift.shift_one") : t("shift.shifts")}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-3 overflow-y-auto flex-1 p-6">
+ {shifts.map((shift) => (
+ <div
+ key={shift.id}
+ className="flex items-start justify-between p-4 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all"
+ style={{ borderLeftColor: shift.color, borderLeftWidth: 4 }}
+ >
+ <div className="flex-1 min-w-0">
+ <div className="font-semibold flex items-center gap-2">
+ <div
+ className="w-1 h-4 rounded-full"
+ style={{ backgroundColor: shift.color }}
+ />
+ <span className="truncate">{shift.title}</span>
+ </div>
+ <div className="text-sm text-muted-foreground mt-1">
+ {shift.isAllDay ? (
+ <span className="font-medium">{t("shift.allDay")}</span>
+ ) : (
+ <span>
+ {shift.startTime} - {shift.endTime}
+ </span>
+ )}
+ </div>
+ {shift.notes && (
+ <p className="text-xs text-muted-foreground mt-2 line-clamp-2">
+ {shift.notes}
+ </p>
+ )}
+ </div>
+ {onDeleteShift && !shift.icloudSyncId && (
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8 shrink-0 text-destructive hover:text-destructive hover:bg-destructive/10"
+ onClick={() => onDeleteShift(shift.id)}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ ))}
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/icloud-sync-manage-dialog.tsx b/components/icloud-sync-manage-dialog.tsx
new file mode 100644
index 0000000..662f0cc
--- /dev/null
+++ b/components/icloud-sync-manage-dialog.tsx
@@ -0,0 +1,447 @@
+"use client";
+
+import { useState, useEffect, useCallback } from "react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { ColorPicker } from "@/components/ui/color-picker";
+import { useTranslations } from "next-intl";
+import { ICloudSync } from "@/lib/db/schema";
+import { Loader2, Trash2, RefreshCw, Plus, Edit2 } from "lucide-react";
+import { toast } from "sonner";
+import { PRESET_COLORS } from "@/lib/constants";
+import { isValidICloudUrl } from "@/lib/icloud-utils";
+
+interface ICloudSyncManageDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendarId: string | null;
+ onSyncComplete?: () => void;
+}
+
+export function ICloudSyncManageDialog({
+ open,
+ onOpenChange,
+ calendarId,
+ onSyncComplete,
+}: ICloudSyncManageDialogProps) {
+ const t = useTranslations();
+ const [syncs, setSyncs] = useState<ICloudSync[]>([]);
+ const [isLoading, setIsLoading] = useState(false);
+ const [isSyncing, setIsSyncing] = useState<string | null>(null);
+ const [isDeleting, setIsDeleting] = useState<string | null>(null);
+ const [showAddForm, setShowAddForm] = useState(false);
+ const [editingSync, setEditingSync] = useState<ICloudSync | null>(null);
+
+ // Form state
+ const [formName, setFormName] = useState("");
+ const [formUrl, setFormUrl] = useState("");
+ const [formColor, setFormColor] = useState("#3b82f6");
+
+ const fetchSyncs = useCallback(async () => {
+ if (!calendarId) return;
+
+ setIsLoading(true);
+ try {
+ const response = await fetch(
+ `/api/icloud-syncs?calendarId=${calendarId}`
+ );
+ if (response.ok) {
+ const data = await response.json();
+ setSyncs(data);
+ }
+ } catch (error) {
+ console.error("Failed to fetch syncs:", error);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [calendarId]);
+
+ // Load syncs when dialog opens, reset state when it closes
+ useEffect(() => {
+ if (open && calendarId) {
+ fetchSyncs();
+ } else {
+ // Reset all internal state when dialog closes or calendarId becomes falsy
+ setSyncs([]);
+ setIsLoading(false);
+ setIsSyncing(null);
+ setIsDeleting(null);
+ setShowAddForm(false);
+ setEditingSync(null);
+ setFormName("");
+ setFormUrl("");
+ setFormColor("#3b82f6");
+ }
+ }, [open, calendarId, fetchSyncs]);
+
+ const handleAddSync = async () => {
+ if (!calendarId || !formName.trim() || !formUrl.trim()) return;
+
+ // Validate iCloud URL format
+ if (!isValidICloudUrl(formUrl.trim())) {
+ toast.error(t("icloud.invalidUrlFormat"));
+ return;
+ }
+
+ // Check if URL already exists
+ const normalizedUrl = formUrl.trim().toLowerCase();
+ const urlExists = syncs.some(
+ (sync) => sync.icloudUrl.toLowerCase() === normalizedUrl
+ );
+
+ if (urlExists) {
+ toast.error(t("icloud.urlAlreadyExists"));
+ return;
+ }
+
+ setIsLoading(true);
+ try {
+ const response = await fetch("/api/icloud-syncs", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ calendarId,
+ name: formName.trim(),
+ icloudUrl: formUrl.trim(),
+ color: formColor,
+ }),
+ });
+
+ if (response.ok) {
+ const newSync = await response.json();
+ setFormName("");
+ setFormUrl("");
+ setFormColor("#3b82f6");
+ setShowAddForm(false);
+ await fetchSyncs();
+ toast.success(t("icloud.createSuccess"));
+ // Auto-sync the newly created sync
+ await handleSync(newSync.id);
+ } else {
+ const data = await response.json();
+ toast.error(data.error || t("icloud.createError"));
+ }
+ } catch (error) {
+ console.error("Failed to create sync:", error);
+ toast.error(t("icloud.createError"));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleUpdateSync = async () => {
+ if (!editingSync || !formName.trim()) return;
+
+ setIsLoading(true);
+ try {
+ const response = await fetch(`/api/icloud-syncs/${editingSync.id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name: formName.trim(),
+ icloudUrl: formUrl.trim() || undefined,
+ color: formColor,
+ }),
+ });
+
+ if (response.ok) {
+ setEditingSync(null);
+ setFormName("");
+ setFormUrl("");
+ setFormColor("#3b82f6");
+ await fetchSyncs();
+ onSyncComplete?.(); // Trigger refresh of shifts if color was updated
+ toast.success(t("icloud.updateSuccess"));
+ } else {
+ const data = await response.json();
+ toast.error(data.error || t("icloud.updateError"));
+ }
+ } catch (error) {
+ console.error("Failed to update sync:", error);
+ toast.error(t("icloud.updateError"));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleSync = async (syncId: string) => {
+ setIsSyncing(syncId);
+ try {
+ const response = await fetch(`/api/icloud-syncs/${syncId}/sync`, {
+ method: "POST",
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.error || "Failed to sync calendar");
+ }
+
+ await fetchSyncs();
+ onSyncComplete?.();
+
+ // Show sync statistics
+ const stats = data.stats || { created: 0, updated: 0, deleted: 0 };
+ toast.success(
+ `${t("icloud.syncSuccess")}: ${stats.created} ${t(
+ "icloud.statsCreated"
+ )}, ${stats.updated} ${t("icloud.statsUpdated")}, ${stats.deleted} ${t(
+ "icloud.statsDeleted"
+ )}`
+ );
+ } catch (error) {
+ console.error("Sync error:", error);
+ toast.error(
+ error instanceof Error ? error.message : t("icloud.syncError")
+ );
+ } finally {
+ setIsSyncing(null);
+ }
+ };
+
+ const handleDelete = async (syncId: string) => {
+ if (!confirm(t("icloud.deleteConfirm"))) return;
+
+ setIsDeleting(syncId);
+ try {
+ const response = await fetch(`/api/icloud-syncs/${syncId}`, {
+ method: "DELETE",
+ });
+
+ if (response.ok) {
+ await fetchSyncs();
+ onSyncComplete?.();
+ toast.success(t("icloud.deleteSuccess"));
+ } else {
+ const data = await response.json();
+ toast.error(data.error || t("icloud.deleteError"));
+ }
+ } catch (error) {
+ console.error("Delete error:", error);
+ toast.error(t("icloud.deleteError"));
+ } finally {
+ setIsDeleting(null);
+ }
+ };
+
+ const startEdit = (sync: ICloudSync) => {
+ setEditingSync(sync);
+ setFormName(sync.name);
+ setFormUrl(sync.icloudUrl);
+ setFormColor(sync.color);
+ setShowAddForm(false);
+ };
+
+ const cancelEdit = () => {
+ setEditingSync(null);
+ setFormName("");
+ setFormUrl("");
+ setFormColor("#3b82f6");
+ };
+
+ const startAdd = () => {
+ setShowAddForm(true);
+ setEditingSync(null);
+ setFormName("");
+ setFormUrl("");
+ setFormColor("#3b82f6");
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[600px] max-w-[95vw] max-h-[85vh] flex flex-col p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">
+ <DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5">
+ <DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
+ {t("icloud.manageTitle")}
+ </DialogTitle>
+ <DialogDescription className="text-sm text-muted-foreground">
+ {t("icloud.manageDescription")}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-3 overflow-y-auto flex-1 p-6">
+ {/* Existing Syncs List */}
+ {syncs.length > 0 && (
+ <div className="space-y-3">
+ {syncs.map((sync) => (
+ <div
+ key={sync.id}
+ className="flex items-center justify-between p-4 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all"
+ style={{ borderLeftColor: sync.color, borderLeftWidth: 4 }}
+ >
+ <div className="flex-1 min-w-0">
+ <div className="font-semibold flex items-center gap-2">
+ <div
+ className="w-1 h-4 rounded-full"
+ style={{ backgroundColor: sync.color }}
+ />
+ <span className="truncate">{sync.name}</span>
+ </div>
+ {sync.lastSyncedAt && (
+ <p className="text-xs text-muted-foreground mt-1">
+ {t("icloud.lastSynced")}:{" "}
+ {new Date(sync.lastSyncedAt).toLocaleString()}
+ </p>
+ )}
+ </div>
+ <div className="flex gap-1 shrink-0">
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8"
+ onClick={() => startEdit(sync)}
+ disabled={!!isSyncing || !!isDeleting}
+ >
+ <Edit2 className="h-4 w-4" />
+ </Button>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8"
+ onClick={() => handleSync(sync.id)}
+ disabled={!!isSyncing || !!isDeleting}
+ >
+ {isSyncing === sync.id ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <RefreshCw className="h-4 w-4" />
+ )}
+ </Button>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
+ onClick={() => handleDelete(sync.id)}
+ disabled={!!isSyncing || !!isDeleting}
+ >
+ {isDeleting === sync.id ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Trash2 className="h-4 w-4" />
+ )}
+ </Button>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Add/Edit Form */}
+ {(showAddForm || editingSync) && (
+ <div className="rounded-xl border border-border/50 bg-muted/20 p-4 space-y-4">
+ <h3 className="font-semibold">
+ {editingSync ? t("icloud.editSync") : t("icloud.addSync")}
+ </h3>
+
+ <div className="space-y-2">
+ <Label htmlFor="sync-name">{t("icloud.nameLabel")}</Label>
+ <Input
+ id="sync-name"
+ type="text"
+ placeholder={t("icloud.namePlaceholder")}
+ value={formName}
+ onChange={(e) => setFormName(e.target.value)}
+ disabled={isLoading}
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="sync-url">{t("icloud.urlLabel")}</Label>
+ <Input
+ id="sync-url"
+ type="text"
+ placeholder={t("icloud.urlPlaceholder")}
+ value={formUrl}
+ onChange={(e) => setFormUrl(e.target.value)}
+ disabled={isLoading || !!editingSync}
+ />
+ {!editingSync && (
+ <p className="text-xs text-muted-foreground">
+ {t("icloud.urlHint")}
+ </p>
+ )}
+ </div>
+
+ <div className="space-y-2">
+ <ColorPicker
+ color={formColor}
+ onChange={setFormColor}
+ label={t("icloud.colorLabel")}
+ presetColors={PRESET_COLORS}
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("icloud.colorHint")}
+ </p>
+ </div>
+
+ <div className="flex gap-2">
+ <Button
+ variant="outline"
+ onClick={() => {
+ if (editingSync) {
+ cancelEdit();
+ } else {
+ setShowAddForm(false);
+ setFormName("");
+ setFormUrl("");
+ setFormColor("#3b82f6");
+ }
+ }}
+ disabled={isLoading}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ onClick={editingSync ? handleUpdateSync : handleAddSync}
+ disabled={
+ isLoading ||
+ !formName.trim() ||
+ (!editingSync && !formUrl.trim())
+ }
+ >
+ {isLoading ? (
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ ) : null}
+ {editingSync ? t("common.save") : t("icloud.addSync")}
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {/* Add Button */}
+ {!showAddForm && !editingSync && (
+ <Button
+ onClick={startAdd}
+ className="w-full h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25"
+ disabled={!!isSyncing || !!isDeleting}
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ {t("icloud.addNewSync")}
+ </Button>
+ )}
+
+ {/* Instructions */}
+ <div className="rounded-lg border bg-blue-50 dark:bg-blue-950/20 p-4">
+ <div className="text-sm space-y-2">
+ <div className="font-medium">{t("icloud.howToTitle")}</div>
+ <ol className="list-decimal list-inside space-y-1 text-muted-foreground">
+ <li>{t("icloud.howToStep1")}</li>
+ <li>{t("icloud.howToStep2")}</li>
+ <li>{t("icloud.howToStep3")}</li>
+ <li>{t("icloud.howToStep4")}</li>
+ </ol>
+ </div>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/preset-edit-dialog.tsx b/components/preset-edit-dialog.tsx
index 91b0428..b38e1c3 100644
--- a/components/preset-edit-dialog.tsx
+++ b/components/preset-edit-dialog.tsx
@@ -14,17 +14,7 @@ import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { ColorPicker } from "@/components/ui/color-picker";
import { ShiftPreset } from "@/lib/db/schema";
-
-const PRESET_COLORS = [
- { name: "Blue", value: "#3b82f6" },
- { name: "Red", value: "#ef4444" },
- { name: "Green", value: "#10b981" },
- { name: "Amber", value: "#f59e0b" },
- { name: "Violet", value: "#8b5cf6" },
- { name: "Pink", value: "#ec4899" },
- { name: "Cyan", value: "#06b6d4" },
- { name: "Orange", value: "#f97316" },
-];
+import { PRESET_COLORS } from "@/lib/constants";
interface PresetFormData {
title: string;
diff --git a/components/shift-card.tsx b/components/shift-card.tsx
index 3506b50..c0c09c3 100644
--- a/components/shift-card.tsx
+++ b/components/shift-card.tsx
@@ -49,14 +49,16 @@ export function ShiftCard({ shift, onDelete }: ShiftCardProps) {
</p>
)}
</div>
- <Button
- variant="ghost"
- size="icon"
- className="h-8 w-8 sm:h-9 sm:w-9 transition-all text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950 flex-shrink-0 rounded-full"
- onClick={() => onDelete(shift.id)}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
+ {!shift.icloudSyncId && (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8 sm:h-9 sm:w-9 transition-all text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950 flex-shrink-0 rounded-full"
+ onClick={() => onDelete(shift.id)}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ )}
</div>
<div
className="absolute inset-0 opacity-[0.05] pointer-events-none"
diff --git a/components/shift-form-fields.tsx b/components/shift-form-fields.tsx
index 3b291fe..d6b76a1 100644
--- a/components/shift-form-fields.tsx
+++ b/components/shift-form-fields.tsx
@@ -6,17 +6,7 @@ import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { ColorPicker } from "@/components/ui/color-picker";
import { ShiftFormData } from "@/components/shift-dialog";
-
-const PRESET_COLORS = [
- { name: "Blue", value: "#3b82f6" },
- { name: "Red", value: "#ef4444" },
- { name: "Green", value: "#10b981" },
- { name: "Amber", value: "#f59e0b" },
- { name: "Violet", value: "#8b5cf6" },
- { name: "Pink", value: "#ec4899" },
- { name: "Cyan", value: "#06b6d4" },
- { name: "Orange", value: "#f97316" },
-];
+import { PRESET_COLORS } from "@/lib/constants";
interface ShiftFormFieldsProps {
formData: ShiftFormData;
diff --git a/drizzle/0004_modern_swarm.sql b/drizzle/0004_modern_swarm.sql
new file mode 100644
index 0000000..346c574
--- /dev/null
+++ b/drizzle/0004_modern_swarm.sql
@@ -0,0 +1,15 @@
+CREATE TABLE `icloud_syncs` (
+ `id` text PRIMARY KEY NOT NULL,
+ `calendar_id` text NOT NULL,
+ `name` text NOT NULL,
+ `icloud_url` text NOT NULL,
+ `color` text DEFAULT '#3b82f6' NOT NULL,
+ `last_synced_at` integer,
+ `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
+ALTER TABLE `shifts` ADD `icloud_event_id` text;--> statement-breakpoint
+ALTER TABLE `shifts` ADD `icloud_sync_id` text REFERENCES icloud_syncs(id) ON DELETE cascade;--> statement-breakpoint
+ALTER TABLE `shifts` ADD `synced_from_icloud` integer DEFAULT false NOT NULL;
\ No newline at end of file
diff --git a/drizzle/meta/0004_snapshot.json b/drizzle/meta/0004_snapshot.json
new file mode 100644
index 0000000..4b0a415
--- /dev/null
+++ b/drizzle/meta/0004_snapshot.json
@@ -0,0 +1,498 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "3aedc83b-9240-434e-ba61-b4de693ca043",
+ "prevId": "bf43fc23-219f-45cc-b9b0-0773af4656b0",
+ "tables": {
+ "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
+ },
+ "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": {}
+ },
+ "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'"
+ },
+ "password_hash": {
+ "name": "password_hash",
+ "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": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "icloud_syncs": {
+ "name": "icloud_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
+ },
+ "icloud_url": {
+ "name": "icloud_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "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": {
+ "icloud_syncs_calendar_id_calendars_id_fk": {
+ "name": "icloud_syncs_calendar_id_calendars_id_fk",
+ "tableFrom": "icloud_syncs",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_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
+ },
+ "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
+ },
+ "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": {}
+ },
+ "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
+ },
+ "icloud_event_id": {
+ "name": "icloud_event_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "icloud_sync_id": {
+ "name": "icloud_sync_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "synced_from_icloud": {
+ "name": "synced_from_icloud",
+ "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_icloud_sync_id_icloud_syncs_id_fk": {
+ "name": "shifts_icloud_sync_id_icloud_syncs_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "icloud_syncs",
+ "columnsFrom": [
+ "icloud_sync_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index 9bcc7c7..9db361e 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -29,6 +29,13 @@
"when": 1763857902681,
"tag": "0003_serious_wolfpack",
"breakpoints": true
+ },
+ {
+ "idx": 4,
+ "version": "6",
+ "when": 1764709080826,
+ "tag": "0004_modern_swarm",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/lib/constants.ts b/lib/constants.ts
new file mode 100644
index 0000000..fc9058c
--- /dev/null
+++ b/lib/constants.ts
@@ -0,0 +1,17 @@
+/**
+ * Shared constants used across the application
+ */
+
+/**
+ * Preset color options for shifts and calendars
+ */
+export const PRESET_COLORS = [
+ { name: "Blue", value: "#3b82f6" },
+ { name: "Red", value: "#ef4444" },
+ { name: "Green", value: "#10b981" },
+ { name: "Amber", value: "#f59e0b" },
+ { name: "Violet", value: "#8b5cf6" },
+ { name: "Pink", value: "#ec4899" },
+ { name: "Cyan", value: "#06b6d4" },
+ { name: "Orange", value: "#f97316" },
+];
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 1a585ff..15d7bb8 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -16,6 +16,25 @@ export const calendars = sqliteTable("calendars", {
.default(sql`CURRENT_TIMESTAMP`),
});
+export const icloudSyncs = sqliteTable("icloud_syncs", {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ calendarId: text("calendar_id")
+ .notNull()
+ .references(() => calendars.id, { onDelete: "cascade" }),
+ name: text("name").notNull(),
+ icloudUrl: text("icloud_url").notNull(),
+ color: text("color").notNull().default("#3b82f6"),
+ lastSyncedAt: integer("last_synced_at", { mode: "timestamp" }),
+ createdAt: integer("created_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ updatedAt: integer("updated_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+});
+
export const shifts = sqliteTable("shifts", {
id: text("id")
.primaryKey()
@@ -36,6 +55,13 @@ export const shifts = sqliteTable("shifts", {
isSecondary: integer("is_secondary", { mode: "boolean" })
.notNull()
.default(false),
+ icloudEventId: text("icloud_event_id"),
+ icloudSyncId: text("icloud_sync_id").references(() => icloudSyncs.id, {
+ onDelete: "cascade",
+ }),
+ syncedFromIcloud: integer("synced_from_icloud", { mode: "boolean" })
+ .notNull()
+ .default(false),
createdAt: integer("created_at", { mode: "timestamp" })
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
@@ -87,6 +113,8 @@ export const calendarNotes = sqliteTable("calendar_notes", {
export type Calendar = typeof calendars.$inferSelect;
export type NewCalendar = typeof calendars.$inferInsert;
+export type ICloudSync = typeof icloudSyncs.$inferSelect;
+export type NewICloudSync = typeof icloudSyncs.$inferInsert;
export type Shift = typeof shifts.$inferSelect;
export type NewShift = typeof shifts.$inferInsert;
export type ShiftPreset = typeof shiftPresets.$inferSelect;
diff --git a/lib/icloud-utils.ts b/lib/icloud-utils.ts
new file mode 100644
index 0000000..2034461
--- /dev/null
+++ b/lib/icloud-utils.ts
@@ -0,0 +1,219 @@
+/**
+ * iCloud calendar utility functions
+ */
+
+import ICAL from "ical.js";
+
+/**
+ * Validates iCloud calendar URL to prevent SSRF vulnerabilities
+ * @param url - The URL to validate
+ * @returns true if valid, false otherwise
+ */
+export function isValidICloudUrl(url: string): boolean {
+ try {
+ const parsedUrl = new URL(url);
+
+ // Check if protocol is webcal or https
+ if (!["webcal:", "https:"].includes(parsedUrl.protocol)) {
+ return false;
+ }
+
+ // Check if hostname is from iCloud domain
+ const hostname = parsedUrl.hostname.toLowerCase();
+ if (!hostname.endsWith(".icloud.com") && hostname !== "icloud.com") {
+ return false;
+ }
+
+ return true;
+ } catch {
+ // Invalid URL format
+ return false;
+ }
+}
+
+/**
+ * Expands recurring events into individual occurrences within a time window
+ * @param vevent - The VEVENT component from iCal.js
+ * @param startWindow - Start of the time window (default: now)
+ * @param endWindow - End of the time window (default: 1 year from now)
+ * @returns Array of event occurrences with their dates
+ */
+export function expandRecurringEvents(
+ vevent: ICAL.Component,
+ startWindow?: Date,
+ endWindow?: Date
+): Array<{
+ event: ICAL.Event;
+ startDate: ICAL.Time;
+ endDate: ICAL.Time;
+ recurrenceId?: ICAL.Time;
+}> {
+ const event = new ICAL.Event(vevent);
+ const occurrences: Array<{
+ event: ICAL.Event;
+ startDate: ICAL.Time;
+ endDate: ICAL.Time;
+ recurrenceId?: ICAL.Time;
+ }> = [];
+
+ // Default time window: now to 1 year from now
+ const start = startWindow || new Date();
+ const end = endWindow || new Date(Date.now() + 365 * 24 * 60 * 60 * 1000);
+
+ const startTime = ICAL.Time.fromJSDate(start, true);
+ const endTime = ICAL.Time.fromJSDate(end, true);
+
+ // Check if this event has a recurrence rule
+ if (event.isRecurring()) {
+ // Use the iterator to expand recurring events
+ const iterator = event.iterator();
+ let next;
+
+ // Iterate through all occurrences within the time window
+ while ((next = iterator.next())) {
+ // Stop if we've gone past the end window
+ if (next.compare(endTime) > 0) {
+ break;
+ }
+
+ // Skip if before start window
+ if (next.compare(startTime) < 0) {
+ continue;
+ }
+
+ // Calculate the end time for this occurrence
+ const duration = event.duration;
+ const occurrenceEnd = next.clone();
+ occurrenceEnd.addDuration(duration);
+
+ occurrences.push({
+ event,
+ startDate: next,
+ endDate: occurrenceEnd,
+ recurrenceId: next,
+ });
+ }
+ } else {
+ // Non-recurring event - just return the single occurrence if it's within the window
+ const eventStart = event.startDate;
+ const eventEnd = event.endDate;
+
+ if (
+ eventStart &&
+ eventEnd &&
+ eventStart.compare(endTime) <= 0 &&
+ eventEnd.compare(startTime) >= 0
+ ) {
+ occurrences.push({
+ event,
+ startDate: eventStart,
+ endDate: eventEnd,
+ });
+ }
+ }
+
+ return occurrences;
+}
+
+/**
+ * Splits a multi-day event into separate day entries
+ * @param startDate - Start date/time of the event
+ * @param endDate - End date/time of the event
+ * @param isAllDay - Whether the event is an all-day event
+ * @returns Array of day entries with date and time information
+ */
+export function splitMultiDayEvent(
+ startDate: Date,
+ endDate: Date,
+ isAllDay: boolean
+): Array<{
+ date: Date;
+ startTime: string;
+ endTime: string;
+ dayIndex: number;
+}> {
+ const days: Array<{
+ date: Date;
+ startTime: string;
+ endTime: string;
+ dayIndex: number;
+ }> = [];
+
+ // Normalize dates to midnight for comparison
+ const startDay = new Date(
+ startDate.getFullYear(),
+ startDate.getMonth(),
+ startDate.getDate()
+ );
+ const endDay = new Date(
+ endDate.getFullYear(),
+ endDate.getMonth(),
+ endDate.getDate()
+ );
+
+ // Check if event spans multiple days
+ const daysDiff = Math.floor(
+ (endDay.getTime() - startDay.getTime()) / (1000 * 60 * 60 * 24)
+ );
+
+ if (daysDiff === 0) {
+ // Single day event
+ let startTime = "00:00";
+ let endTime = "23:59";
+
+ if (!isAllDay) {
+ const startHours = startDate.getHours().toString().padStart(2, "0");
+ const startMinutes = startDate.getMinutes().toString().padStart(2, "0");
+ startTime = `${startHours}:${startMinutes}`;
+
+ const endHours = endDate.getHours().toString().padStart(2, "0");
+ const endMinutes = endDate.getMinutes().toString().padStart(2, "0");
+ endTime = `${endHours}:${endMinutes}`;
+ }
+
+ days.push({
+ date: new Date(startDay),
+ startTime,
+ endTime,
+ dayIndex: 0,
+ });
+ } else {
+ // Multi-day event - split into separate days
+ for (let i = 0; i <= daysDiff; i++) {
+ const currentDay = new Date(startDay);
+ currentDay.setDate(startDay.getDate() + i);
+
+ let startTime = "00:00";
+ let endTime = "23:59";
+
+ if (!isAllDay) {
+ if (i === 0) {
+ // First day: use actual start time, end at midnight
+ const startHours = startDate.getHours().toString().padStart(2, "0");
+ const startMinutes = startDate
+ .getMinutes()
+ .toString()
+ .padStart(2, "0");
+ startTime = `${startHours}:${startMinutes}`;
+ endTime = "23:59";
+ } else if (i === daysDiff) {
+ // Last day: start at midnight, use actual end time
+ startTime = "00:00";
+ const endHours = endDate.getHours().toString().padStart(2, "0");
+ const endMinutes = endDate.getMinutes().toString().padStart(2, "0");
+ endTime = `${endHours}:${endMinutes}`;
+ }
+ // Middle days keep default 00:00 - 23:59
+ }
+
+ days.push({
+ date: new Date(currentDay),
+ startTime,
+ endTime,
+ dayIndex: i,
+ });
+ }
+ }
+
+ return days;
+}
diff --git a/lib/types.ts b/lib/types.ts
index 223cd23..876ee29 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -1,5 +1,5 @@
// Re-export types from Drizzle schema
-export type { Calendar, Shift } from "./db/schema";
+export type { Calendar, Shift, ICloudSync } from "./db/schema";
export interface CalendarWithCount {
id: string;
@@ -26,6 +26,7 @@ export interface ShiftWithCalendar {
color: string;
notes?: string | null;
isAllDay?: boolean;
+ icloudSyncId?: string | null;
createdAt: Date | null;
updatedAt: Date | null;
}
diff --git a/messages/de.json b/messages/de.json
index 6bb6919..ce68b05 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -157,5 +157,39 @@
},
"version": {
"label": "Version"
+ },
+ "icloud": {
+ "manageTitle": "iCloud-Synchronisierungen verwalten",
+ "manageDescription": "Füge mehrere iCloud-Kalendersynchronisierungen für diesen Kalender hinzu und verwalte sie",
+ "addSync": "Synchronisierung hinzufügen",
+ "addNewSync": "Neue iCloud-Synchronisierung hinzufügen",
+ "editSync": "iCloud-Synchronisierung bearbeiten",
+ "nameLabel": "Synchronisierungsname",
+ "namePlaceholder": "z.B. Arbeitskalender, Privatkalender",
+ "urlLabel": "iCloud-Kalender URL",
+ "urlPlaceholder": "webcal://p108-caldav.icloud.com/published/2/...",
+ "urlHint": "Füge die webcal:// URL von iCloud ein (beginnt mit webcal://)",
+ "urlAlreadyExists": "Diese URL wurde bereits hinzugefügt",
+ "invalidUrlFormat": "Ungültiges iCloud URL-Format. URL muss mit webcal:// oder https:// beginnen und von icloud.com stammen",
+ "colorLabel": "Schichten-Farbe",
+ "colorHint": "Wähle die Farbe für alle importierten Schichten",
+ "lastSynced": "Zuletzt synchronisiert",
+ "syncError": "Kalender konnte nicht synchronisiert werden",
+ "createError": "Synchronisierung konnte nicht erstellt werden",
+ "createSuccess": "Synchronisierung erfolgreich erstellt",
+ "updateError": "Synchronisierung konnte nicht aktualisiert werden",
+ "updateSuccess": "Synchronisierung erfolgreich aktualisiert",
+ "deleteError": "Synchronisierung konnte nicht gelöscht werden",
+ "deleteSuccess": "Synchronisierung erfolgreich gelöscht",
+ "deleteConfirm": "Diese iCloud-Synchronisierung löschen? Alle synchronisierten Schichten werden entfernt.",
+ "syncSuccess": "Synchronisierung erfolgreich",
+ "statsCreated": "erstellt",
+ "statsUpdated": "aktualisiert",
+ "statsDeleted": "gelöscht",
+ "howToTitle": "So erhältst du deine iCloud-Kalender URL:",
+ "howToStep1": "Öffne iCloud.com und gehe zu Kalender",
+ "howToStep2": "Klicke auf das Teilen-Symbol neben deinem Kalender",
+ "howToStep3": "Aktiviere 'Öffentlicher Kalender'",
+ "howToStep4": "Kopiere die URL und füge sie hier ein"
}
}
diff --git a/messages/en.json b/messages/en.json
index 8a52dee..3f2dd84 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -157,5 +157,39 @@
},
"version": {
"label": "Version"
+ },
+ "icloud": {
+ "manageTitle": "Manage iCloud Syncs",
+ "manageDescription": "Add and manage multiple iCloud calendar syncs for this calendar",
+ "addSync": "Add Sync",
+ "addNewSync": "Add New iCloud Sync",
+ "editSync": "Edit iCloud Sync",
+ "nameLabel": "Sync Name",
+ "namePlaceholder": "e.g., Work Calendar, Personal Calendar",
+ "urlLabel": "iCloud Calendar URL",
+ "urlPlaceholder": "webcal://p108-caldav.icloud.com/published/2/...",
+ "urlHint": "Paste the webcal:// URL from iCloud (starts with webcal://)",
+ "urlAlreadyExists": "This URL has already been added",
+ "invalidUrlFormat": "Invalid iCloud URL format. URL must start with webcal:// or https:// and be from icloud.com",
+ "colorLabel": "Shift Color",
+ "colorHint": "Choose the color for all imported shifts",
+ "lastSynced": "Last synced",
+ "syncError": "Failed to sync calendar",
+ "createError": "Failed to create sync",
+ "createSuccess": "Sync created successfully",
+ "updateError": "Failed to update sync",
+ "updateSuccess": "Sync updated successfully",
+ "deleteError": "Failed to delete sync",
+ "deleteSuccess": "Sync deleted successfully",
+ "deleteConfirm": "Delete this iCloud sync? All synced shifts will be removed.",
+ "syncSuccess": "Sync successful",
+ "statsCreated": "created",
+ "statsUpdated": "updated",
+ "statsDeleted": "deleted",
+ "howToTitle": "How to get your iCloud calendar URL:",
+ "howToStep1": "Open iCloud.com and go to Calendar",
+ "howToStep2": "Click the share icon next to your calendar",
+ "howToStep3": "Enable 'Public Calendar'",
+ "howToStep4": "Copy the URL and paste it here"
}
}
diff --git a/package-lock.json b/package-lock.json
index f80323f..57e8edd 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -20,6 +20,7 @@
"dotenv": "^17.2.3",
"drizzle-kit": "^0.31.7",
"drizzle-orm": "^0.44.7",
+ "ical.js": "^2.2.1",
"lucide-react": "^0.554.0",
"motion": "^12.23.24",
"next": "16.0.3",
@@ -6232,6 +6233,12 @@
"hermes-estree": "0.25.1"
}
},
+ "node_modules/ical.js": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/ical.js/-/ical.js-2.2.1.tgz",
+ "integrity": "sha512-yK/UlPbEs316igb/tjRgbFA8ZV75rCsBJp/hWOatpyaPNlgw0dGDmU+FoicOcwX4xXkeXOkYiOmCqNPFpNPkQg==",
+ "license": "MPL-2.0"
+ },
"node_modules/ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
diff --git a/package.json b/package.json
index 7bada45..6f0c8c1 100644
--- a/package.json
+++ b/package.json
@@ -25,6 +25,7 @@
"dotenv": "^17.2.3",
"drizzle-kit": "^0.31.7",
"drizzle-orm": "^0.44.7",
+ "ical.js": "^2.2.1",
"lucide-react": "^0.554.0",
"motion": "^12.23.24",
"next": "16.0.3",