Skip to content

Your favorite shift management application!

feat: Add sync notifications & fix: auto-sync (#38)

panteL6c8742002ab6
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index ca0e2a8..71ad1d5 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -109,6 +109,12 @@ next-intl setup with auto-detection:
- Usage: `const t = useTranslations()` → `t("shift.create")`
- Date formatting: `locale === "de" ? de : enUS`
+**Translation Key Usage Status**:
+
+All translation keys in `messages/{de,en}.json` are actively used.
+
+When adding new features, ensure all translation keys are actually used in components. Remove unused keys to keep translation files clean.
+
### Component Design Patterns
- **Dialogs**: Control state via props, reset on close
@@ -116,6 +122,41 @@ next-intl setup with auto-detection:
- **Colors**: Use `PRESET_COLORS` array, hex format (`#3b82f6`), 20% opacity for backgrounds
- **Dates**: `formatDateToLocal()` for YYYY-MM-DD format
+### UI/UX Design Principles
+
+**Live Updates**: All components must support real-time updates via Server-Sent Events (SSE):
+
+- Listen to relevant SSE events (shift, preset, note, sync-log updates)
+- Use silent refresh patterns: `fetchData(false)` to update without loading states
+- Implement refresh triggers: counter-based props (e.g., `syncLogRefreshTrigger`)
+- Avoid flashing/blinking during updates - update data smoothly without UI disruption
+
+**Consistent Dialog Design**: All dialogs must follow the unified design pattern:
+
+```tsx
+<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("dialog.title")}
+ </DialogTitle>
+ <DialogDescription className="text-sm text-muted-foreground">
+ {t("dialog.description")}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-4 overflow-y-auto flex-1 px-6 pb-6">
+ {/* Dialog content */}
+ </div>
+</DialogContent>
+```
+
+Key design elements:
+
+- Gradient backgrounds for visual depth
+- Consistent padding (`p-6`, `px-6`, `pb-6`)
+- Border styling with reduced opacity (`border-border/50`)
+- Backdrop blur effects for modern aesthetics
+- Gradient text for titles (`bg-gradient-to-r from-foreground to-foreground/70`)
+
### Calendar Interactions
- **Left-click**: Toggle shift with selected preset
diff --git a/README.md b/README.md
index c8f8ad2..03f4321 100644
--- a/README.md
+++ b/README.md
@@ -2,6 +2,7 @@
<div align="center">
![BetterShift](https://img.shields.io/badge/BetterShift-Shift%20Management-blue?style=for-the-badge)
+![Version](https://img.shields.io/github/v/release/pantelx/bettershift?style=for-the-badge&label=Version)
![Checks](https://img.shields.io/github/check-runs/pantelx/bettershift/main?style=for-the-badge&label=Checks)
[![Discord](https://img.shields.io/badge/Discord-Join%20our%20Community-7289DA?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/Ma4SnagqwE)
@@ -28,53 +29,54 @@
## ✨ Key Features
-### 📅 Calendar & Shift Management
+### 📅 Smart Shift Calendar Management
-- **Multiple Calendars**: Create and manage multiple shift calendars with custom names and colors
-- **Interactive Calendar View**: Month-based calendar with week-based layout for easy navigation
-- **Quick Shift Toggle**: Left-click any day to toggle shifts using your selected preset
-- **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")
-- **External Calendars**: Automatically or manually synchronize multiple external calendars at configurable intervals or import ICS files
+- **Multiple Calendars** — Create unlimited shift calendars with custom names and colors for different jobs, people or schedules
+- **Interactive Month View** — Navigate shifts effortlessly with a clean, week-based calendar layout
+- **One-Click Shift Toggle** — Left-click any day to instantly add or remove shifts using your active preset
+- **Daily Notes** — Right-click any day to attach context notes (e.g., "Early shift for doctor appointment")
+- **External Calendar Sync** — Subscribe to external calendars (Google, Outlook, iCal) with automatic or manual refresh
+- **Sync Notification Center** — Monitor external calendar sync status, errors, and updates in real-time
-### 🎨 Customization & Organization
+### 🎨 Flexible Customization
-- **Color Coding**: Assign colors to calendars and presets for better visualization
-- **Preset Management**: Create, edit, and delete shift presets with auto-save functionality
-- **Custom Shift Times**: Define exact start and end times for each shift
-- **Flexible Scheduling**: Easily create one-time shifts or use presets for recurring patterns
+- **Shift Presets** — Build reusable templates with custom labels, times, and color-coded categories
+- **Visual Organization** — Color-code calendars and shifts for instant visual recognition
+- **Quick Preset Switching** — Change active presets on the fly to adapt to different shift patterns
+- **Auto-Save Templates** — Automatically save new shift configurations as presets for future use
-### 🔒 Security & Privacy
+### 🔒 Privacy & Security
-- **Password Protection**: Secure individual calendars with optional passwords
-- **Local Storage**: Passwords are securely hashed using SHA-256
+- **Password Protection** — Lock individual calendars with SHA-256 encrypted passwords
+- **Secure Local Storage** — All data stays on your server; passwords are hashed and never stored in plaintext
+- **Per-Calendar Access Control** — Different calendars can have different security levels
-### 🌐 Internationalization
+### 🌍 International by Design
-- **Multi-Language Support**: Built-in support for German and English
-- **Automatic Detection**: Automatically detects browser language preference
-- **Manual Switching**: Easy language switcher in the footer
-- **Cookie-Based Preference**: Your language choice persists across sessions
+- **Multi-Language Support** — Full German and English translations built-in
+- **Smart Language Detection** — Automatically uses your browser's language preference
+- **Persistent Settings** — Language choice saved in cookies across sessions
+- **Easy Switching** — Toggle languages anytime from the footer
-### 📊 Statistics & Insights
+### 📊 Insightful Analytics
-- **Shift Statistics**: View detailed statistics for different time periods
-- **Customizable Periods**: Analyze shifts for current month, last 30 days, or custom ranges
-- **Real-time Updates**: Statistics automatically refresh when shifts are modified
+- **Flexible Time Periods** — View statistics for current month, last 30 days, or custom date ranges
+- **Real-Time Stats** — Shift totals and hour calculations update instantly when you make changes
+- **Work Pattern Analysis** — Understand your schedule with aggregated shift data
-### 🔄 Real-Time Synchronization
+### ⚡ Live Updates & Sync
-- **Server-Sent Events**: Real-time updates across multiple browser tabs
-- **Offline Handling**: Graceful handling of offline scenarios
-- **Automatic Refresh**: Data refreshes automatically when changes are detected
+- **Server-Sent Events (SSE)** — Changes appear instantly across all open browser tabs
+- **Connection Monitoring** — Visual indicators show real-time sync status
+- **Offline Resilience** — Graceful handling when connection drops, auto-reconnect on restore
+- **Background Refresh** — Data updates silently without disrupting your workflow
-### 💾 Modern Tech Stack
+### 🛠️ Modern Foundation
-- **Next.js 16 App Router**: Latest Next.js with React 19 for optimal performance
-- **SQLite with Drizzle ORM**: Lightweight, file-based database with type-safe queries
-- **Tailwind CSS 4**: Modern styling with shadcn/ui components
-- **Docker Support**: Easy deployment with Docker and Docker Compose
+- **Next.js 16 + React 19** — Built on the latest App Router architecture for peak performance
+- **SQLite + Drizzle ORM** — Lightweight file-based database with full TypeScript type safety
+- **Tailwind CSS 4** — Modern, responsive design with shadcn/ui component library
+- **Docker Ready** — One-command deployment with Docker Compose for easy self-hosting
---
diff --git a/app/api/external-syncs/[id]/sync/route.ts b/app/api/external-syncs/[id]/sync/route.ts
index c278854..7704c82 100644
--- a/app/api/external-syncs/[id]/sync/route.ts
+++ b/app/api/external-syncs/[id]/sync/route.ts
@@ -1,17 +1,25 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { externalSyncs, shifts } from "@/lib/db/schema";
+import { externalSyncs, shifts, syncLogs } from "@/lib/db/schema";
import { eq, inArray } from "drizzle-orm";
import ICAL from "ical.js";
import {
expandRecurringEvents,
splitMultiDayEvent,
+ createEventFingerprint,
+ needsUpdate,
} from "@/lib/external-calendar-utils";
+import { eventEmitter } from "@/lib/event-emitter";
/**
* Core sync logic extracted for reuse by both API route and auto-sync service
+ * @param syncId - The external sync ID
+ * @param syncType - Whether this is "auto" or "manual" sync
*/
-export async function syncExternalCalendar(syncId: string) {
+export async function syncExternalCalendar(
+ syncId: string,
+ syncType: "auto" | "manual" = "manual"
+) {
// Get the external sync configuration
const [externalSync] = await db
.select()
@@ -23,204 +31,310 @@ export async function syncExternalCalendar(syncId: string) {
throw new Error("External sync configuration not found");
}
- // Convert webcal:// to https:// for calendar URLs
- const fetchUrl = externalSync.calendarUrl.replace(
- /^webcal:\/\//i,
- "https://"
- );
+ let stats;
+ let errorMessage: string | null = null;
- // Fetch the calendar from the specified URL with timeout protection
- let icsData: string;
try {
- const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
+ // Convert webcal:// to https:// for calendar URLs
+ const fetchUrl = externalSync.calendarUrl.replace(
+ /^webcal:\/\//i,
+ "https://"
+ );
+ // Fetch the calendar from the specified URL with timeout protection
+ let icsData: string;
try {
- const response = await fetch(fetchUrl, { signal: controller.signal });
- clearTimeout(timeoutId);
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
- if (!response.ok) {
- throw new Error(`Failed to fetch calendar: ${response.statusText}`);
- }
- icsData = await response.text();
- } catch (fetchError) {
- clearTimeout(timeoutId);
-
- // Check if this was a timeout/abort error
- if (fetchError instanceof Error && fetchError.name === "AbortError") {
- throw new Error(
- "Request timed out after 10 seconds. Please try again."
- );
+ try {
+ const response = await fetch(fetchUrl, { signal: controller.signal });
+ clearTimeout(timeoutId);
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch calendar: ${response.statusText}`);
+ }
+ icsData = await response.text();
+ } catch (fetchError) {
+ clearTimeout(timeoutId);
+
+ // Check if this was a timeout/abort error
+ if (fetchError instanceof Error && fetchError.name === "AbortError") {
+ throw new Error(
+ "Request timed out after 10 seconds. Please try again."
+ );
+ }
+ throw fetchError;
}
- throw fetchError;
+ } catch (error) {
+ console.error("Error fetching external calendar:", error);
+ throw new Error(
+ error instanceof Error
+ ? error.message
+ : "Failed to fetch external calendar. Please check the URL."
+ );
}
- } catch (error) {
- console.error("Error fetching external calendar:", error);
- throw new Error(
- error instanceof Error
- ? error.message
- : "Failed to fetch external calendar. Please check the URL."
- );
- }
-
- // Parse the ICS data
- let jcalData;
- try {
- jcalData = ICAL.parse(icsData);
- } catch (error) {
- console.error("Error parsing ICS data:", error);
- throw new Error("Failed to parse calendar data. Invalid ICS format.");
- }
-
- 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 synced shifts for this sync
- const existingShifts = await db
- .select()
- .from(shifts)
- .where(eq(shifts.externalSyncId, syncId));
-
- 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
- );
+ // Parse the ICS data
+ let jcalData;
+ try {
+ jcalData = ICAL.parse(icsData);
+ } catch (error) {
+ console.error("Error parsing ICS data:", error);
+ throw new Error("Failed to parse calendar data. Invalid ICS format.");
+ }
- for (const occurrence of occurrences) {
- const { event, startDate, endDate, recurrenceId } = occurrence;
+ 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 synced shifts for this sync
+ const existingShifts = await db
+ .select()
+ .from(shifts)
+ .where(eq(shifts.externalSyncId, syncId));
+
+ // Create a Map of existing shifts by fingerprint for O(1) lookup
+ const existingShiftsByFingerprint = new Map<
+ string,
+ typeof shifts.$inferSelect
+ >();
+ for (const shift of existingShifts) {
+ const fingerprint = createEventFingerprint(
+ shift.date,
+ shift.startTime,
+ shift.endTime,
+ shift.title,
+ undefined,
+ // Only use externalEventId for iCloud/Google (stable UIDs)
+ externalSync.syncType !== "custom"
+ ? shift.externalEventId || undefined
+ : undefined
+ );
+ existingShiftsByFingerprint.set(fingerprint, shift);
+ }
- // 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;
+ const processedFingerprints = 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
+ }
- 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;
+
+ const title = event.summary || "Untitled Event";
+
+ // Create fingerprint based on event content
+ // For iCloud/Google: include eventId for stable UID-based matching
+ // For custom: exclude eventId as UIDs may be unstable
+ const fingerprint = createEventFingerprint(
+ dayEntry.date,
+ dayEntry.startTime,
+ dayEntry.endTime,
+ title,
+ undefined,
+ externalSync.syncType !== "custom" ? eventId : undefined
+ );
+
+ processedFingerprints.add(fingerprint);
+
+ const shiftData = {
+ calendarId: externalSync.calendarId,
+ date: dayEntry.date,
+ startTime: dayEntry.startTime,
+ endTime: dayEntry.endTime,
+ title,
+ color: externalSync.color,
+ notes: event.description || null,
+ isAllDay,
+ isSecondary: false,
+ externalEventId: eventId,
+ externalSyncId: syncId,
+ syncedFromExternal: true,
+ presetId: null,
+ };
+
+ // Check if this event already exists by fingerprint
+ const existingShift = existingShiftsByFingerprint.get(fingerprint);
+
+ if (existingShift) {
+ // Only update if data has actually changed
+ if (needsUpdate(existingShift, shiftData)) {
+ shiftsToUpdate.push({
+ id: existingShift.id,
+ ...shiftData,
+ updatedAt: new Date(),
+ });
+ }
+ // If no changes, skip this shift (no update needed)
+ } else {
+ // Collect for batch insert
+ shiftsToInsert.push({
+ id: crypto.randomUUID(),
+ ...shiftData,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ });
+ }
+ }
}
+ }
- const isAllDay = startDate.isDate;
-
- // Convert ICAL.Time to JavaScript Date
- const startJsDate = startDate.toJSDate();
- const endJsDate = endDate.toJSDate();
+ // Calculate which shifts to delete before transaction
+ // Delete shifts that are no longer in the external calendar (based on fingerprint)
+ const shiftIdsToDelete = existingShifts
+ .filter((shift) => {
+ const fingerprint = createEventFingerprint(
+ shift.date,
+ shift.startTime,
+ shift.endTime,
+ shift.title,
+ undefined,
+ // Only use externalEventId for iCloud/Google (stable UIDs)
+ externalSync.syncType !== "custom"
+ ? shift.externalEventId || undefined
+ : undefined
+ );
+ return !processedFingerprints.has(fingerprint);
+ })
+ .map((s) => s.id);
- // Split multi-day events into separate shifts for each day
- const dayEntries = splitMultiDayEvent(startJsDate, endJsDate, isAllDay);
+ // 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();
+ }
- 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;
+ // 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();
+ }
+ }
- processedEventIds.add(eventId);
+ // 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();
+ }
- const shiftData = {
+ // Update last sync time
+ tx.update(externalSyncs)
+ .set({
+ lastSyncedAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .where(eq(externalSyncs.id, syncId))
+ .run();
+
+ // Log the sync result
+ tx.insert(syncLogs)
+ .values({
+ id: crypto.randomUUID(),
calendarId: externalSync.calendarId,
- date: dayEntry.date,
- startTime: dayEntry.startTime,
- endTime: dayEntry.endTime,
- title: event.summary || "Untitled Event",
- color: externalSync.color,
- notes: event.description || null,
- isAllDay,
- isSecondary: false,
- externalEventId: eventId,
externalSyncId: syncId,
- syncedFromExternal: true,
- presetId: null,
- };
-
- // Check if this event already exists
- const existingShift = existingShifts.find(
- (s) => s.externalEventId === 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(),
- });
- }
- }
- }
- }
+ externalSyncName: externalSync.name,
+ status: "success",
+ errorMessage: null,
+ shiftsCreated: shiftsToInsert.length,
+ shiftsUpdated: shiftsToUpdate.length,
+ shiftsDeleted: shiftIdsToDelete.length,
+ syncType,
+ syncedAt: new Date(),
+ })
+ .run();
+
+ // Return transaction stats
+ return {
+ created: shiftsToInsert.length,
+ updated: shiftsToUpdate.length,
+ deleted: shiftIdsToDelete.length,
+ totalEvents: vevents.length,
+ totalOccurrences: shiftsToInsert.length + shiftsToUpdate.length,
+ calendarId: externalSync.calendarId,
+ syncType: externalSync.syncType,
+ };
+ });
- // Calculate which shifts to delete before transaction
- const shiftIdsToDelete = existingShifts
- .filter(
- (s) => s.externalEventId && !processedEventIds.has(s.externalEventId)
- )
- .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();
- }
+ stats = transactionResult;
- // 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();
- }
- }
+ // Emit event for sync log creation after successful transaction
+ eventEmitter.emit("calendar-change", {
+ type: "sync-log",
+ action: "create",
+ calendarId: externalSync.calendarId,
+ });
+ } catch (error) {
+ errorMessage =
+ error instanceof Error ? error.message : "Unknown sync error";
- // 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();
- }
+ // Log the error
+ await db.insert(syncLogs).values({
+ id: crypto.randomUUID(),
+ calendarId: externalSync.calendarId,
+ externalSyncId: syncId,
+ externalSyncName: externalSync.name,
+ status: "error",
+ errorMessage,
+ shiftsCreated: 0,
+ shiftsUpdated: 0,
+ shiftsDeleted: 0,
+ syncType,
+ syncedAt: new Date(),
+ });
- // Update last sync time
- tx.update(externalSyncs)
- .set({
- lastSyncedAt: new Date(),
- updatedAt: new Date(),
- })
- .where(eq(externalSyncs.id, syncId))
- .run();
-
- // Return transaction stats
- return {
- created: shiftsToInsert.length,
- updated: shiftsToUpdate.length,
- deleted: shiftIdsToDelete.length,
- totalEvents: vevents.length,
- totalOccurrences: shiftsToInsert.length + shiftsToUpdate.length,
+ // Emit event for sync log creation
+ eventEmitter.emit("calendar-change", {
+ type: "sync-log",
+ action: "create",
calendarId: externalSync.calendarId,
- syncType: externalSync.syncType,
- };
- });
+ });
+
+ throw error;
+ }
- return transactionResult;
+ return stats;
}
export async function POST(
@@ -229,7 +343,7 @@ export async function POST(
) {
try {
const { id: syncId } = await params;
- const stats = await syncExternalCalendar(syncId);
+ const stats = await syncExternalCalendar(syncId, "manual");
return NextResponse.json({
success: true,
diff --git a/app/api/sync-logs/route.ts b/app/api/sync-logs/route.ts
new file mode 100644
index 0000000..d8ffc09
--- /dev/null
+++ b/app/api/sync-logs/route.ts
@@ -0,0 +1,92 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { syncLogs } from "@/lib/db/schema";
+import { eq, desc, and } from "drizzle-orm";
+
+export async function GET(request: NextRequest) {
+ const searchParams = request.nextUrl.searchParams;
+ const calendarId = searchParams.get("calendarId");
+ const limit = parseInt(searchParams.get("limit") || "50");
+
+ if (!calendarId) {
+ return NextResponse.json(
+ { error: "Calendar ID is required" },
+ { status: 400 }
+ );
+ }
+
+ try {
+ const logs = await db
+ .select()
+ .from(syncLogs)
+ .where(eq(syncLogs.calendarId, calendarId))
+ .orderBy(desc(syncLogs.syncedAt))
+ .limit(limit);
+
+ return NextResponse.json(logs);
+ } catch (error) {
+ console.error("Error fetching sync logs:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch sync logs" },
+ { status: 500 }
+ );
+ }
+}
+
+export async function PATCH(request: NextRequest) {
+ const searchParams = request.nextUrl.searchParams;
+ const calendarId = searchParams.get("calendarId");
+ const action = searchParams.get("action");
+
+ if (!calendarId) {
+ return NextResponse.json(
+ { error: "Calendar ID is required" },
+ { status: 400 }
+ );
+ }
+
+ try {
+ if (action === "markErrorsAsRead") {
+ // Mark all error logs as read for this calendar
+ await db
+ .update(syncLogs)
+ .set({ isRead: true })
+ .where(
+ and(eq(syncLogs.calendarId, calendarId), eq(syncLogs.status, "error"))
+ );
+
+ return NextResponse.json({ success: true });
+ }
+
+ return NextResponse.json({ error: "Invalid action" }, { status: 400 });
+ } catch (error) {
+ console.error("Error updating sync logs:", error);
+ return NextResponse.json(
+ { error: "Failed to update sync logs" },
+ { status: 500 }
+ );
+ }
+}
+
+export async function DELETE(request: NextRequest) {
+ const searchParams = request.nextUrl.searchParams;
+ const calendarId = searchParams.get("calendarId");
+
+ if (!calendarId) {
+ return NextResponse.json(
+ { error: "Calendar ID is required" },
+ { status: 400 }
+ );
+ }
+
+ try {
+ await db.delete(syncLogs).where(eq(syncLogs.calendarId, calendarId));
+ return NextResponse.json({ success: true });
+ } catch (error) {
+ console.error("Error deleting sync logs:", error);
+ return NextResponse.json(
+ { error: "Failed to delete sync logs" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/page.tsx b/app/page.tsx
index ebd92e8..bf759bf 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -10,6 +10,7 @@ import { PasswordDialog } from "@/components/password-dialog";
import { ManagePasswordDialog } from "@/components/manage-password-dialog";
import { DeleteCalendarDialog } from "@/components/delete-calendar-dialog";
import { ExternalSyncManageDialog } from "@/components/external-sync-manage-dialog";
+import { SyncNotificationDialog } from "@/components/sync-notification-dialog";
import { DayShiftsDialog } from "@/components/day-shifts-dialog";
import { SyncedShiftsDialog } from "@/components/synced-shifts-dialog";
import { LanguageSwitcher } from "@/components/language-switcher";
@@ -98,11 +99,13 @@ function HomeContent() {
// External Calendar Syncs state
const [externalSyncs, setExternalSyncs] = useState<ExternalSync[]>([]);
+ const [hasSyncErrors, setHasSyncErrors] = useState(false);
// Fetch external syncs for the calendar
const fetchExternalSyncs = useCallback(async () => {
if (!selectedCalendar) {
setExternalSyncs([]);
+ setHasSyncErrors(false);
return;
}
@@ -119,9 +122,34 @@ function HomeContent() {
}
}, [selectedCalendar]);
+ // Fetch sync logs to check for errors
+ const fetchSyncErrorStatus = useCallback(async () => {
+ if (!selectedCalendar) {
+ setHasSyncErrors(false);
+ return;
+ }
+
+ try {
+ const response = await fetch(
+ `/api/sync-logs?calendarId=${selectedCalendar}&limit=50`
+ );
+ if (response.ok) {
+ const logs = await response.json();
+ // Only show errors that are not read
+ const hasErrors = logs.some(
+ (log: any) => log.status === "error" && !log.isRead
+ );
+ setHasSyncErrors(hasErrors);
+ }
+ } catch (error) {
+ console.error("Failed to fetch sync logs:", error);
+ }
+ }, [selectedCalendar]);
+
useEffect(() => {
fetchExternalSyncs();
- }, [fetchExternalSyncs]);
+ fetchSyncErrorStatus();
+ }, [fetchExternalSyncs, fetchSyncErrorStatus]);
// Local state
const [selectedPresetId, setSelectedPresetId] = useState<
@@ -140,6 +168,9 @@ function HomeContent() {
const [showDeleteCalendarDialog, setShowDeleteCalendarDialog] =
useState(false);
const [showExternalSyncDialog, setShowExternalSyncDialog] = useState(false);
+ const [showSyncNotificationDialog, setShowSyncNotificationDialog] =
+ useState(false);
+ const [syncLogRefreshTrigger, setSyncLogRefreshTrigger] = useState(0);
const [showDayShiftsDialog, setShowDayShiftsDialog] = useState(false);
const [showSyncedShiftsDialog, setShowSyncedShiftsDialog] = useState(false);
const [selectedDayDate, setSelectedDayDate] = useState<Date | null>(null);
@@ -154,11 +185,12 @@ function HomeContent() {
>();
const [selectedNote, setSelectedNote] = useState<CalendarNote | undefined>();
const [pendingAction, setPendingAction] = useState<{
- type: "delete" | "edit";
+ type: "delete" | "edit" | "syncNotifications";
shiftId?: string;
formData?: ShiftFormData;
presetAction?: () => Promise<void>;
noteAction?: () => Promise<void>;
+ action?: () => Promise<void>;
} | null>(null);
const [statsRefreshTrigger, setStatsRefreshTrigger] = useState(0);
const [togglingDates, setTogglingDates] = useState<Set<string>>(new Set());
@@ -179,6 +211,10 @@ function HomeContent() {
onPresetUpdate: refetchPresets,
onNoteUpdate: refetchNotes,
onStatsRefresh: () => setStatsRefreshTrigger((prev) => prev + 1),
+ onSyncLogUpdate: () => {
+ fetchSyncErrorStatus();
+ setSyncLogRefreshTrigger((prev) => prev + 1);
+ },
isConnected,
setIsConnected,
});
@@ -344,6 +380,8 @@ function HomeContent() {
} else if (pendingAction.noteAction) {
await pendingAction.noteAction();
setShowNoteDialog(false);
+ } else if (pendingAction.action) {
+ await pendingAction.action();
}
} catch (error) {
console.error("Failed to execute pending action:", error);
@@ -728,12 +766,49 @@ function HomeContent() {
selectedPresetId={selectedPresetId}
isConnected={isConnected}
showMobileCalendarDialog={showMobileCalendarDialog}
+ hasSyncErrors={hasSyncErrors}
onSelectCalendar={setSelectedCalendar}
onSelectPreset={setSelectedPresetId}
onCreateCalendar={() => setShowCalendarDialog(true)}
onManagePassword={() => setShowManagePasswordDialog(true)}
onDeleteCalendar={initiateDeleteCalendar}
onExternalSync={handleExternalSyncClick}
+ onSyncNotifications={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 cachedPassword = getCachedPassword(selectedCalendar);
+
+ if (cachedPassword) {
+ // Verify cached password
+ const result = await verifyAndCachePassword(
+ selectedCalendar,
+ cachedPassword
+ );
+
+ if (result.valid) {
+ setShowSyncNotificationDialog(true);
+ return;
+ }
+ }
+
+ // Show password dialog if no valid cached password
+ setPendingAction({
+ type: "syncNotifications",
+ action: async () => {
+ setShowSyncNotificationDialog(true);
+ },
+ });
+ setShowPasswordDialog(true);
+ } else {
+ // No password protection
+ setShowSyncNotificationDialog(true);
+ }
+ }}
onPresetsChange={refetchPresets}
onShiftsChange={refetchShifts}
onStatsRefresh={() => setStatsRefreshTrigger((prev) => prev + 1)}
@@ -1021,12 +1096,15 @@ function HomeContent() {
open={showExternalSyncDialog}
onOpenChange={setShowExternalSyncDialog}
calendarId={selectedCalendar}
+ syncErrorRefreshTrigger={syncLogRefreshTrigger}
onSyncComplete={() => {
refetchShifts();
refetchCalendars();
setStatsRefreshTrigger((prev) => prev + 1);
// Refetch external syncs to get updated displayMode
fetchExternalSyncs();
+ // Refetch sync error status
+ fetchSyncErrorStatus();
}}
/>
)}
@@ -1049,6 +1127,18 @@ function HomeContent() {
shifts={selectedSyncedShifts}
/>
+ {/* Sync Notification Center */}
+ {selectedCalendar && (
+ <SyncNotificationDialog
+ open={showSyncNotificationDialog}
+ onOpenChange={setShowSyncNotificationDialog}
+ calendarId={selectedCalendar}
+ onErrorsMarkedRead={fetchSyncErrorStatus}
+ onSyncLogUpdate={() => setSyncLogRefreshTrigger((prev) => prev + 1)}
+ syncLogRefreshTrigger={syncLogRefreshTrigger}
+ />
+ )}
+
{/* Footer */}
<AppFooter versionInfo={versionInfo} />
</div>
diff --git a/components/app-header.tsx b/components/app-header.tsx
index e148ca4..dd087db 100644
--- a/components/app-header.tsx
+++ b/components/app-header.tsx
@@ -21,12 +21,14 @@ interface AppHeaderProps {
selectedPresetId: string | undefined;
isConnected: boolean;
showMobileCalendarDialog: boolean;
+ hasSyncErrors?: boolean;
onSelectCalendar: (id: string) => void;
onSelectPreset: (id: string | undefined) => void;
onCreateCalendar: () => void;
onManagePassword: () => void;
onDeleteCalendar: (id: string) => void;
onExternalSync: () => void;
+ onSyncNotifications: () => void;
onPresetsChange: () => void;
onShiftsChange: () => void;
onStatsRefresh: () => void;
@@ -43,12 +45,14 @@ export function AppHeader({
selectedPresetId,
isConnected,
showMobileCalendarDialog,
+ hasSyncErrors = false,
onSelectCalendar,
onSelectPreset,
onCreateCalendar,
onManagePassword,
onDeleteCalendar,
onExternalSync,
+ onSyncNotifications,
onPresetsChange,
onShiftsChange,
onStatsRefresh,
@@ -129,6 +133,8 @@ export function AppHeader({
onManagePassword={onManagePassword}
onDelete={onDeleteCalendar}
onExternalSync={onExternalSync}
+ onSyncNotifications={onSyncNotifications}
+ hasSyncErrors={hasSyncErrors}
/>
</div>
</motion.div>
@@ -211,6 +217,7 @@ export function AppHeader({
{selectedCalendar && (
<div className="px-0.5 sm:px-0">
<PresetSelector
+ calendars={calendars}
presets={presets}
selectedPresetId={selectedPresetId}
onSelectPreset={onSelectPreset}
@@ -265,6 +272,12 @@ export function AppHeader({
onMobileCalendarDialogChange(false);
onExternalSync();
}}
+ onSyncNotifications={() => {
+ onMobileCalendarDialogChange(false);
+ onSyncNotifications();
+ }}
+ hasSyncErrors={hasSyncErrors}
+ variant="mobile"
/>
</div>
</DialogContent>
diff --git a/components/calendar-dialog.tsx b/components/calendar-dialog.tsx
index 9e9d598..c59dae5 100644
--- a/components/calendar-dialog.tsx
+++ b/components/calendar-dialog.tsx
@@ -245,7 +245,7 @@ export function CalendarDialog({
disabled={!name.trim()}
className="flex-1 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:opacity-50 disabled:shadow-none"
>
- {t("common.create")} {t("calendar.title")}
+ {t("common.create")}
</Button>
</div>
</form>
diff --git a/components/calendar-selector.tsx b/components/calendar-selector.tsx
index 9dbf315..4b2e00a 100644
--- a/components/calendar-selector.tsx
+++ b/components/calendar-selector.tsx
@@ -10,7 +10,8 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
-import { Plus, KeyRound, Trash2, Cloud } from "lucide-react";
+import { Plus, KeyRound, Trash2, Cloud, Bell } from "lucide-react";
+import { getCachedPassword } from "@/lib/password-cache";
interface CalendarSelectorProps {
calendars: CalendarWithCount[];
@@ -20,6 +21,9 @@ interface CalendarSelectorProps {
onManagePassword?: () => void;
onDelete?: (id: string) => void;
onExternalSync?: () => void;
+ onSyncNotifications?: () => void;
+ hasSyncErrors?: boolean;
+ variant?: "desktop" | "mobile";
}
export function CalendarSelector({
@@ -30,13 +34,113 @@ export function CalendarSelector({
onManagePassword,
onDelete,
onExternalSync,
+ onSyncNotifications,
+ hasSyncErrors = false,
+ variant = "desktop",
}: CalendarSelectorProps) {
const t = useTranslations();
+ const selectedCalendar = calendars.find((c) => c.id === selectedId);
+ // Hide external sync buttons if calendar is locked AND no valid password is cached
+ const isCalendarLocked = selectedCalendar?.isLocked === true;
+ const hasPassword = selectedId ? !!getCachedPassword(selectedId) : false;
+ const shouldHideSyncButtons = isCalendarLocked && !hasPassword;
+
+ // Desktop: Compact icon-based layout
+ if (variant === "desktop") {
+ return (
+ <div className="flex gap-2 items-center">
+ <Select value={selectedId} onValueChange={onSelect}>
+ <SelectTrigger className="flex-1 h-9 sm:h-10 text-sm">
+ <SelectValue placeholder={t("calendar.title")} />
+ </SelectTrigger>
+ <SelectContent>
+ {calendars.map((calendar) => (
+ <SelectItem key={calendar.id} value={calendar.id}>
+ <div className="flex items-center gap-2">
+ <div
+ className="w-3 h-3 rounded-full"
+ style={{ backgroundColor: calendar.color }}
+ />
+ {calendar.name}
+ </div>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {onManagePassword && selectedId && (
+ <Button
+ onClick={onManagePassword}
+ size="icon"
+ variant="outline"
+ className="h-9 w-9 sm:h-10 sm:w-10"
+ title={t("calendar.managePassword")}
+ >
+ <KeyRound className="h-4 w-4" />
+ </Button>
+ )}
+ {onExternalSync && selectedId && !shouldHideSyncButtons && (
+ <Button
+ onClick={onExternalSync}
+ size="icon"
+ variant="outline"
+ className="h-9 w-9 sm:h-10 sm:w-10"
+ title={t("externalSync.manageTitle")}
+ >
+ <Cloud className="h-4 w-4" />
+ </Button>
+ )}
+ {onSyncNotifications && selectedId && !shouldHideSyncButtons && (
+ <Button
+ onClick={onSyncNotifications}
+ size="icon"
+ variant="outline"
+ className={`h-9 w-9 sm:h-10 sm:w-10 relative ${
+ hasSyncErrors
+ ? "text-red-600 hover:text-red-600 border-red-300 hover:border-red-400"
+ : ""
+ }`}
+ title={
+ hasSyncErrors
+ ? t("syncNotifications.hasErrors")
+ : t("syncNotifications.title")
+ }
+ >
+ <Bell className="h-4 w-4" />
+ {hasSyncErrors && (
+ <span className="absolute -top-1 -right-1 h-3 w-3 bg-red-600 rounded-full border-2 border-background animate-pulse" />
+ )}
+ </Button>
+ )}
+ {onDelete && selectedId && (
+ <Button
+ onClick={() => onDelete(selectedId)}
+ size="icon"
+ variant="outline"
+ className="h-9 w-9 sm:h-10 sm:w-10 text-destructive hover:text-destructive"
+ title={t("calendar.deleteCalendar")}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ )}
+ <Button
+ onClick={onCreateNew}
+ size="icon"
+ variant="outline"
+ className="h-9 w-9 sm:h-10 sm:w-10"
+ >
+ <Plus className="h-4 w-4" />
+ </Button>
+ </div>
+ );
+ }
+
+ // Mobile: Full-width dropdown with buttons in grid below
return (
- <div className="flex gap-2 items-center">
+ <div className="flex flex-col gap-3">
+ {/* Calendar Dropdown - Full Width */}
<Select value={selectedId} onValueChange={onSelect}>
- <SelectTrigger className="flex-1 h-9 sm:h-10 text-sm">
+ <SelectTrigger className="h-10 text-sm">
<SelectValue placeholder={t("calendar.title")} />
</SelectTrigger>
<SelectContent>
@@ -53,46 +157,72 @@ export function CalendarSelector({
))}
</SelectContent>
</Select>
- {onManagePassword && selectedId && (
- <Button
- onClick={onManagePassword}
- size="icon"
- variant="outline"
- className="h-9 w-9 sm:h-10 sm:w-10"
- title={t("calendar.managePassword")}
- >
- <KeyRound className="h-4 w-4" />
- </Button>
- )}
- {onExternalSync && selectedId && (
- <Button
- onClick={onExternalSync}
- size="icon"
- variant="outline"
- className="h-9 w-9 sm:h-10 sm:w-10"
- title={t("externalSync.manageTitle")}
- >
- <Cloud className="h-4 w-4" />
- </Button>
- )}
- {onDelete && selectedId && (
- <Button
- onClick={() => onDelete(selectedId)}
- size="icon"
- variant="outline"
- className="h-9 w-9 sm:h-10 sm:w-10 text-destructive hover:text-destructive"
- title={t("calendar.deleteCalendar")}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
+
+ {/* Action Buttons - Even distribution */}
+ {selectedId && (
+ <div className="grid grid-cols-4 gap-2">
+ {onManagePassword && (
+ <Button
+ onClick={onManagePassword}
+ size="sm"
+ variant="outline"
+ className="h-9"
+ title={t("calendar.managePassword")}
+ >
+ <KeyRound className="h-4 w-4" />
+ </Button>
+ )}
+ {onExternalSync && !shouldHideSyncButtons && (
+ <Button
+ onClick={onExternalSync}
+ size="sm"
+ variant="outline"
+ className="h-9"
+ title={t("externalSync.manage")}
+ >
+ <Cloud className="h-4 w-4" />
+ </Button>
+ )}
+ {onSyncNotifications && !shouldHideSyncButtons && (
+ <Button
+ onClick={onSyncNotifications}
+ size="sm"
+ variant="outline"
+ className={`h-9 relative ${
+ hasSyncErrors
+ ? "text-red-600 hover:text-red-600 border-red-300 hover:border-red-400"
+ : ""
+ }`}
+ title={
+ hasSyncErrors
+ ? t("syncNotifications.hasErrors")
+ : t("syncNotifications.title")
+ }
+ >
+ <Bell className="h-4 w-4" />
+ {hasSyncErrors && (
+ <span className="absolute -top-1 -right-1 h-2.5 w-2.5 bg-red-600 rounded-full border-2 border-background animate-pulse" />
+ )}
+ </Button>
+ )}
+ {onDelete && (
+ <Button
+ onClick={() => onDelete(selectedId)}
+ size="sm"
+ variant="outline"
+ className="h-9 text-destructive hover:text-destructive"
+ title={t("calendar.deleteCalendar")}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
)}
- <Button
- onClick={onCreateNew}
- size="icon"
- variant="outline"
- className="h-9 w-9 sm:h-10 sm:w-10"
- >
- <Plus className="h-4 w-4" />
+
+ {/* Create New Button - Full Width */}
+ <Button onClick={onCreateNew} size="sm" variant="outline" className="h-9">
+ <Plus className="h-4 w-4 mr-2" />
+ {t("common.create")}
</Button>
</div>
);
diff --git a/components/external-sync-manage-dialog.tsx b/components/external-sync-manage-dialog.tsx
index 4ce1e7e..60a49f2 100644
--- a/components/external-sync-manage-dialog.tsx
+++ b/components/external-sync-manage-dialog.tsx
@@ -44,6 +44,7 @@ interface ExternalSyncManageDialogProps {
onOpenChange: (open: boolean) => void;
calendarId: string | null;
onSyncComplete?: () => void;
+ syncErrorRefreshTrigger?: number;
}
export function ExternalSyncManageDialog({
@@ -51,9 +52,11 @@ export function ExternalSyncManageDialog({
onOpenChange,
calendarId,
onSyncComplete,
+ syncErrorRefreshTrigger,
}: ExternalSyncManageDialogProps) {
const t = useTranslations();
const [syncs, setSyncs] = useState<ExternalSync[]>([]);
+ const [syncErrors, setSyncErrors] = useState<Record<string, string>>({});
const [isLoading, setIsLoading] = useState(false);
const [isSyncing, setIsSyncing] = useState<string | null>(null);
const [isDeleting, setIsDeleting] = useState<string | null>(null);
@@ -84,24 +87,71 @@ export function ExternalSyncManageDialog({
} | null>(null);
const isInitialMount = useRef(true);
- const fetchSyncs = useCallback(async () => {
- if (!calendarId) return;
+ const fetchSyncs = useCallback(
+ async (showLoadingState = true) => {
+ if (!calendarId) return;
- setIsLoading(true);
- try {
- const response = await fetch(
- `/api/external-syncs?calendarId=${calendarId}`
- );
- if (response.ok) {
- const data = await response.json();
- setSyncs(data);
+ if (showLoadingState) {
+ setIsLoading(true);
}
- } catch (error) {
- console.error("Failed to fetch syncs:", error);
- } finally {
- setIsLoading(false);
+ try {
+ const response = await fetch(
+ `/api/external-syncs?calendarId=${calendarId}`
+ );
+ if (response.ok) {
+ const data = await response.json();
+ setSyncs(data);
+
+ // Fetch last sync logs to check for errors
+ const logsResponse = await fetch(
+ `/api/sync-logs?calendarId=${calendarId}&limit=50`
+ );
+ if (logsResponse.ok) {
+ const logs = await logsResponse.json();
+ const errors: Record<string, string> = {};
+
+ // Get the latest error for each external sync
+ data.forEach((sync: ExternalSync) => {
+ const syncLogs = logs.filter(
+ (log: any) => log.externalSyncId === sync.id
+ );
+ // Only show unread errors
+ const latestError = syncLogs.find(
+ (log: any) => log.status === "error" && !log.isRead
+ );
+ if (latestError) {
+ errors[sync.id] =
+ latestError.errorMessage ||
+ t("syncNotifications.statusError");
+ }
+ });
+
+ setSyncErrors(errors);
+ }
+ }
+ } catch (error) {
+ console.error("Failed to fetch syncs:", error);
+ } finally {
+ if (showLoadingState) {
+ setIsLoading(false);
+ }
+ }
+ },
+ [calendarId, t]
+ );
+
+ // Silent refresh for sync error updates (triggered by SSE)
+ useEffect(() => {
+ if (
+ open &&
+ calendarId &&
+ syncErrorRefreshTrigger &&
+ syncErrorRefreshTrigger > 0
+ ) {
+ // Silently refresh sync errors without loading state
+ fetchSyncs(false);
}
- }, [calendarId]);
+ }, [syncErrorRefreshTrigger, open, calendarId, fetchSyncs]);
// Load syncs when dialog opens, reset state when it closes
useEffect(() => {
@@ -700,11 +750,25 @@ export function ExternalSyncManageDialog({
</div>
</div>
- {/* Last synced info - always below badges */}
- {sync.lastSyncedAt && (
- <div className="text-xs text-muted-foreground pt-1 border-t border-border/30">
- {t("externalSync.lastSynced")}:{" "}
- {new Date(sync.lastSyncedAt).toLocaleString()}
+ {/* Last synced info and errors - always below badges */}
+ {(sync.lastSyncedAt || syncErrors[sync.id]) && (
+ <div className="pt-1 border-t border-border/30 space-y-1.5">
+ {sync.lastSyncedAt && (
+ <div className="text-xs text-muted-foreground">
+ {t("externalSync.lastSynced")}:{" "}
+ {new Date(sync.lastSyncedAt).toLocaleString()}
+ </div>
+ )}
+ {syncErrors[sync.id] && (
+ <div className="text-xs text-red-100 bg-red-950/90 p-2 rounded border border-red-800">
+ <div className="font-medium mb-0.5">
+ {t("syncNotifications.errorMessage")}:
+ </div>
+ <div className="text-red-200">
+ {syncErrors[sync.id]}
+ </div>
+ </div>
+ )}
</div>
)}
</div>
diff --git a/components/preset-list.tsx b/components/preset-list.tsx
index c5c33e7..c6558a6 100644
--- a/components/preset-list.tsx
+++ b/components/preset-list.tsx
@@ -3,8 +3,12 @@ import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Check, Plus, Settings, ChevronDown, ChevronUp } from "lucide-react";
import { ShiftPreset } from "@/lib/db/schema";
+import { CalendarWithCount } from "@/lib/types";
+import { getCachedPassword } from "@/lib/password-cache";
interface PresetListProps {
+ calendars: CalendarWithCount[];
+ calendarId: string;
presets: ShiftPreset[];
selectedPresetId?: string;
onSelectPreset: (presetId: string | undefined) => void;
@@ -14,6 +18,8 @@ interface PresetListProps {
}
export function PresetList({
+ calendars,
+ calendarId,
presets,
selectedPresetId,
onSelectPreset,
@@ -24,6 +30,12 @@ export function PresetList({
const t = useTranslations();
const [showSecondary, setShowSecondary] = React.useState(false);
+ // Hide preset buttons if calendar is locked AND no valid password is cached
+ const selectedCalendar = calendars.find((c) => c.id === calendarId);
+ const isCalendarLocked = selectedCalendar?.isLocked === true;
+ const hasPassword = calendarId ? !!getCachedPassword(calendarId) : false;
+ const shouldHidePresetButtons = isCalendarLocked && !hasPassword;
+
const primaryPresets = presets.filter((p) => !p.isSecondary);
const secondaryPresets = presets.filter((p) => p.isSecondary);
@@ -41,6 +53,11 @@ export function PresetList({
);
}
+ // Hide everything if calendar is locked and no password is cached
+ if (shouldHidePresetButtons) {
+ return null;
+ }
+
if (presets.length === 0) {
return (
<div className="border-2 border-dashed rounded-lg p-4 sm:p-6 text-center space-y-2 sm:space-y-3">
diff --git a/components/preset-selector.tsx b/components/preset-selector.tsx
index dfedd3a..de6cedb 100644
--- a/components/preset-selector.tsx
+++ b/components/preset-selector.tsx
@@ -2,6 +2,7 @@
import { useTranslations } from "next-intl";
import { ShiftPreset } from "@/lib/db/schema";
+import { CalendarWithCount } from "@/lib/types";
import { useState } from "react";
import { toast } from "sonner";
import { PresetList } from "@/components/preset-list";
@@ -13,6 +14,7 @@ import { PresetManageDialog } from "@/components/preset-manage-dialog";
import { usePasswordProtection } from "@/hooks/usePasswordProtection";
interface PresetSelectorProps {
+ calendars: CalendarWithCount[];
presets: ShiftPreset[];
selectedPresetId?: string;
onSelectPreset: (presetId: string | undefined) => void;
@@ -25,6 +27,7 @@ interface PresetSelectorProps {
}
export function PresetSelector({
+ calendars,
presets,
selectedPresetId,
onSelectPreset,
@@ -166,6 +169,8 @@ export function PresetSelector({
return (
<>
<PresetList
+ calendars={calendars}
+ calendarId={calendarId}
presets={presets}
selectedPresetId={selectedPresetId}
onSelectPreset={onSelectPreset}
diff --git a/components/sync-notification-dialog.tsx b/components/sync-notification-dialog.tsx
new file mode 100644
index 0000000..3e8350f
--- /dev/null
+++ b/components/sync-notification-dialog.tsx
@@ -0,0 +1,339 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { SyncLog } from "@/lib/db/schema";
+import {
+ CheckCircle2,
+ XCircle,
+ Clock,
+ RefreshCw,
+ User,
+ Trash2,
+ CheckCheck,
+} from "lucide-react";
+import { toast } from "sonner";
+
+interface SyncNotificationDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendarId: string | null;
+ onErrorsMarkedRead?: () => void;
+ onSyncLogUpdate?: () => void;
+ syncLogRefreshTrigger?: number;
+}
+
+export function SyncNotificationDialog({
+ open,
+ onOpenChange,
+ calendarId,
+ onErrorsMarkedRead,
+ onSyncLogUpdate,
+ syncLogRefreshTrigger,
+}: SyncNotificationDialogProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const [logs, setLogs] = useState<SyncLog[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [filter, setFilter] = useState<"all" | "success" | "error">("all");
+ const [isDeleting, setIsDeleting] = useState(false);
+ const [isMarkingRead, setIsMarkingRead] = useState(false);
+
+ const fetchLogs = useCallback(
+ async (showLoadingState = true) => {
+ if (!calendarId) return;
+
+ if (showLoadingState) {
+ setLoading(true);
+ }
+ try {
+ const response = await fetch(
+ `/api/sync-logs?calendarId=${calendarId}&limit=20`
+ );
+ if (response.ok) {
+ const data = await response.json();
+ setLogs(data);
+ }
+ } catch (error) {
+ console.error("Failed to fetch sync logs:", error);
+ } finally {
+ if (showLoadingState) {
+ setLoading(false);
+ }
+ }
+ },
+ [calendarId]
+ );
+
+ useEffect(() => {
+ if (open && calendarId) {
+ fetchLogs();
+ }
+ }, [open, calendarId, fetchLogs]);
+
+ // Silent refresh when SSE triggers update (syncLogRefreshTrigger changes)
+ useEffect(() => {
+ if (
+ open &&
+ calendarId &&
+ syncLogRefreshTrigger &&
+ syncLogRefreshTrigger > 0
+ ) {
+ fetchLogs(false);
+ }
+ }, [open, calendarId, syncLogRefreshTrigger, fetchLogs]);
+
+ const formatDateTime = (date: Date) => {
+ return new Intl.DateTimeFormat(locale, {
+ day: "2-digit",
+ month: "2-digit",
+ year: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ }).format(new Date(date));
+ };
+
+ const getStatusIcon = (status: string) => {
+ if (status === "success") {
+ return <CheckCircle2 className="h-5 w-5 text-green-600" />;
+ }
+ return <XCircle className="h-5 w-5 text-red-600" />;
+ };
+
+ const getSyncTypeIcon = (syncType: string) => {
+ if (syncType === "auto") {
+ return <RefreshCw className="h-4 w-4" />;
+ }
+ return <User className="h-4 w-4" />;
+ };
+
+ const hasChanges = (log: SyncLog) => {
+ return (
+ log.shiftsCreated > 0 || log.shiftsUpdated > 0 || log.shiftsDeleted > 0
+ );
+ };
+
+ const handleDeleteLogs = async () => {
+ if (!calendarId) return;
+ if (!confirm(t("syncNotifications.deleteConfirm"))) return;
+
+ setIsDeleting(true);
+ try {
+ const response = await fetch(`/api/sync-logs?calendarId=${calendarId}`, {
+ method: "DELETE",
+ });
+
+ if (response.ok) {
+ setLogs([]);
+ toast.success(t("syncNotifications.deleteSuccess"));
+ } else {
+ toast.error(t("syncNotifications.deleteError"));
+ }
+ } catch (error) {
+ console.error("Failed to delete sync logs:", error);
+ toast.error(t("syncNotifications.deleteError"));
+ } finally {
+ setIsDeleting(false);
+ }
+ };
+
+ const handleMarkErrorsAsRead = async () => {
+ if (!calendarId) return;
+
+ setIsMarkingRead(true);
+ try {
+ const response = await fetch(
+ `/api/sync-logs?calendarId=${calendarId}&action=markErrorsAsRead`,
+ { method: "PATCH" }
+ );
+
+ if (response.ok) {
+ await fetchLogs();
+ toast.success(t("syncNotifications.markedAsRead"));
+ // Notify parent to refresh error status
+ onErrorsMarkedRead?.();
+ } else {
+ toast.error(t("syncNotifications.markAsReadError"));
+ }
+ } catch (error) {
+ console.error("Failed to mark errors as read:", error);
+ toast.error(t("syncNotifications.markAsReadError"));
+ } finally {
+ setIsMarkingRead(false);
+ }
+ };
+
+ const filteredLogs = logs.filter((log) => {
+ if (filter === "all") return true;
+ return log.status === filter;
+ });
+
+ 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("syncNotifications.title")}
+ </DialogTitle>
+ </DialogHeader>
+
+ {/* Filter and Actions */}
+ <div className="flex flex-wrap gap-2 items-center pb-4 border-b border-border/50 px-6 pt-6">
+ <Select
+ value={filter}
+ onValueChange={(v: typeof filter) => setFilter(v)}
+ >
+ <SelectTrigger className="w-[140px]">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">
+ {t("syncNotifications.filterAll")}
+ </SelectItem>
+ <SelectItem value="success">
+ {t("syncNotifications.filterSuccess")}
+ </SelectItem>
+ <SelectItem value="error">
+ {t("syncNotifications.filterError")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <div className="flex gap-2 ml-auto">
+ {logs.some((log) => log.status === "error" && !log.isRead) && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleMarkErrorsAsRead}
+ disabled={isMarkingRead}
+ >
+ <CheckCheck className="h-4 w-4 mr-2" />
+ {t("syncNotifications.markAsRead")}
+ </Button>
+ )}
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleDeleteLogs}
+ disabled={isDeleting || logs.length === 0}
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("syncNotifications.deleteAll")}
+ </Button>
+ </div>
+ </div>
+
+ <div className="space-y-4 overflow-y-auto flex-1 px-6 pb-6">
+ {loading ? (
+ <div className="text-center py-8 text-muted-foreground">
+ {t("common.loading")}
+ </div>
+ ) : filteredLogs.length === 0 ? (
+ <div className="text-center py-8 text-muted-foreground">
+ {logs.length === 0
+ ? t("syncNotifications.noLogs")
+ : t("syncNotifications.noLogsFiltered")}
+ </div>
+ ) : (
+ filteredLogs.map((log) => (
+ <div
+ key={log.id}
+ className="border rounded-lg p-4 space-y-3 hover:bg-accent/50 transition-colors"
+ >
+ {/* Header with status and sync type */}
+ <div className="flex items-start justify-between">
+ <div className="flex items-center gap-2">
+ {getStatusIcon(log.status)}
+ <div>
+ <div className="font-medium flex items-center gap-2">
+ {log.externalSyncName}
+ {log.isRead && log.status === "error" && (
+ <span className="text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground">
+ {t("syncNotifications.read")}
+ </span>
+ )}
+ </div>
+ <div className="text-sm text-muted-foreground flex items-center gap-1.5">
+ <Clock className="h-3.5 w-3.5" />
+ {formatDateTime(log.syncedAt)}
+ </div>
+ </div>
+ </div>
+ <div className="flex items-center gap-1.5 text-sm text-muted-foreground">
+ {getSyncTypeIcon(log.syncType)}
+ <span>
+ {log.syncType === "auto"
+ ? t("syncNotifications.syncTypeAuto")
+ : t("syncNotifications.syncTypeManual")}
+ </span>
+ </div>
+ </div>
+
+ {/* Status and changes */}
+ {log.status === "success" ? (
+ <div>
+ {hasChanges(log) ? (
+ <div className="flex flex-wrap gap-3 text-sm">
+ {log.shiftsCreated > 0 && (
+ <div className="flex items-center gap-1.5 text-green-700">
+ <span className="font-medium">
+ {t("syncNotifications.created", {
+ count: log.shiftsCreated,
+ })}
+ </span>
+ </div>
+ )}
+ {log.shiftsUpdated > 0 && (
+ <div className="flex items-center gap-1.5 text-blue-700">
+ <span className="font-medium">
+ {t("syncNotifications.updated", {
+ count: log.shiftsUpdated,
+ })}
+ </span>
+ </div>
+ )}
+ {log.shiftsDeleted > 0 && (
+ <div className="flex items-center gap-1.5 text-orange-700">
+ <span className="font-medium">
+ {t("syncNotifications.deleted", {
+ count: log.shiftsDeleted,
+ })}
+ </span>
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="text-sm text-muted-foreground">
+ {t("syncNotifications.noChanges")}
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="text-sm text-red-100 bg-red-950/90 p-3 rounded border border-red-800">
+ <div className="font-medium mb-1">
+ {t("syncNotifications.errorMessage")}:
+ </div>
+ <div className="text-red-200">{log.errorMessage}</div>
+ </div>
+ )}
+ </div>
+ ))
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/drizzle/0010_unusual_paibok.sql b/drizzle/0010_unusual_paibok.sql
new file mode 100644
index 0000000..6aea31d
--- /dev/null
+++ b/drizzle/0010_unusual_paibok.sql
@@ -0,0 +1,16 @@
+CREATE TABLE `sync_logs` (
+ `id` text PRIMARY KEY NOT NULL,
+ `calendar_id` text NOT NULL,
+ `external_sync_id` text NOT NULL,
+ `external_sync_name` text NOT NULL,
+ `status` text NOT NULL,
+ `error_message` text,
+ `shifts_created` integer DEFAULT 0 NOT NULL,
+ `shifts_updated` integer DEFAULT 0 NOT NULL,
+ `shifts_deleted` integer DEFAULT 0 NOT NULL,
+ `sync_type` text DEFAULT 'auto' NOT NULL,
+ `is_read` integer DEFAULT false NOT NULL,
+ `synced_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ FOREIGN KEY (`calendar_id`) REFERENCES `calendars`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`external_sync_id`) REFERENCES `external_syncs`(`id`) ON UPDATE no action ON DELETE cascade
+);
diff --git a/drizzle/meta/0010_snapshot.json b/drizzle/meta/0010_snapshot.json
new file mode 100644
index 0000000..467bff3
--- /dev/null
+++ b/drizzle/meta/0010_snapshot.json
@@ -0,0 +1,689 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "bdcccdcf-d9b5-4906-88d7-3d6012bdbfef",
+ "prevId": "fd73869c-1ddc-4926-af8e-b1551f13f226",
+ "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
+ },
+ "is_one_time_import": {
+ "name": "is_one_time_import",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "last_synced_at": {
+ "name": "last_synced_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "external_syncs_calendar_id_calendars_id_fk": {
+ "name": "external_syncs_calendar_id_calendars_id_fk",
+ "tableFrom": "external_syncs",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "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": {}
+ },
+ "sync_logs": {
+ "name": "sync_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_sync_id": {
+ "name": "external_sync_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_sync_name": {
+ "name": "external_sync_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shifts_created": {
+ "name": "shifts_created",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "shifts_updated": {
+ "name": "shifts_updated",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "shifts_deleted": {
+ "name": "shifts_deleted",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "sync_type": {
+ "name": "sync_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'auto'"
+ },
+ "is_read": {
+ "name": "is_read",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "synced_at": {
+ "name": "synced_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sync_logs_calendar_id_calendars_id_fk": {
+ "name": "sync_logs_calendar_id_calendars_id_fk",
+ "tableFrom": "sync_logs",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sync_logs_external_sync_id_external_syncs_id_fk": {
+ "name": "sync_logs_external_sync_id_external_syncs_id_fk",
+ "tableFrom": "sync_logs",
+ "tableTo": "external_syncs",
+ "columnsFrom": [
+ "external_sync_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "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 a5c834c..82610bc 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -71,6 +71,13 @@
"when": 1765071171359,
"tag": "0009_omniscient_magma",
"breakpoints": true
+ },
+ {
+ "idx": 10,
+ "version": "6",
+ "when": 1765059800909,
+ "tag": "0010_unusual_paibok",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/hooks/useSSEConnection.ts b/hooks/useSSEConnection.ts
index fffdc60..f6bb7f0 100644
--- a/hooks/useSSEConnection.ts
+++ b/hooks/useSSEConnection.ts
@@ -8,6 +8,7 @@ interface SSEConnectionOptions {
onPresetUpdate: () => void;
onNoteUpdate: () => void;
onStatsRefresh: () => void;
+ onSyncLogUpdate?: () => void;
isConnected: boolean;
setIsConnected: (connected: boolean) => void;
}
@@ -18,6 +19,7 @@ export function useSSEConnection({
onPresetUpdate,
onNoteUpdate,
onStatsRefresh,
+ onSyncLogUpdate,
isConnected,
setIsConnected,
}: SSEConnectionOptions) {
@@ -33,6 +35,7 @@ export function useSSEConnection({
const presetUpdateRef = useRef(onPresetUpdate);
const noteUpdateRef = useRef(onNoteUpdate);
const statsRefreshRef = useRef(onStatsRefresh);
+ const syncLogUpdateRef = useRef(onSyncLogUpdate);
const setIsConnectedRef = useRef(setIsConnected);
const tRef = useRef(t);
@@ -42,6 +45,7 @@ export function useSSEConnection({
presetUpdateRef.current = onPresetUpdate;
noteUpdateRef.current = onNoteUpdate;
statsRefreshRef.current = onStatsRefresh;
+ syncLogUpdateRef.current = onSyncLogUpdate;
setIsConnectedRef.current = setIsConnected;
tRef.current = t;
}, [
@@ -49,6 +53,7 @@ export function useSSEConnection({
onPresetUpdate,
onNoteUpdate,
onStatsRefresh,
+ onSyncLogUpdate,
setIsConnected,
t,
]);
@@ -159,6 +164,8 @@ export function useSSEConnection({
presetUpdateRef.current();
} else if (data.type === "note") {
noteUpdateRef.current();
+ } else if (data.type === "sync-log") {
+ syncLogUpdateRef.current?.();
}
lastSyncTimeRef.current = Date.now();
diff --git a/lib/auto-sync-service.ts b/lib/auto-sync-service.ts
index 352c165..c2f570c 100644
--- a/lib/auto-sync-service.ts
+++ b/lib/auto-sync-service.ts
@@ -147,19 +147,21 @@ class AutoSyncService {
console.log(`Executing auto-sync for ${syncId}`);
try {
- // Call sync function directly instead of HTTP fetch
- const stats = await syncExternalCalendar(syncId);
+ // Call sync function with "auto" type
+ const stats = await syncExternalCalendar(syncId, "auto");
if (stats) {
console.log(`Auto-sync completed for ${syncId}:`, stats);
- // Emit event to notify connected clients
- eventEmitter.emit("calendar-change", {
- type: "shift",
- action: "update",
- calendarId: stats.calendarId,
- data: { autoSync: true, syncId, stats },
- });
+ // Emit event to notify connected clients only if changes were made
+ if (stats.created > 0 || stats.updated > 0 || stats.deleted > 0) {
+ eventEmitter.emit("calendar-change", {
+ type: "shift",
+ action: "update",
+ calendarId: stats.calendarId,
+ data: { autoSync: true, syncId, stats },
+ });
+ }
}
} catch (error) {
console.error(`Auto-sync error for ${syncId}:`, error);
@@ -189,8 +191,8 @@ class AutoSyncService {
console.log(`Manually triggering sync for ${syncId}`);
try {
- // Call sync function directly instead of HTTP fetch
- const stats = await syncExternalCalendar(syncId);
+ // Call sync function with "manual" type
+ const stats = await syncExternalCalendar(syncId, "manual");
if (stats) {
console.log(`Manual sync completed for ${syncId}:`, stats);
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 38a23f0..eb287c1 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -125,6 +125,29 @@ export const calendarNotes = sqliteTable("calendar_notes", {
.default(sql`CURRENT_TIMESTAMP`),
});
+export const syncLogs = sqliteTable("sync_logs", {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ calendarId: text("calendar_id")
+ .notNull()
+ .references(() => calendars.id, { onDelete: "cascade" }),
+ externalSyncId: text("external_sync_id")
+ .notNull()
+ .references(() => externalSyncs.id, { onDelete: "cascade" }),
+ externalSyncName: text("external_sync_name").notNull(), // Denormalized for history
+ status: text("status").notNull(), // success, error
+ errorMessage: text("error_message"),
+ shiftsCreated: integer("shifts_created").notNull().default(0),
+ shiftsUpdated: integer("shifts_updated").notNull().default(0),
+ shiftsDeleted: integer("shifts_deleted").notNull().default(0),
+ syncType: text("sync_type").notNull().default("auto"), // auto, manual
+ isRead: integer("is_read", { mode: "boolean" }).notNull().default(false),
+ syncedAt: integer("synced_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+});
+
export type Calendar = typeof calendars.$inferSelect;
export type NewCalendar = typeof calendars.$inferInsert;
export type ExternalSync = typeof externalSyncs.$inferSelect;
@@ -135,3 +158,5 @@ export type ShiftPreset = typeof shiftPresets.$inferSelect;
export type NewShiftPreset = typeof shiftPresets.$inferInsert;
export type CalendarNote = typeof calendarNotes.$inferSelect;
export type NewCalendarNote = typeof calendarNotes.$inferInsert;
+export type SyncLog = typeof syncLogs.$inferSelect;
+export type NewSyncLog = typeof syncLogs.$inferInsert;
diff --git a/lib/event-emitter.ts b/lib/event-emitter.ts
index 96e45d4..ab4d578 100644
--- a/lib/event-emitter.ts
+++ b/lib/event-emitter.ts
@@ -34,12 +34,22 @@ class EventEmitter {
}
}
-// Global singleton instance
-export const eventEmitter = new EventEmitter();
+// Global singleton instance with HMR support
+// Use globalThis to persist across hot reloads in development
+const globalForEventEmitter = globalThis as unknown as {
+ eventEmitter: EventEmitter | undefined;
+};
+
+export const eventEmitter =
+ globalForEventEmitter.eventEmitter ?? new EventEmitter();
+
+if (process.env.NODE_ENV !== "production") {
+ globalForEventEmitter.eventEmitter = eventEmitter;
+}
// Event types
export type CalendarChangeEvent = {
- type: "shift" | "preset" | "note" | "calendar";
+ type: "shift" | "preset" | "note" | "calendar" | "sync-log";
action: "create" | "update" | "delete";
calendarId: string;
data?: unknown;
diff --git a/lib/external-calendar-utils.ts b/lib/external-calendar-utils.ts
index 7b0e2b5..310729a 100644
--- a/lib/external-calendar-utils.ts
+++ b/lib/external-calendar-utils.ts
@@ -328,3 +328,86 @@ export function splitMultiDayEvent(
return days;
}
+
+/**
+ * Creates a stable fingerprint for an event based on its content
+ * This is used because some calendar providers generate new UIDs on each request
+ * @param date - Event date
+ * @param startTime - Start time
+ * @param endTime - End time
+ * @param title - Event title
+ * @param dayIndex - For multi-day events, the day index
+ * @returns A stable fingerprint string
+ */
+export function createEventFingerprint(
+ date: Date,
+ startTime: string,
+ endTime: string,
+ title: string,
+ dayIndex?: number,
+ externalEventId?: string
+): string {
+ const dateStr = new Date(date).toISOString().split("T")[0];
+ const parts = [dateStr, startTime, endTime, title];
+ if (dayIndex !== undefined) {
+ parts.push(`day${dayIndex}`);
+ }
+ if (externalEventId) {
+ parts.push(externalEventId);
+ }
+ return parts.join("|");
+}
+
+/**
+ * Compares shift data to determine if an update is needed
+ * @param existing - The existing shift from database
+ * @param newData - The new shift data from external calendar
+ * @returns true if shifts are different and update is needed
+ */
+export function needsUpdate(
+ existing: {
+ date: Date;
+ startTime: string;
+ endTime: string;
+ title: string;
+ color: string;
+ notes: string | null;
+ isAllDay: boolean;
+ isSecondary: boolean;
+ },
+ newData: {
+ date: Date;
+ startTime: string;
+ endTime: string;
+ title: string;
+ color: string;
+ notes: string | null;
+ isAllDay: boolean;
+ isSecondary: boolean;
+ }
+): boolean {
+ // Compare date (convert to comparable format)
+ const existingDate = new Date(existing.date).toISOString().split("T")[0];
+ const newDate = new Date(newData.date).toISOString().split("T")[0];
+ if (existingDate !== newDate) return true;
+
+ // Compare time fields
+ if (existing.startTime !== newData.startTime) return true;
+ if (existing.endTime !== newData.endTime) return true;
+
+ // Compare title
+ if (existing.title !== newData.title) return true;
+
+ // Compare color
+ if (existing.color !== newData.color) return true;
+
+ // Compare notes (handle null values)
+ if ((existing.notes || null) !== (newData.notes || null)) return true;
+
+ // Compare boolean fields
+ if (existing.isAllDay !== newData.isAllDay) return true;
+ if (existing.isSecondary !== newData.isSecondary) return true;
+
+ // No differences found
+ return false;
+}
diff --git a/messages/de.json b/messages/de.json
index 094abc8..4083431 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -173,6 +173,7 @@
},
"externalSync": {
"manageTitle": "Externe Kalender verwalten",
+ "manage": "Verwalten",
"manageDescription": "Füge mehrere externe Kalender für diesen Kalender hinzu und verwalte sie",
"syncTypeICloud": "iCloud",
"syncTypeGoogle": "Google",
@@ -233,5 +234,30 @@
"autoSyncHint": "Wähle wie oft dieser Kalender automatisch synchronisiert werden soll",
"autoSyncManual": "Manuell",
"autoSync24hShort": "24 h"
+ },
+ "syncNotifications": {
+ "title": "Sync-Benachrichtigungen",
+ "noLogs": "Noch keine Synchronisierungen",
+ "noLogsFiltered": "Keine Synchronisierungen für diesen Filter",
+ "statusError": "Fehler",
+ "syncTypeAuto": "Automatisch",
+ "syncTypeManual": "Manuell",
+ "created": "{count} erstellt",
+ "updated": "{count} aktualisiert",
+ "deleted": "{count} gelöscht",
+ "noChanges": "Keine Änderungen",
+ "errorMessage": "Fehlermeldung",
+ "filterAll": "Alle anzeigen",
+ "filterSuccess": "Nur Erfolgreiche",
+ "filterError": "Nur Fehler",
+ "deleteAll": "Alle löschen",
+ "deleteConfirm": "Möchten Sie wirklich alle Sync-Logs löschen?",
+ "deleteSuccess": "Sync-Logs erfolgreich gelöscht",
+ "deleteError": "Fehler beim Löschen der Sync-Logs",
+ "hasErrors": "Fehler vorhanden",
+ "markAsRead": "Als gelesen markieren",
+ "markedAsRead": "Fehler als gelesen markiert",
+ "markAsReadError": "Fehler beim Markieren als gelesen",
+ "read": "Gelesen"
}
}
diff --git a/messages/en.json b/messages/en.json
index 2095654..56ee275 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -173,6 +173,7 @@
},
"externalSync": {
"manageTitle": "Manage External Calendars",
+ "manage": "Manage",
"manageDescription": "Add and manage multiple external calendars for this calendar",
"syncTypeICloud": "iCloud",
"syncTypeGoogle": "Google",
@@ -233,5 +234,30 @@
"autoSyncHint": "Choose how often this calendar should automatically sync",
"autoSyncManual": "Manual",
"autoSync24hShort": "24 h"
+ },
+ "syncNotifications": {
+ "title": "Sync Notifications",
+ "noLogs": "No syncs yet",
+ "noLogsFiltered": "No syncs match this filter",
+ "statusError": "Error",
+ "syncTypeAuto": "Automatic",
+ "syncTypeManual": "Manual",
+ "created": "{count} created",
+ "updated": "{count} updated",
+ "deleted": "{count} deleted",
+ "noChanges": "No changes",
+ "errorMessage": "Error message",
+ "filterAll": "Show all",
+ "filterSuccess": "Success only",
+ "filterError": "Errors only",
+ "deleteAll": "Delete all",
+ "deleteConfirm": "Are you sure you want to delete all sync logs?",
+ "deleteSuccess": "Sync logs deleted successfully",
+ "deleteError": "Failed to delete sync logs",
+ "hasErrors": "Has errors",
+ "markAsRead": "Mark as read",
+ "markedAsRead": "Errors marked as read",
+ "markAsReadError": "Failed to mark as read",
+ "read": "Read"
}
}