Skip to content

Your favorite shift management application!

feat: Add Google calendar sync (#24)

panteLd4dde1b046c7
diff --git a/app/api/icloud-syncs/[id]/route.ts b/app/api/external-syncs/[id]/route.ts
similarity index 59%
rename from app/api/icloud-syncs/[id]/route.ts
rename to app/api/external-syncs/[id]/route.ts
index b0fe77a..ee4b058 100644
--- a/app/api/icloud-syncs/[id]/route.ts
+++ b/app/api/external-syncs/[id]/route.ts
@@ -1,11 +1,14 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { icloudSyncs, shifts } from "@/lib/db/schema";
+import { externalSyncs, shifts } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
import { eventEmitter } from "@/lib/event-emitter";
-import { isValidICloudUrl } from "@/lib/icloud-utils";
+import {
+ isValidCalendarUrl,
+ type CalendarSyncType,
+} from "@/lib/external-calendar-utils";
-// GET single iCloud sync
+// GET single external sync
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
@@ -13,30 +16,30 @@ export async function GET(
try {
const { id } = await params;
- const [icloudSync] = await db
+ const [externalSync] = await db
.select()
- .from(icloudSyncs)
- .where(eq(icloudSyncs.id, id))
+ .from(externalSyncs)
+ .where(eq(externalSyncs.id, id))
.limit(1);
- if (!icloudSync) {
+ if (!externalSync) {
return NextResponse.json(
- { error: "iCloud sync not found" },
+ { error: "External sync not found" },
{ status: 404 }
);
}
- return NextResponse.json(icloudSync);
+ return NextResponse.json(externalSync);
} catch (error) {
- console.error("Failed to fetch iCloud sync:", error);
+ console.error("Failed to fetch external sync:", error);
return NextResponse.json(
- { error: "Failed to fetch iCloud sync" },
+ { error: "Failed to fetch external sync" },
{ status: 500 }
);
}
}
-// PATCH update iCloud sync
+// PATCH update external sync
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
@@ -46,7 +49,7 @@ export async function PATCH(
const body = await request.json();
const {
name,
- icloudUrl,
+ calendarUrl,
color,
displayMode,
isHidden,
@@ -54,17 +57,39 @@ export async function PATCH(
autoSyncInterval,
} = body;
- // Validate iCloud URL if provided
- if (icloudUrl !== undefined && !isValidICloudUrl(icloudUrl)) {
+ // Get existing sync to validate URL with correct sync type
+ const [existingSync] = await db
+ .select()
+ .from(externalSyncs)
+ .where(eq(externalSyncs.id, id))
+ .limit(1);
+
+ if (!existingSync) {
return NextResponse.json(
- {
- error:
- "Invalid iCloud URL. URL must use webcal:// or https:// protocol and be from icloud.com domain",
- },
- { status: 400 }
+ { error: "External sync not found" },
+ { status: 404 }
);
}
+ // Validate calendar URL if provided
+ if (calendarUrl !== undefined) {
+ if (
+ !isValidCalendarUrl(
+ calendarUrl,
+ existingSync.syncType as CalendarSyncType
+ )
+ ) {
+ const domain =
+ existingSync.syncType === "icloud" ? "icloud.com" : "google.com";
+ return NextResponse.json(
+ {
+ error: `Invalid ${existingSync.syncType} calendar URL. URL must use webcal:// or https:// protocol and be from ${domain} domain`,
+ },
+ { status: 400 }
+ );
+ }
+ }
+
// Validate autoSyncInterval if provided
const validIntervals = [0, 5, 15, 30, 60, 120, 360, 720, 1440];
if (
@@ -86,7 +111,7 @@ export async function PATCH(
};
if (name !== undefined) updateData.name = name;
- if (icloudUrl !== undefined) updateData.icloudUrl = icloudUrl;
+ if (calendarUrl !== undefined) updateData.calendarUrl = calendarUrl;
if (color !== undefined) updateData.color = color;
if (displayMode !== undefined) updateData.displayMode = displayMode;
if (isHidden !== undefined) updateData.isHidden = isHidden;
@@ -95,14 +120,14 @@ export async function PATCH(
updateData.autoSyncInterval = autoSyncInterval;
const [updated] = await db
- .update(icloudSyncs)
+ .update(externalSyncs)
.set(updateData)
- .where(eq(icloudSyncs.id, id))
+ .where(eq(externalSyncs.id, id))
.returning();
if (!updated) {
return NextResponse.json(
- { error: "iCloud sync not found" },
+ { error: "External sync not found" },
{ status: 404 }
);
}
@@ -115,14 +140,14 @@ export async function PATCH(
color: color,
updatedAt: new Date(),
})
- .where(eq(shifts.icloudSyncId, id));
+ .where(eq(shifts.externalSyncId, 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 },
+ data: { externalSyncId: id, colorUpdated: true },
});
}
@@ -132,21 +157,21 @@ export async function PATCH(
type: "shift",
action: "update",
calendarId: updated.calendarId,
- data: { icloudSyncId: id, visibilityUpdated: true },
+ data: { externalSyncId: id, visibilityUpdated: true },
});
}
return NextResponse.json(updated);
} catch (error) {
- console.error("Failed to update iCloud sync:", error);
+ console.error("Failed to update external sync:", error);
return NextResponse.json(
- { error: "Failed to update iCloud sync" },
+ { error: "Failed to update external sync" },
{ status: 500 }
);
}
}
-// DELETE iCloud sync and all associated shifts
+// DELETE external sync and all associated shifts
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
@@ -154,13 +179,13 @@ export async function DELETE(
try {
const { id } = await params;
- await db.delete(icloudSyncs).where(eq(icloudSyncs.id, id));
+ await db.delete(externalSyncs).where(eq(externalSyncs.id, id));
return NextResponse.json({ success: true });
} catch (error) {
- console.error("Failed to delete iCloud sync:", error);
+ console.error("Failed to delete external sync:", error);
return NextResponse.json(
- { error: "Failed to delete iCloud sync" },
+ { error: "Failed to delete external sync" },
{ status: 500 }
);
}
diff --git a/app/api/icloud-syncs/[id]/sync/route.ts b/app/api/external-syncs/[id]/sync/route.ts
similarity index 79%
rename from app/api/icloud-syncs/[id]/sync/route.ts
rename to app/api/external-syncs/[id]/sync/route.ts
index 5d02c55..c278854 100644
--- a/app/api/icloud-syncs/[id]/sync/route.ts
+++ b/app/api/external-syncs/[id]/sync/route.ts
@@ -1,29 +1,35 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { icloudSyncs, shifts } from "@/lib/db/schema";
+import { externalSyncs, shifts } from "@/lib/db/schema";
import { eq, inArray } from "drizzle-orm";
import ICAL from "ical.js";
-import { expandRecurringEvents, splitMultiDayEvent } from "@/lib/icloud-utils";
+import {
+ expandRecurringEvents,
+ splitMultiDayEvent,
+} from "@/lib/external-calendar-utils";
/**
* Core sync logic extracted for reuse by both API route and auto-sync service
*/
-export async function syncICloudCalendar(syncId: string) {
- // Get the iCloud sync configuration
- const [icloudSync] = await db
+export async function syncExternalCalendar(syncId: string) {
+ // Get the external sync configuration
+ const [externalSync] = await db
.select()
- .from(icloudSyncs)
- .where(eq(icloudSyncs.id, syncId))
+ .from(externalSyncs)
+ .where(eq(externalSyncs.id, syncId))
.limit(1);
- if (!icloudSync) {
- throw new Error("iCloud sync configuration not found");
+ if (!externalSync) {
+ throw new Error("External sync configuration not found");
}
- // Convert webcal:// to https:// for iCloud URLs
- const fetchUrl = icloudSync.icloudUrl.replace(/^webcal:\/\//i, "https://");
+ // Convert webcal:// to https:// for calendar URLs
+ const fetchUrl = externalSync.calendarUrl.replace(
+ /^webcal:\/\//i,
+ "https://"
+ );
- // Fetch the calendar from the specified iCloud URL with timeout protection
+ // Fetch the calendar from the specified URL with timeout protection
let icsData: string;
try {
const controller = new AbortController();
@@ -49,11 +55,11 @@ export async function syncICloudCalendar(syncId: string) {
throw fetchError;
}
} catch (error) {
- console.error("Error fetching iCloud calendar:", error);
+ console.error("Error fetching external calendar:", error);
throw new Error(
error instanceof Error
? error.message
- : "Failed to fetch iCloud calendar. Please check the URL."
+ : "Failed to fetch external calendar. Please check the URL."
);
}
@@ -75,11 +81,11 @@ export async function syncICloudCalendar(syncId: string) {
const syncWindowEnd = new Date();
syncWindowEnd.setFullYear(syncWindowEnd.getFullYear() + 1);
- // Get existing iCloud synced shifts for this sync
+ // Get existing synced shifts for this sync
const existingShifts = await db
.select()
.from(shifts)
- .where(eq(shifts.icloudSyncId, syncId));
+ .where(eq(shifts.externalSyncId, syncId));
const processedEventIds = new Set<string>();
const shiftsToInsert: (typeof shifts.$inferInsert)[] = [];
@@ -125,24 +131,24 @@ export async function syncICloudCalendar(syncId: string) {
processedEventIds.add(eventId);
const shiftData = {
- calendarId: icloudSync.calendarId,
+ calendarId: externalSync.calendarId,
date: dayEntry.date,
startTime: dayEntry.startTime,
endTime: dayEntry.endTime,
title: event.summary || "Untitled Event",
- color: icloudSync.color,
+ color: externalSync.color,
notes: event.description || null,
isAllDay,
isSecondary: false,
- icloudEventId: eventId,
- icloudSyncId: syncId,
- syncedFromIcloud: true,
+ externalEventId: eventId,
+ externalSyncId: syncId,
+ syncedFromExternal: true,
presetId: null,
};
// Check if this event already exists
const existingShift = existingShifts.find(
- (s) => s.icloudEventId === eventId
+ (s) => s.externalEventId === eventId
);
if (existingShift) {
@@ -167,7 +173,9 @@ export async function syncICloudCalendar(syncId: string) {
// Calculate which shifts to delete before transaction
const shiftIdsToDelete = existingShifts
- .filter((s) => s.icloudEventId && !processedEventIds.has(s.icloudEventId))
+ .filter(
+ (s) => s.externalEventId && !processedEventIds.has(s.externalEventId)
+ )
.map((s) => s.id);
// Perform batch operations in a transaction for atomicity and better performance
@@ -186,18 +194,18 @@ export async function syncICloudCalendar(syncId: string) {
}
}
- // Delete shifts that are no longer in the iCloud calendar in one batch
+ // Delete shifts that are no longer in the external calendar in one batch
if (shiftIdsToDelete.length > 0) {
tx.delete(shifts).where(inArray(shifts.id, shiftIdsToDelete)).run();
}
// Update last sync time
- tx.update(icloudSyncs)
+ tx.update(externalSyncs)
.set({
lastSyncedAt: new Date(),
updatedAt: new Date(),
})
- .where(eq(icloudSyncs.id, syncId))
+ .where(eq(externalSyncs.id, syncId))
.run();
// Return transaction stats
@@ -207,7 +215,8 @@ export async function syncICloudCalendar(syncId: string) {
deleted: shiftIdsToDelete.length,
totalEvents: vevents.length,
totalOccurrences: shiftsToInsert.length + shiftsToUpdate.length,
- calendarId: icloudSync.calendarId,
+ calendarId: externalSync.calendarId,
+ syncType: externalSync.syncType,
};
});
@@ -220,14 +229,14 @@ export async function POST(
) {
try {
const { id: syncId } = await params;
- const stats = await syncICloudCalendar(syncId);
+ const stats = await syncExternalCalendar(syncId);
return NextResponse.json({
success: true,
stats,
});
} catch (error) {
- console.error("Error syncing iCloud calendar:", error);
+ console.error("Error syncing external calendar:", error);
const errorMessage =
error instanceof Error ? error.message : "Internal server error";
return NextResponse.json({ error: errorMessage }, { status: 500 });
diff --git a/app/api/icloud-syncs/route.ts b/app/api/external-syncs/route.ts
similarity index 54%
rename from app/api/icloud-syncs/route.ts
rename to app/api/external-syncs/route.ts
index 03572b2..fdb2bd7 100644
--- a/app/api/icloud-syncs/route.ts
+++ b/app/api/external-syncs/route.ts
@@ -1,10 +1,13 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { icloudSyncs } from "@/lib/db/schema";
+import { externalSyncs } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
-import { isValidICloudUrl } from "@/lib/icloud-utils";
+import {
+ isValidCalendarUrl,
+ type CalendarSyncType,
+} from "@/lib/external-calendar-utils";
-// GET all iCloud syncs for a calendar
+// GET all external syncs for a calendar
export async function GET(request: Request) {
try {
const { searchParams } = new URL(request.url);
@@ -19,46 +22,57 @@ export async function GET(request: Request) {
const syncs = await db
.select()
- .from(icloudSyncs)
- .where(eq(icloudSyncs.calendarId, calendarId))
- .orderBy(icloudSyncs.createdAt);
+ .from(externalSyncs)
+ .where(eq(externalSyncs.calendarId, calendarId))
+ .orderBy(externalSyncs.createdAt);
return NextResponse.json(syncs);
} catch (error) {
- console.error("Failed to fetch iCloud syncs:", error);
+ console.error("Failed to fetch external syncs:", error);
return NextResponse.json(
- { error: "Failed to fetch iCloud syncs" },
+ { error: "Failed to fetch external syncs" },
{ status: 500 }
);
}
}
-// POST create new iCloud sync
+// POST create new external sync
export async function POST(request: Request) {
try {
const body = await request.json();
const {
calendarId,
name,
- icloudUrl,
+ syncType,
+ calendarUrl,
color,
displayMode,
autoSyncInterval,
} = body;
- if (!calendarId || !name || !icloudUrl) {
+ if (!calendarId || !name || !calendarUrl || !syncType) {
return NextResponse.json(
- { error: "Calendar ID, name, and iCloud URL are required" },
+ {
+ error: "Calendar ID, name, sync type, and calendar URL are required",
+ },
+ { status: 400 }
+ );
+ }
+
+ // Validate sync type
+ if (!["icloud", "google"].includes(syncType)) {
+ return NextResponse.json(
+ { error: "Sync type must be either 'icloud' or 'google'" },
{ status: 400 }
);
}
- // Validate iCloud URL to prevent SSRF
- if (!isValidICloudUrl(icloudUrl)) {
+ // Validate calendar URL to prevent SSRF
+ if (!isValidCalendarUrl(calendarUrl, syncType as CalendarSyncType)) {
+ const domain = syncType === "icloud" ? "icloud.com" : "google.com";
return NextResponse.json(
{
- error:
- "Invalid iCloud URL. URL must use webcal:// or https:// protocol and be from icloud.com domain",
+ error: `Invalid ${syncType} calendar URL. URL must use webcal:// or https:// protocol and be from ${domain} domain`,
},
{ status: 400 }
);
@@ -80,13 +94,14 @@ export async function POST(request: Request) {
);
}
- const [icloudSync] = await db
- .insert(icloudSyncs)
+ const [externalSync] = await db
+ .insert(externalSyncs)
.values({
id: crypto.randomUUID(),
calendarId,
name,
- icloudUrl,
+ syncType,
+ calendarUrl,
color: color || "#3b82f6",
displayMode: displayMode || "normal",
autoSyncInterval: autoSyncInterval || 0,
@@ -95,11 +110,11 @@ export async function POST(request: Request) {
})
.returning();
- return NextResponse.json(icloudSync, { status: 201 });
+ return NextResponse.json(externalSync, { status: 201 });
} catch (error) {
- console.error("Failed to create iCloud sync:", error);
+ console.error("Failed to create external sync:", error);
return NextResponse.json(
- { error: "Failed to create iCloud sync" },
+ { error: "Failed to create external sync" },
{ status: 500 }
);
}
diff --git a/app/api/shifts/route.ts b/app/api/shifts/route.ts
index a1f4c03..276d03c 100644
--- a/app/api/shifts/route.ts
+++ b/app/api/shifts/route.ts
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { calendars, shifts, icloudSyncs } from "@/lib/db/schema";
+import { calendars, shifts, externalSyncs } from "@/lib/db/schema";
import { eq, and, gte, lte, or, isNull } from "drizzle-orm";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
@@ -30,8 +30,8 @@ export async function GET(request: Request) {
notes: shifts.notes,
isAllDay: shifts.isAllDay,
isSecondary: shifts.isSecondary,
- syncedFromIcloud: shifts.syncedFromIcloud,
- icloudSyncId: shifts.icloudSyncId,
+ syncedFromExternal: shifts.syncedFromExternal,
+ externalSyncId: shifts.externalSyncId,
createdAt: shifts.createdAt,
updatedAt: shifts.updatedAt,
calendar: {
@@ -42,7 +42,7 @@ export async function GET(request: Request) {
})
.from(shifts)
.leftJoin(calendars, eq(shifts.calendarId, calendars.id))
- .leftJoin(icloudSyncs, eq(shifts.icloudSyncId, icloudSyncs.id));
+ .leftJoin(externalSyncs, eq(shifts.externalSyncId, externalSyncs.id));
if (date) {
const targetDate = new Date(date);
@@ -54,8 +54,8 @@ export async function GET(request: Request) {
eq(shifts.calendarId, calendarId),
gte(shifts.date, startOfDay),
lte(shifts.date, endOfDay),
- // Exclude shifts from hidden iCloud syncs (or shifts that are not synced)
- or(isNull(shifts.icloudSyncId), eq(icloudSyncs.isHidden, false))
+ // Exclude shifts from hidden external syncs (or shifts that are not synced)
+ or(isNull(shifts.externalSyncId), eq(externalSyncs.isHidden, false))
)
);
return NextResponse.json(result);
@@ -64,8 +64,8 @@ export async function GET(request: Request) {
const result = await query.where(
and(
eq(shifts.calendarId, calendarId),
- // Exclude shifts from hidden iCloud syncs (or shifts that are not synced)
- or(isNull(shifts.icloudSyncId), eq(icloudSyncs.isHidden, false))
+ // Exclude shifts from hidden external syncs (or shifts that are not synced)
+ or(isNull(shifts.externalSyncId), eq(externalSyncs.isHidden, false))
)
);
return NextResponse.json(result);
diff --git a/app/api/shifts/stats/route.ts b/app/api/shifts/stats/route.ts
index 251c266..762fea8 100644
--- a/app/api/shifts/stats/route.ts
+++ b/app/api/shifts/stats/route.ts
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { shifts, icloudSyncs, shiftPresets } from "@/lib/db/schema";
+import { shifts, externalSyncs, shiftPresets } from "@/lib/db/schema";
import { eq, and, gte, lte, sql, or, isNull } from "drizzle-orm";
import {
startOfWeek,
@@ -55,7 +55,7 @@ export async function GET(request: Request) {
count: sql<number>`count(*)`.as("count"),
})
.from(shifts)
- .leftJoin(icloudSyncs, eq(shifts.icloudSyncId, icloudSyncs.id))
+ .leftJoin(externalSyncs, eq(shifts.externalSyncId, externalSyncs.id))
.leftJoin(shiftPresets, eq(shifts.presetId, shiftPresets.id))
.where(
and(
@@ -64,10 +64,10 @@ export async function GET(request: Request) {
lte(shifts.date, endDate),
// Exclude shifts from iCloud syncs that are hidden or hidden from stats
or(
- isNull(shifts.icloudSyncId),
+ isNull(shifts.externalSyncId),
and(
- eq(icloudSyncs.isHidden, false),
- eq(icloudSyncs.hideFromStats, false)
+ eq(externalSyncs.isHidden, false),
+ eq(externalSyncs.hideFromStats, false)
)
),
// Exclude shifts from presets that are hidden from stats
diff --git a/app/page.tsx b/app/page.tsx
index 691d99c..39252ea 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -9,7 +9,7 @@ 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 { ExternalSyncManageDialog } from "@/components/external-sync-manage-dialog";
import { DayShiftsDialog } from "@/components/day-shifts-dialog";
import { SyncedShiftsDialog } from "@/components/synced-shifts-dialog";
import { LanguageSwitcher } from "@/components/language-switcher";
@@ -41,7 +41,7 @@ import {
endOfWeek,
} from "date-fns";
import { de, enUS } from "date-fns/locale";
-import { CalendarNote, ShiftPreset, ICloudSync } from "@/lib/db/schema";
+import { CalendarNote, ExternalSync } from "@/lib/db/schema";
import { ShiftWithCalendar } from "@/lib/types";
import { formatDateToLocal } from "@/lib/date-utils";
import {
@@ -96,32 +96,32 @@ function HomeContent() {
refetchNotes,
} = useNotes(selectedCalendar);
- // iCloud Syncs state
- const [icloudSyncs, setIcloudSyncs] = useState<ICloudSync[]>([]);
+ // External Calendar Syncs state
+ const [externalSyncs, setExternalSyncs] = useState<ExternalSync[]>([]);
- // Fetch iCloud syncs for the calendar
- const fetchICloudSyncs = useCallback(async () => {
+ // Fetch external syncs for the calendar
+ const fetchExternalSyncs = useCallback(async () => {
if (!selectedCalendar) {
- setIcloudSyncs([]);
+ setExternalSyncs([]);
return;
}
try {
const response = await fetch(
- `/api/icloud-syncs?calendarId=${selectedCalendar}`
+ `/api/external-syncs?calendarId=${selectedCalendar}`
);
if (response.ok) {
const data = await response.json();
- setIcloudSyncs(data);
+ setExternalSyncs(data);
}
} catch (error) {
- console.error("Failed to fetch iCloud syncs:", error);
+ console.error("Failed to fetch external syncs:", error);
}
}, [selectedCalendar]);
useEffect(() => {
- fetchICloudSyncs();
- }, [fetchICloudSyncs]);
+ fetchExternalSyncs();
+ }, [fetchExternalSyncs]);
// Local state
const [selectedPresetId, setSelectedPresetId] = useState<
@@ -139,7 +139,7 @@ function HomeContent() {
const [showNoteDialog, setShowNoteDialog] = useState(false);
const [showDeleteCalendarDialog, setShowDeleteCalendarDialog] =
useState(false);
- const [showICloudSyncDialog, setShowICloudSyncDialog] = useState(false);
+ const [showExternalSyncDialog, setShowExternalSyncDialog] = useState(false);
const [showDayShiftsDialog, setShowDayShiftsDialog] = useState(false);
const [showSyncedShiftsDialog, setShowSyncedShiftsDialog] = useState(false);
const [selectedDayDate, setSelectedDayDate] = useState<Date | null>(null);
@@ -257,7 +257,7 @@ function HomeContent() {
setShowDeleteCalendarDialog(true);
};
- const handleICloudSyncClick = async () => {
+ const handleExternalSyncClick = async () => {
if (!selectedCalendar) return;
const calendar = calendars.find((c) => c.id === selectedCalendar);
@@ -275,7 +275,7 @@ function HomeContent() {
);
if (result.valid) {
- setShowICloudSyncDialog(true);
+ setShowExternalSyncDialog(true);
return;
}
}
@@ -284,13 +284,13 @@ function HomeContent() {
setPendingAction({
type: "edit",
presetAction: async () => {
- setShowICloudSyncDialog(true);
+ setShowExternalSyncDialog(true);
},
});
setShowPasswordDialog(true);
} else {
// No password protection
- setShowICloudSyncDialog(true);
+ setShowExternalSyncDialog(true);
}
};
@@ -737,7 +737,7 @@ function HomeContent() {
onCreateCalendar={() => setShowCalendarDialog(true)}
onManagePassword={() => setShowManagePasswordDialog(true)}
onDeleteCalendar={initiateDeleteCalendar}
- onICloudSync={handleICloudSyncClick}
+ onExternalSync={handleExternalSyncClick}
onPresetsChange={refetchPresets}
onShiftsChange={refetchShifts}
onStatsRefresh={() => setStatsRefreshTrigger((prev) => prev + 1)}
@@ -882,7 +882,7 @@ function HomeContent() {
notes={notes}
selectedPresetId={selectedPresetId}
togglingDates={togglingDates}
- icloudSyncs={icloudSyncs}
+ externalSyncs={externalSyncs}
onDayClick={handleDayClick}
onDayRightClick={handleDayRightClick}
onNoteIconClick={handleNoteIconClick}
@@ -1021,16 +1021,16 @@ function HomeContent() {
/>
)}
{selectedCalendar && (
- <ICloudSyncManageDialog
- open={showICloudSyncDialog}
- onOpenChange={setShowICloudSyncDialog}
+ <ExternalSyncManageDialog
+ open={showExternalSyncDialog}
+ onOpenChange={setShowExternalSyncDialog}
calendarId={selectedCalendar}
onSyncComplete={() => {
refetchShifts();
refetchCalendars();
setStatsRefreshTrigger((prev) => prev + 1);
- // Refetch iCloud syncs to get updated displayMode
- fetchICloudSyncs();
+ // Refetch external syncs to get updated displayMode
+ fetchExternalSyncs();
}}
/>
)}
diff --git a/components/app-header.tsx b/components/app-header.tsx
index 444c900..e148ca4 100644
--- a/components/app-header.tsx
+++ b/components/app-header.tsx
@@ -26,7 +26,7 @@ interface AppHeaderProps {
onCreateCalendar: () => void;
onManagePassword: () => void;
onDeleteCalendar: (id: string) => void;
- onICloudSync: () => void;
+ onExternalSync: () => void;
onPresetsChange: () => void;
onShiftsChange: () => void;
onStatsRefresh: () => void;
@@ -48,7 +48,7 @@ export function AppHeader({
onCreateCalendar,
onManagePassword,
onDeleteCalendar,
- onICloudSync,
+ onExternalSync,
onPresetsChange,
onShiftsChange,
onStatsRefresh,
@@ -128,7 +128,7 @@ export function AppHeader({
onCreateNew={onCreateCalendar}
onManagePassword={onManagePassword}
onDelete={onDeleteCalendar}
- onICloudSync={onICloudSync}
+ onExternalSync={onExternalSync}
/>
</div>
</motion.div>
@@ -261,9 +261,9 @@ export function AppHeader({
onManagePassword();
}}
onDelete={onDeleteCalendar}
- onICloudSync={() => {
+ onExternalSync={() => {
onMobileCalendarDialogChange(false);
- onICloudSync();
+ onExternalSync();
}}
/>
</div>
diff --git a/components/calendar-grid.tsx b/components/calendar-grid.tsx
index 1b2f928..31248b9 100644
--- a/components/calendar-grid.tsx
+++ b/components/calendar-grid.tsx
@@ -1,7 +1,7 @@
import { motion } from "motion/react";
import { StickyNote, RefreshCw } from "lucide-react";
import { ShiftWithCalendar } from "@/lib/types";
-import { CalendarNote, ICloudSync } from "@/lib/db/schema";
+import { CalendarNote, ExternalSync } from "@/lib/db/schema";
import { isToday } from "date-fns";
import { useTranslations } from "next-intl";
import { useRef, useEffect } from "react";
@@ -14,7 +14,7 @@ interface CalendarGridProps {
notes: CalendarNote[];
selectedPresetId: string | undefined;
togglingDates: Set<string>;
- icloudSyncs: ICloudSync[];
+ externalSyncs: ExternalSync[];
onDayClick: (date: Date) => void;
onDayRightClick: (e: React.MouseEvent, date: Date) => void;
onNoteIconClick: (e: React.MouseEvent, date: Date) => void;
@@ -30,7 +30,7 @@ export function CalendarGrid({
notes,
selectedPresetId,
togglingDates,
- icloudSyncs,
+ externalSyncs,
onDayClick,
onDayRightClick,
onNoteIconClick,
@@ -177,27 +177,27 @@ export function CalendarGrid({
} = {};
dayShifts.forEach((shift) => {
- if (shift.syncedFromIcloud && shift.icloudSyncId) {
- const sync = icloudSyncs.find(
- (s) => s.id === shift.icloudSyncId
+ if (shift.syncedFromExternal && shift.externalSyncId) {
+ const sync = externalSyncs.find(
+ (s) => s.id === shift.externalSyncId
);
const displayMode = sync?.displayMode || "normal";
if (displayMode === "minimal") {
- if (!syncedShiftsByMode[shift.icloudSyncId]) {
- syncedShiftsByMode[shift.icloudSyncId] = [];
+ if (!syncedShiftsByMode[shift.externalSyncId]) {
+ syncedShiftsByMode[shift.externalSyncId] = [];
}
- syncedShiftsByMode[shift.icloudSyncId].push(shift);
+ syncedShiftsByMode[shift.externalSyncId].push(shift);
}
}
});
// Get shifts to display normally (regular + synced with normal mode)
const normalDisplayShifts = dayShifts.filter((s) => {
- if (!s.syncedFromIcloud) return true;
- if (!s.icloudSyncId) return true;
- const sync = icloudSyncs.find(
- (sync) => sync.id === s.icloudSyncId
+ if (!s.syncedFromExternal) return true;
+ if (!s.externalSyncId) return true;
+ const sync = externalSyncs.find(
+ (sync) => sync.id === s.externalSyncId
);
return !sync || sync.displayMode === "normal";
});
@@ -263,7 +263,7 @@ export function CalendarGrid({
{/* Show minimal badges for each sync with minimal display mode */}
{Object.entries(syncedShiftsByMode).map(
([syncId, syncShifts]) => {
- const sync = icloudSyncs.find((s) => s.id === syncId);
+ const sync = externalSyncs.find((s) => s.id === syncId);
if (!sync || syncShifts.length === 0) return null;
return (
diff --git a/components/calendar-selector.tsx b/components/calendar-selector.tsx
index 48bd6ba..9dbf315 100644
--- a/components/calendar-selector.tsx
+++ b/components/calendar-selector.tsx
@@ -19,7 +19,7 @@ interface CalendarSelectorProps {
onCreateNew: () => void;
onManagePassword?: () => void;
onDelete?: (id: string) => void;
- onICloudSync?: () => void;
+ onExternalSync?: () => void;
}
export function CalendarSelector({
@@ -29,7 +29,7 @@ export function CalendarSelector({
onCreateNew,
onManagePassword,
onDelete,
- onICloudSync,
+ onExternalSync,
}: CalendarSelectorProps) {
const t = useTranslations();
@@ -64,13 +64,13 @@ export function CalendarSelector({
<KeyRound className="h-4 w-4" />
</Button>
)}
- {onICloudSync && selectedId && (
+ {onExternalSync && selectedId && (
<Button
- onClick={onICloudSync}
+ onClick={onExternalSync}
size="icon"
variant="outline"
className="h-9 w-9 sm:h-10 sm:w-10"
- title={t("icloud.manageTitle")}
+ title={t("externalSync.manageTitle")}
>
<Cloud className="h-4 w-4" />
</Button>
diff --git a/components/day-shifts-dialog.tsx b/components/day-shifts-dialog.tsx
index 6864a09..7df59f8 100644
--- a/components/day-shifts-dialog.tsx
+++ b/components/day-shifts-dialog.tsx
@@ -83,7 +83,7 @@ export function DayShiftsDialog({
</p>
)}
</div>
- {onDeleteShift && !shift.icloudSyncId && (
+ {onDeleteShift && !shift.externalSyncId && (
<Button
size="icon"
variant="ghost"
diff --git a/components/icloud-sync-manage-dialog.tsx b/components/external-sync-manage-dialog.tsx
similarity index 67%
rename from components/icloud-sync-manage-dialog.tsx
rename to components/external-sync-manage-dialog.tsx
index 86ddbfb..c508d47 100644
--- a/components/icloud-sync-manage-dialog.tsx
+++ b/components/external-sync-manage-dialog.tsx
@@ -22,36 +22,40 @@ import {
import { ColorPicker } from "@/components/ui/color-picker";
import { Slider } from "@/components/ui/slider";
import { useTranslations } from "next-intl";
-import { ICloudSync } from "@/lib/db/schema";
+import { ExternalSync } 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";
+import {
+ isValidCalendarUrl,
+ type CalendarSyncType,
+} from "@/lib/external-calendar-utils";
-interface ICloudSyncManageDialogProps {
+interface ExternalSyncManageDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
calendarId: string | null;
onSyncComplete?: () => void;
}
-export function ICloudSyncManageDialog({
+export function ExternalSyncManageDialog({
open,
onOpenChange,
calendarId,
onSyncComplete,
-}: ICloudSyncManageDialogProps) {
+}: ExternalSyncManageDialogProps) {
const t = useTranslations();
- const [syncs, setSyncs] = useState<ICloudSync[]>([]);
+ const [syncs, setSyncs] = useState<ExternalSync[]>([]);
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);
+ const [editingSync, setEditingSync] = useState<ExternalSync | null>(null);
// Form state
const [formName, setFormName] = useState("");
const [formUrl, setFormUrl] = useState("");
+ const [formSyncType, setFormSyncType] = useState("icloud");
const [formColor, setFormColor] = useState("#3b82f6");
const [formDisplayMode, setFormDisplayMode] = useState("normal");
const [formAutoSyncInterval, setFormAutoSyncInterval] = useState(0);
@@ -62,7 +66,7 @@ export function ICloudSyncManageDialog({
setIsLoading(true);
try {
const response = await fetch(
- `/api/icloud-syncs?calendarId=${calendarId}`
+ `/api/external-syncs?calendarId=${calendarId}`
);
if (response.ok) {
const data = await response.json();
@@ -89,6 +93,7 @@ export function ICloudSyncManageDialog({
setEditingSync(null);
setFormName("");
setFormUrl("");
+ setFormSyncType("icloud");
setFormColor("#3b82f6");
setFormDisplayMode("normal");
setFormAutoSyncInterval(0);
@@ -98,32 +103,33 @@ export function ICloudSyncManageDialog({
const handleAddSync = async () => {
if (!calendarId || !formName.trim() || !formUrl.trim()) return;
- // Validate iCloud URL format
- if (!isValidICloudUrl(formUrl.trim())) {
- toast.error(t("icloud.invalidUrlFormat"));
+ // Validate calendar URL format
+ if (!isValidCalendarUrl(formUrl.trim(), formSyncType as CalendarSyncType)) {
+ toast.error(t("externalSync.invalidUrlFormat"));
return;
}
// Check if URL already exists
const normalizedUrl = formUrl.trim().toLowerCase();
const urlExists = syncs.some(
- (sync) => sync.icloudUrl.toLowerCase() === normalizedUrl
+ (sync) => sync.calendarUrl.toLowerCase() === normalizedUrl
);
if (urlExists) {
- toast.error(t("icloud.urlAlreadyExists"));
+ toast.error(t("externalSync.urlAlreadyExists"));
return;
}
setIsLoading(true);
try {
- const response = await fetch("/api/icloud-syncs", {
+ const response = await fetch("/api/external-syncs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
calendarId,
name: formName.trim(),
- icloudUrl: formUrl.trim(),
+ calendarUrl: formUrl.trim(),
+ syncType: formSyncType,
color: formColor,
displayMode: formDisplayMode,
autoSyncInterval: formAutoSyncInterval,
@@ -134,22 +140,23 @@ export function ICloudSyncManageDialog({
const newSync = await response.json();
setFormName("");
setFormUrl("");
+ setFormSyncType("icloud");
setFormColor("#3b82f6");
setFormDisplayMode("normal");
setFormAutoSyncInterval(0);
setShowAddForm(false);
await fetchSyncs();
onSyncComplete?.(); // Trigger refresh to update parent state
- toast.success(t("icloud.createSuccess"));
+ toast.success(t("externalSync.createSuccess"));
// Auto-sync the newly created sync
await handleSync(newSync.id);
} else {
const data = await response.json();
- toast.error(data.error || t("icloud.createError"));
+ toast.error(data.error || t("externalSync.createError"));
}
} catch (error) {
console.error("Failed to create sync:", error);
- toast.error(t("icloud.createError"));
+ toast.error(t("externalSync.createError"));
} finally {
setIsLoading(false);
}
@@ -160,7 +167,7 @@ export function ICloudSyncManageDialog({
setIsLoading(true);
try {
- const response = await fetch(`/api/icloud-syncs/${editingSync.id}`, {
+ const response = await fetch(`/api/external-syncs/${editingSync.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -176,19 +183,20 @@ export function ICloudSyncManageDialog({
setEditingSync(null);
setFormName("");
setFormUrl("");
+ setFormSyncType("icloud");
setFormColor("#3b82f6");
setFormDisplayMode("normal");
setFormAutoSyncInterval(0);
await fetchSyncs();
- onSyncComplete?.(); // Trigger refresh of shifts and iCloudSyncs
- toast.success(t("icloud.updateSuccess"));
+ onSyncComplete?.(); // Trigger refresh of shifts and externalSyncs
+ toast.success(t("externalSync.updateSuccess"));
} else {
const data = await response.json();
- toast.error(data.error || t("icloud.updateError"));
+ toast.error(data.error || t("externalSync.updateError"));
}
} catch (error) {
console.error("Failed to update sync:", error);
- toast.error(t("icloud.updateError"));
+ toast.error(t("externalSync.updateError"));
} finally {
setIsLoading(false);
}
@@ -197,7 +205,7 @@ export function ICloudSyncManageDialog({
const handleSync = async (syncId: string) => {
setIsSyncing(syncId);
try {
- const response = await fetch(`/api/icloud-syncs/${syncId}/sync`, {
+ const response = await fetch(`/api/external-syncs/${syncId}/sync`, {
method: "POST",
});
@@ -213,16 +221,16 @@ export function ICloudSyncManageDialog({
// 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"
- )}`
+ `${t("externalSync.syncSuccess")}: ${stats.created} ${t(
+ "externalSync.statsCreated"
+ )}, ${stats.updated} ${t("externalSync.statsUpdated")}, ${
+ stats.deleted
+ } ${t("externalSync.statsDeleted")}`
);
} catch (error) {
console.error("Sync error:", error);
toast.error(
- error instanceof Error ? error.message : t("icloud.syncError")
+ error instanceof Error ? error.message : t("externalSync.syncError")
);
} finally {
setIsSyncing(null);
@@ -230,34 +238,34 @@ export function ICloudSyncManageDialog({
};
const handleDelete = async (syncId: string) => {
- if (!confirm(t("icloud.deleteConfirm"))) return;
+ if (!confirm(t("externalSync.deleteConfirm"))) return;
setIsDeleting(syncId);
try {
- const response = await fetch(`/api/icloud-syncs/${syncId}`, {
+ const response = await fetch(`/api/external-syncs/${syncId}`, {
method: "DELETE",
});
if (response.ok) {
await fetchSyncs();
onSyncComplete?.();
- toast.success(t("icloud.deleteSuccess"));
+ toast.success(t("externalSync.deleteSuccess"));
} else {
const data = await response.json();
- toast.error(data.error || t("icloud.deleteError"));
+ toast.error(data.error || t("externalSync.deleteError"));
}
} catch (error) {
console.error("Delete error:", error);
- toast.error(t("icloud.deleteError"));
+ toast.error(t("externalSync.deleteError"));
} finally {
setIsDeleting(null);
}
};
- const startEdit = (sync: ICloudSync) => {
+ const startEdit = (sync: ExternalSync) => {
setEditingSync(sync);
setFormName(sync.name);
- setFormUrl(sync.icloudUrl);
+ setFormUrl(sync.calendarUrl);
setFormColor(sync.color);
setFormDisplayMode(sync.displayMode || "normal");
setFormAutoSyncInterval(sync.autoSyncInterval || 0);
@@ -268,6 +276,7 @@ export function ICloudSyncManageDialog({
setEditingSync(null);
setFormName("");
setFormUrl("");
+ setFormSyncType("icloud");
setFormColor("#3b82f6");
setFormDisplayMode("normal");
setFormAutoSyncInterval(0);
@@ -287,7 +296,7 @@ export function ICloudSyncManageDialog({
}
try {
- const response = await fetch(`/api/icloud-syncs/${syncId}`, {
+ const response = await fetch(`/api/external-syncs/${syncId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -298,10 +307,10 @@ export function ICloudSyncManageDialog({
if (response.ok) {
await fetchSyncs();
onSyncComplete?.(); // Trigger refresh
- toast.success(t("icloud.updateSuccess"));
+ toast.success(t("externalSync.updateSuccess"));
} else {
const data = await response.json();
- toast.error(data.error || t("icloud.updateError"));
+ toast.error(data.error || t("externalSync.updateError"));
// Revert optimistic update on error
if (editingSync && editingSync.id === syncId) {
@@ -313,7 +322,7 @@ export function ICloudSyncManageDialog({
}
} catch (error) {
console.error("Failed to update visibility:", error);
- toast.error(t("icloud.updateError"));
+ toast.error(t("externalSync.updateError"));
// Revert optimistic update on error
if (editingSync && editingSync.id === syncId) {
@@ -330,20 +339,36 @@ export function ICloudSyncManageDialog({
setEditingSync(null);
setFormName("");
setFormUrl("");
+ setFormSyncType("icloud");
setFormColor("#3b82f6");
setFormDisplayMode("normal");
setFormAutoSyncInterval(0);
};
+ // Get URL placeholder and hint based on sync type
+ const getUrlPlaceholder = () => {
+ if (formSyncType === "google") {
+ return t("externalSync.urlPlaceholderGoogle");
+ }
+ return t("externalSync.urlPlaceholderICloud");
+ };
+
+ const getUrlHint = () => {
+ if (formSyncType === "google") {
+ return t("externalSync.urlHintGoogle");
+ }
+ return t("externalSync.urlHintICloud");
+ };
+
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")}
+ {t("externalSync.manageTitle")}
</DialogTitle>
<DialogDescription className="text-sm text-muted-foreground">
- {t("icloud.manageDescription")}
+ {t("externalSync.manageDescription")}
</DialogDescription>
</DialogHeader>
@@ -357,34 +382,44 @@ export function ICloudSyncManageDialog({
className="flex flex-col gap-3 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 items-center justify-between">
- <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>
- {sync.autoSyncInterval > 0 ? (
- <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-primary/10 text-primary text-xs font-medium">
- <RefreshCw className="h-3 w-3" />
- {sync.autoSyncInterval < 60
- ? `${sync.autoSyncInterval} min`
- : sync.autoSyncInterval < 1440
- ? `${sync.autoSyncInterval / 60} h`
- : `${sync.autoSyncInterval / 1440} d`}
- </span>
- ) : (
- <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-muted/50 text-muted-foreground text-xs font-medium">
- {t("icloud.autoSyncManual")}
- </span>
- )}
- </div>
+ {/* Title row - always full width on mobile */}
+ <div className="flex items-start gap-2">
+ <div
+ className="w-1 h-4 rounded-full shrink-0 mt-0.5"
+ style={{ backgroundColor: sync.color }}
+ />
+ <span className="font-semibold flex-1 min-w-0 break-words">
+ {sync.name}
+ </span>
+ </div>
+
+ {/* Badges and buttons row */}
+ <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:justify-between">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-xs px-2 py-0.5 rounded-full bg-muted border border-border/50 font-normal">
+ {sync.syncType === "google"
+ ? t("externalSync.syncTypeGoogle")
+ : t("externalSync.syncTypeICloud")}
+ </span>
+ {sync.autoSyncInterval > 0 ? (
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-primary/10 text-primary text-xs font-medium">
+ <RefreshCw className="h-3 w-3" />
+ {sync.autoSyncInterval < 60
+ ? `${sync.autoSyncInterval} min`
+ : sync.autoSyncInterval < 1440
+ ? `${sync.autoSyncInterval / 60} h`
+ : `${sync.autoSyncInterval / 1440} d`}
+ </span>
+ ) : (
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-muted/50 text-muted-foreground text-xs font-medium">
+ {t("externalSync.autoSyncManual")}
+ </span>
+ )}
{sync.lastSyncedAt && (
- <p className="text-xs text-muted-foreground mt-1">
- {t("icloud.lastSynced")}:{" "}
+ <span className="text-xs text-muted-foreground">
+ {t("externalSync.lastSynced")}:{" "}
{new Date(sync.lastSyncedAt).toLocaleString()}
- </p>
+ </span>
)}
</div>
<div className="flex gap-1 shrink-0">
@@ -434,34 +469,57 @@ export function ICloudSyncManageDialog({
{(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")}
+ {editingSync
+ ? t("externalSync.editSync")
+ : t("externalSync.addSync")}
</h3>
<div className="space-y-2">
- <Label htmlFor="sync-name">{t("icloud.nameLabel")}</Label>
+ <Label htmlFor="sync-name">{t("externalSync.nameLabel")}</Label>
<Input
id="sync-name"
type="text"
- placeholder={t("icloud.namePlaceholder")}
+ placeholder={t("externalSync.namePlaceholder")}
value={formName}
onChange={(e) => setFormName(e.target.value)}
disabled={isLoading}
/>
</div>
+ {!editingSync && (
+ <div className="space-y-2">
+ <Label htmlFor="sync-type">
+ {t("externalSync.syncTypeLabel")}
+ </Label>
+ <Select value={formSyncType} onValueChange={setFormSyncType}>
+ <SelectTrigger id="sync-type" className="bg-background/50">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="icloud">
+ {t("externalSync.syncTypeICloud")}
+ </SelectItem>
+ <SelectItem value="google">
+ {t("externalSync.syncTypeGoogle")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ )}
+
<div className="space-y-2">
- <Label htmlFor="sync-url">{t("icloud.urlLabel")}</Label>
+ <Label htmlFor="sync-url">{t("externalSync.urlLabel")}</Label>
<Input
id="sync-url"
type="text"
- placeholder={t("icloud.urlPlaceholder")}
+ placeholder={getUrlPlaceholder()}
value={formUrl}
onChange={(e) => setFormUrl(e.target.value)}
disabled={isLoading || !!editingSync}
/>
{!editingSync && (
<p className="text-xs text-muted-foreground">
- {t("icloud.urlHint")}
+ {getUrlHint()}
</p>
)}
</div>
@@ -470,17 +528,17 @@ export function ICloudSyncManageDialog({
<ColorPicker
color={formColor}
onChange={setFormColor}
- label={t("icloud.colorLabel")}
+ label={t("externalSync.colorLabel")}
presetColors={PRESET_COLORS}
/>
<p className="text-xs text-muted-foreground">
- {t("icloud.colorHint")}
+ {t("externalSync.colorHint")}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="sync-display-mode">
- {t("icloud.displayMode")}
+ {t("externalSync.displayMode")}
</Label>
<Select
value={formDisplayMode}
@@ -494,24 +552,24 @@ export function ICloudSyncManageDialog({
</SelectTrigger>
<SelectContent>
<SelectItem value="normal">
- {t("icloud.displayModeNormal")}
+ {t("externalSync.displayModeNormal")}
</SelectItem>
<SelectItem value="minimal">
- {t("icloud.displayModeMinimal")}
+ {t("externalSync.displayModeMinimal")}
</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
- {t("icloud.displayModeHint")}
+ {t("externalSync.displayModeHint")}
</p>
</div>
<div className="space-y-3">
<div className="flex items-center justify-between">
- <Label>{t("icloud.autoSyncLabel")}</Label>
+ <Label>{t("externalSync.autoSyncLabel")}</Label>
<span className="text-sm font-medium text-primary">
{formAutoSyncInterval === 0
- ? t("icloud.autoSyncManual")
+ ? t("externalSync.autoSyncManual")
: formAutoSyncInterval < 60
? `${formAutoSyncInterval} min`
: formAutoSyncInterval < 1440
@@ -536,11 +594,11 @@ export function ICloudSyncManageDialog({
className="w-full"
/>
<div className="flex justify-between text-xs text-muted-foreground">
- <span>{t("icloud.autoSyncManual")}</span>
- <span>{t("icloud.autoSync24hShort")}</span>
+ <span>{t("externalSync.autoSyncManual")}</span>
+ <span>{t("externalSync.autoSync24hShort")}</span>
</div>
<p className="text-xs text-muted-foreground">
- {t("icloud.autoSyncHint")}
+ {t("externalSync.autoSyncHint")}
</p>
</div>
@@ -562,11 +620,11 @@ export function ICloudSyncManageDialog({
htmlFor="hide-calendar"
className="text-sm font-normal cursor-pointer"
>
- {t("icloud.hideCalendar")}
+ {t("externalSync.hideCalendar")}
</Label>
</div>
<p className="text-xs text-muted-foreground pl-6">
- {t("icloud.hideCalendarHint")}
+ {t("externalSync.hideCalendarHint")}
</p>
<div className="flex items-center gap-2">
@@ -594,11 +652,11 @@ export function ICloudSyncManageDialog({
: "cursor-pointer"
}`}
>
- {t("icloud.hideFromStats")}
+ {t("externalSync.hideFromStats")}
</Label>
</div>
<p className="text-xs text-muted-foreground pl-6">
- {t("icloud.hideFromStatsHint")}
+ {t("externalSync.hideFromStatsHint")}
</p>
</div>
)}
@@ -613,6 +671,7 @@ export function ICloudSyncManageDialog({
setShowAddForm(false);
setFormName("");
setFormUrl("");
+ setFormSyncType("icloud");
setFormColor("#3b82f6");
setFormDisplayMode("normal");
setFormAutoSyncInterval(0);
@@ -633,7 +692,7 @@ export function ICloudSyncManageDialog({
{isLoading ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
- {editingSync ? t("common.save") : t("icloud.addSync")}
+ {editingSync ? t("common.save") : t("externalSync.addSync")}
</Button>
</div>
</div>
@@ -647,19 +706,49 @@ export function ICloudSyncManageDialog({
disabled={!!isSyncing || !!isDeleting}
>
<Plus className="mr-2 h-4 w-4" />
- {t("icloud.addNewSync")}
+ {t("externalSync.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>
+ <div className="font-medium">
+ {t(
+ formSyncType === "google"
+ ? "externalSync.howToTitleGoogle"
+ : "externalSync.howToTitleICloud"
+ )}
+ </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>
+ <li>
+ {t(
+ formSyncType === "google"
+ ? "externalSync.howToStep1Google"
+ : "externalSync.howToStep1ICloud"
+ )}
+ </li>
+ <li>
+ {t(
+ formSyncType === "google"
+ ? "externalSync.howToStep2Google"
+ : "externalSync.howToStep2ICloud"
+ )}
+ </li>
+ <li>
+ {t(
+ formSyncType === "google"
+ ? "externalSync.howToStep3Google"
+ : "externalSync.howToStep3ICloud"
+ )}
+ </li>
+ <li>
+ {t(
+ formSyncType === "google"
+ ? "externalSync.howToStep4Google"
+ : "externalSync.howToStep4ICloud"
+ )}
+ </li>
</ol>
</div>
</div>
diff --git a/components/shift-card.tsx b/components/shift-card.tsx
index c0c09c3..ea92dd4 100644
--- a/components/shift-card.tsx
+++ b/components/shift-card.tsx
@@ -49,7 +49,7 @@ export function ShiftCard({ shift, onDelete }: ShiftCardProps) {
</p>
)}
</div>
- {!shift.icloudSyncId && (
+ {!shift.externalSyncId && (
<Button
variant="ghost"
size="icon"
diff --git a/components/synced-shifts-dialog.tsx b/components/synced-shifts-dialog.tsx
index 1153e18..8e3d61f 100644
--- a/components/synced-shifts-dialog.tsx
+++ b/components/synced-shifts-dialog.tsx
@@ -40,10 +40,10 @@ export function SyncedShiftsDialog({
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>
- {t("icloud.syncedShiftsTitle", { date: formattedDate })}
+ {t("externalSync.syncedShiftsTitle", { date: formattedDate })}
</DialogTitle>
<DialogDescription className="sr-only">
- {t("icloud.viewSyncedShifts")}
+ {t("externalSync.viewSyncedShifts")}
</DialogDescription>
</DialogHeader>
<div className="space-y-3 max-h-[60vh] overflow-y-auto">
diff --git a/drizzle/0008_big_reavers.sql b/drizzle/0008_big_reavers.sql
new file mode 100644
index 0000000..0dc6c55
--- /dev/null
+++ b/drizzle/0008_big_reavers.sql
@@ -0,0 +1,49 @@
+PRAGMA foreign_keys=OFF;--> statement-breakpoint
+ALTER TABLE `icloud_syncs` RENAME TO `external_syncs`;--> statement-breakpoint
+ALTER TABLE `external_syncs` RENAME COLUMN "icloud_url" TO "calendar_url";--> statement-breakpoint
+CREATE TABLE `__new_external_syncs` (
+ `id` text PRIMARY KEY NOT NULL,
+ `calendar_id` text NOT NULL,
+ `name` text NOT NULL,
+ `sync_type` text DEFAULT 'icloud' NOT NULL,
+ `calendar_url` text NOT NULL,
+ `color` text DEFAULT '#3b82f6' NOT NULL,
+ `display_mode` text DEFAULT 'normal' NOT NULL,
+ `is_hidden` integer DEFAULT false NOT NULL,
+ `hide_from_stats` integer DEFAULT false NOT NULL,
+ `auto_sync_interval` integer DEFAULT 0 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
+INSERT INTO `__new_external_syncs`("id", "calendar_id", "name", "sync_type", "calendar_url", "color", "display_mode", "is_hidden", "hide_from_stats", "auto_sync_interval", "last_synced_at", "created_at", "updated_at") SELECT "id", "calendar_id", "name", 'icloud', "calendar_url", "color", "display_mode", "is_hidden", "hide_from_stats", "auto_sync_interval", "last_synced_at", "created_at", "updated_at" FROM `external_syncs`;--> statement-breakpoint
+DROP TABLE `external_syncs`;--> statement-breakpoint
+ALTER TABLE `__new_external_syncs` RENAME TO `external_syncs`;--> statement-breakpoint
+CREATE TABLE `__new_shifts` (
+ `id` text PRIMARY KEY NOT NULL,
+ `calendar_id` text NOT NULL,
+ `preset_id` text,
+ `date` integer NOT NULL,
+ `start_time` text NOT NULL,
+ `end_time` text NOT NULL,
+ `title` text NOT NULL,
+ `color` text DEFAULT '#3b82f6' NOT NULL,
+ `notes` text,
+ `is_all_day` integer DEFAULT false NOT NULL,
+ `is_secondary` integer DEFAULT false NOT NULL,
+ `external_event_id` text,
+ `external_sync_id` text,
+ `synced_from_external` integer DEFAULT false 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,
+ FOREIGN KEY (`preset_id`) REFERENCES `shift_presets`(`id`) ON UPDATE no action ON DELETE set null,
+ FOREIGN KEY (`external_sync_id`) REFERENCES `external_syncs`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+INSERT INTO `__new_shifts`("id", "calendar_id", "preset_id", "date", "start_time", "end_time", "title", "color", "notes", "is_all_day", "is_secondary", "external_event_id", "external_sync_id", "synced_from_external", "created_at", "updated_at") SELECT "id", "calendar_id", "preset_id", "date", "start_time", "end_time", "title", "color", "notes", "is_all_day", "is_secondary", "icloud_event_id", "icloud_sync_id", "synced_from_icloud", "created_at", "updated_at" FROM `shifts`;--> statement-breakpoint
+DROP TABLE `shifts`;--> statement-breakpoint
+ALTER TABLE `__new_shifts` RENAME TO `shifts`;--> statement-breakpoint
+PRAGMA foreign_keys=ON;
\ No newline at end of file
diff --git a/drizzle/meta/0008_snapshot.json b/drizzle/meta/0008_snapshot.json
new file mode 100644
index 0000000..73c557b
--- /dev/null
+++ b/drizzle/meta/0008_snapshot.json
@@ -0,0 +1,561 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "bcf5231c-497a-43be-b87a-51cdf54d82c7",
+ "prevId": "a698f740-4747-466e-ab6a-79cb5de013a7",
+ "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
+ },
+ "is_locked": {
+ "name": "is_locked",
+ "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": {},
+ "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
+ },
+ "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": {}
+ },
+ "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
+ },
+ "hide_from_stats": {
+ "name": "hide_from_stats",
+ "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
+ },
+ "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": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {
+ "\"icloud_syncs\"": "\"external_syncs\""
+ },
+ "columns": {
+ "\"external_syncs\".\"icloud_url\"": "\"external_syncs\".\"calendar_url\"",
+ "\"shifts\".\"icloud_event_id\"": "\"shifts\".\"external_event_id\"",
+ "\"shifts\".\"icloud_sync_id\"": "\"shifts\".\"external_sync_id\"",
+ "\"shifts\".\"synced_from_icloud\"": "\"shifts\".\"synced_from_external\""
+ }
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index cef15e0..35ee4bf 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -57,6 +57,13 @@
"when": 1764876813553,
"tag": "0007_flippant_betty_brant",
"breakpoints": true
+ },
+ {
+ "idx": 8,
+ "version": "6",
+ "when": 1764883523241,
+ "tag": "0008_big_reavers",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/lib/auto-sync-service.ts b/lib/auto-sync-service.ts
index 343ca26..352c165 100644
--- a/lib/auto-sync-service.ts
+++ b/lib/auto-sync-service.ts
@@ -1,13 +1,14 @@
/**
- * Auto-Sync Service for iCloud Calendars
+ * Auto-Sync Service for External Calendars
* Runs in the background and periodically syncs calendars based on their autoSyncInterval
+ * Supports iCloud, Google Calendar, and other iCal-based services
*/
import { db } from "@/lib/db";
-import { icloudSyncs } from "@/lib/db/schema";
+import { externalSyncs } from "@/lib/db/schema";
import { gt, eq } from "drizzle-orm";
import { eventEmitter } from "@/lib/event-emitter";
-import { syncICloudCalendar } from "@/app/api/icloud-syncs/[id]/sync/route";
+import { syncExternalCalendar } from "@/app/api/external-syncs/[id]/sync/route";
interface SyncJob {
syncId: string;
@@ -69,8 +70,8 @@ class AutoSyncService {
// Get all syncs with auto-sync enabled (autoSyncInterval > 0)
const syncs = await db
.select()
- .from(icloudSyncs)
- .where(gt(icloudSyncs.autoSyncInterval, 0));
+ .from(externalSyncs)
+ .where(gt(externalSyncs.autoSyncInterval, 0));
// Remove jobs for syncs that were deleted or disabled
for (const [syncId] of this.jobs) {
@@ -147,7 +148,7 @@ class AutoSyncService {
try {
// Call sync function directly instead of HTTP fetch
- const stats = await syncICloudCalendar(syncId);
+ const stats = await syncExternalCalendar(syncId);
if (stats) {
console.log(`Auto-sync completed for ${syncId}:`, stats);
@@ -189,7 +190,7 @@ class AutoSyncService {
try {
// Call sync function directly instead of HTTP fetch
- const stats = await syncICloudCalendar(syncId);
+ const stats = await syncExternalCalendar(syncId);
if (stats) {
console.log(`Manual sync completed for ${syncId}:`, stats);
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index a83001d..0fadd37 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -17,7 +17,7 @@ export const calendars = sqliteTable("calendars", {
.default(sql`CURRENT_TIMESTAMP`),
});
-export const icloudSyncs = sqliteTable("icloud_syncs", {
+export const externalSyncs = sqliteTable("external_syncs", {
id: text("id")
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
@@ -25,7 +25,8 @@ export const icloudSyncs = sqliteTable("icloud_syncs", {
.notNull()
.references(() => calendars.id, { onDelete: "cascade" }),
name: text("name").notNull(),
- icloudUrl: text("icloud_url").notNull(),
+ syncType: text("sync_type").notNull().default("icloud"), // icloud, google, etc.
+ calendarUrl: text("calendar_url").notNull(),
color: text("color").notNull().default("#3b82f6"),
displayMode: text("display_mode").notNull().default("normal"),
isHidden: integer("is_hidden", { mode: "boolean" }).notNull().default(false),
@@ -62,11 +63,11 @@ 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, {
+ externalEventId: text("external_event_id"),
+ externalSyncId: text("external_sync_id").references(() => externalSyncs.id, {
onDelete: "cascade",
}),
- syncedFromIcloud: integer("synced_from_icloud", { mode: "boolean" })
+ syncedFromExternal: integer("synced_from_external", { mode: "boolean" })
.notNull()
.default(false),
createdAt: integer("created_at", { mode: "timestamp" })
@@ -123,8 +124,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 ExternalSync = typeof externalSyncs.$inferSelect;
+export type NewExternalSync = typeof externalSyncs.$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/external-calendar-utils.ts
similarity index 85%
rename from lib/icloud-utils.ts
rename to lib/external-calendar-utils.ts
index 696356e..f000e0b 100644
--- a/lib/icloud-utils.ts
+++ b/lib/external-calendar-utils.ts
@@ -1,15 +1,22 @@
/**
- * iCloud calendar utility functions
+ * External calendar utility functions
+ * Supports iCloud, Google Calendar, and other iCal-based calendar services
*/
import ICAL from "ical.js";
+export type CalendarSyncType = "icloud" | "google";
+
/**
- * Validates iCloud calendar URL to prevent SSRF vulnerabilities
+ * Validates external calendar URL to prevent SSRF vulnerabilities
* @param url - The URL to validate
+ * @param syncType - The type of calendar sync (icloud or google)
* @returns true if valid, false otherwise
*/
-export function isValidICloudUrl(url: string): boolean {
+export function isValidCalendarUrl(
+ url: string,
+ syncType: CalendarSyncType
+): boolean {
try {
const parsedUrl = new URL(url);
@@ -18,10 +25,23 @@ export function isValidICloudUrl(url: string): boolean {
return false;
}
- // Check if hostname is from iCloud domain
const hostname = parsedUrl.hostname.toLowerCase();
- if (!hostname.endsWith(".icloud.com") && hostname !== "icloud.com") {
- return false;
+
+ // Validate based on sync type
+ if (syncType === "icloud") {
+ // Check if hostname is from iCloud domain
+ if (!hostname.endsWith(".icloud.com") && hostname !== "icloud.com") {
+ return false;
+ }
+ } else if (syncType === "google") {
+ // Check if hostname is from Google Calendar domain
+ if (
+ !hostname.endsWith(".google.com") &&
+ hostname !== "google.com" &&
+ hostname !== "calendar.google.com"
+ ) {
+ return false;
+ }
}
return true;
@@ -31,6 +51,14 @@ export function isValidICloudUrl(url: string): boolean {
}
}
+/**
+ * Backwards compatibility - validates iCloud URLs
+ * @deprecated Use isValidCalendarUrl instead
+ */
+export function isValidICloudUrl(url: string): boolean {
+ return isValidCalendarUrl(url, "icloud");
+}
+
/**
* Expands recurring events into individual occurrences within a time window
* @param vevent - The VEVENT component from iCal.js
diff --git a/lib/types.ts b/lib/types.ts
index 5c2820d..ab01f47 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -1,5 +1,5 @@
// Re-export types from Drizzle schema
-export type { Calendar, Shift, ICloudSync } from "./db/schema";
+export type { Calendar, Shift, ExternalSync } from "./db/schema";
export interface CalendarWithCount {
id: string;
@@ -27,8 +27,8 @@ export interface ShiftWithCalendar {
color: string;
notes?: string | null;
isAllDay?: boolean;
- syncedFromIcloud?: boolean;
- icloudSyncId?: string | null;
+ syncedFromExternal?: boolean;
+ externalSyncId?: string | null;
createdAt: Date | null;
updatedAt: Date | null;
}
diff --git a/messages/de.json b/messages/de.json
index 3d0aa4a..9973291 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -170,25 +170,30 @@
"github": "GitHub",
"support": "Unterstützen"
},
- "icloud": {
- "manageTitle": "iCloud-Synchronisierungen verwalten",
- "manageDescription": "Füge mehrere iCloud-Kalendersynchronisierungen für diesen Kalender hinzu und verwalte sie",
+ "externalSync": {
+ "manageTitle": "Kalender-Synchronisierungen verwalten",
+ "manageDescription": "Füge mehrere Kalendersynchronisierungen für diesen Kalender hinzu und verwalte sie",
+ "syncTypeLabel": "Kalender-Typ",
+ "syncTypeICloud": "iCloud",
+ "syncTypeGoogle": "Google",
"displayMode": "Synchronisierte Schichten anzeigen",
"displayModeNormal": "Normal (alle Schichten anzeigen)",
"displayModeMinimal": "Minimalistisch (nur Anzahl anzeigen)",
- "displayModeHint": "Wähle, wie synchronisierte iCloud-Schichten im Kalender angezeigt werden sollen",
+ "displayModeHint": "Wähle, wie synchronisierte Schichten im Kalender angezeigt werden sollen",
"viewSyncedShifts": "Synchronisierte Schichten anzeigen",
"syncedShiftsTitle": "Synchronisierte Schichten - {date}",
- "addSync": "Synchronisierung hinzufügen",
- "addNewSync": "Neue iCloud-Synchronisierung hinzufügen",
- "editSync": "iCloud-Synchronisierung bearbeiten",
+ "addSync": "Hinzufügen",
+ "addNewSync": "Neue Synchronisierung hinzufügen",
+ "editSync": "Kalender-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://)",
+ "urlLabel": "Kalender URL",
+ "urlPlaceholderICloud": "webcal://p108-caldav.icloud.com/published/2/...",
+ "urlPlaceholderGoogle": "https://calendar.google.com/calendar/ical/.../basic.ics",
+ "urlHintICloud": "Füge die webcal:// URL des iCloud Kalenders ein (beginnt mit webcal://)",
+ "urlHintGoogle": "Füge die private iCal URL des Google Kalenders ein (endet mit .ics)",
"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",
+ "invalidUrlFormat": "Ungültiges Kalender URL-Format. URL muss mit webcal:// oder https:// beginnen",
"colorLabel": "Schichten-Farbe",
"colorHint": "Wähle die Farbe für alle importierten Schichten",
"hideCalendar": "Kalender ausblenden",
@@ -203,16 +208,21 @@
"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.",
+ "deleteConfirm": "Diese Kalender-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",
+ "howToTitleICloud": "So erhältst du deine iCloud-Kalender URL:",
+ "howToStep1ICloud": "Öffne iCloud.com und gehe zu Kalender",
+ "howToStep2ICloud": "Klicke auf das Teilen-Symbol neben deinem Kalender",
+ "howToStep3ICloud": "Aktiviere 'Öffentlicher Kalender'",
+ "howToStep4ICloud": "Kopiere die URL und füge sie hier ein",
+ "howToTitleGoogle": "So erhältst du deine Google Kalender URL:",
+ "howToStep1Google": "Öffne Google Kalender und gehe zu Einstellungen",
+ "howToStep2Google": "Wähle deinen Kalender aus",
+ "howToStep3Google": "Scrolle zu 'Geheime Adresse im iCal-Format'",
+ "howToStep4Google": "Kopiere die URL und füge sie hier ein",
"autoSyncLabel": "Automatische Synchronisierung",
"autoSyncHint": "Wähle wie oft dieser Kalender automatisch synchronisiert werden soll",
"autoSyncManual": "Manuell",
diff --git a/messages/en.json b/messages/en.json
index 678c9c0..712e2d0 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -170,25 +170,30 @@
"github": "GitHub",
"support": "Support"
},
- "icloud": {
- "manageTitle": "Manage iCloud Syncs",
- "manageDescription": "Add and manage multiple iCloud calendar syncs for this calendar",
+ "externalSync": {
+ "manageTitle": "Manage Calendar Syncs",
+ "manageDescription": "Add and manage multiple calendar syncs for this calendar",
+ "syncTypeLabel": "Calendar Type",
+ "syncTypeICloud": "iCloud",
+ "syncTypeGoogle": "Google",
"displayMode": "Display synced shifts",
"displayModeNormal": "Normal (show all shifts)",
"displayModeMinimal": "Minimal (show count only)",
- "displayModeHint": "Choose how synced iCloud shifts are displayed in the calendar",
+ "displayModeHint": "Choose how synced shifts are displayed in the calendar",
"viewSyncedShifts": "View synced shifts",
"syncedShiftsTitle": "Synced Shifts - {date}",
"addSync": "Add Sync",
- "addNewSync": "Add New iCloud Sync",
- "editSync": "Edit iCloud Sync",
+ "addNewSync": "Add New Calendar Sync",
+ "editSync": "Edit Calendar 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://)",
+ "urlLabel": "Calendar URL",
+ "urlPlaceholderICloud": "webcal://p108-caldav.icloud.com/published/2/...",
+ "urlPlaceholderGoogle": "https://calendar.google.com/calendar/ical/.../basic.ics",
+ "urlHintICloud": "Paste the webcal:// URL from iCloud (starts with webcal://)",
+ "urlHintGoogle": "Paste the private iCal URL from Google Calendar (ends with .ics)",
"urlAlreadyExists": "This URL has already been added",
- "invalidUrlFormat": "Invalid iCloud URL format. URL must start with webcal:// or https:// and be from icloud.com",
+ "invalidUrlFormat": "Invalid calendar URL format. URL must start with webcal:// or https://",
"colorLabel": "Shift Color",
"colorHint": "Choose the color for all imported shifts",
"hideCalendar": "Hide calendar",
@@ -203,16 +208,21 @@
"updateSuccess": "Sync updated successfully",
"deleteError": "Failed to delete sync",
"deleteSuccess": "Sync deleted successfully",
- "deleteConfirm": "Delete this iCloud sync? All synced shifts will be removed.",
+ "deleteConfirm": "Delete this calendar 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",
+ "howToTitleICloud": "How to get your iCloud calendar URL:",
+ "howToStep1ICloud": "Open iCloud.com and go to Calendar",
+ "howToStep2ICloud": "Click the share icon next to your calendar",
+ "howToStep3ICloud": "Enable 'Public Calendar'",
+ "howToStep4ICloud": "Copy the URL and paste it here",
+ "howToTitleGoogle": "How to get your Google Calendar URL:",
+ "howToStep1Google": "Open Google Calendar and go to Settings",
+ "howToStep2Google": "Select your calendar",
+ "howToStep3Google": "Scroll to 'Secret address in iCal format'",
+ "howToStep4Google": "Copy the URL and paste it here",
"autoSyncLabel": "Auto Sync",
"autoSyncHint": "Choose how often this calendar should automatically sync",
"autoSyncManual": "Manual",