diff --git a/app/agenda/page.tsx b/app/agenda/page.tsx index b47ecc5..43da248 100644 --- a/app/agenda/page.tsx +++ b/app/agenda/page.tsx @@ -557,6 +557,69 @@ export default async function CalendarPage() { } } + // Auto-sync Infomaniak calendars if needed (background, don't block page load) + const infomaniakSyncConfigs = await prisma.calendarSync.findMany({ + where: { + provider: 'infomaniak', + syncEnabled: true, + calendar: { + userId: session?.user?.id || '' + } + } + }); + + console.log(`[AGENDA] Found ${infomaniakSyncConfigs.length} Infomaniak sync configs`); + + // Trigger sync for Infomaniak calendars that need it (async, don't wait) + for (const syncConfig of infomaniakSyncConfigs) { + const minutesSinceLastSync = syncConfig.lastSyncAt + ? (Date.now() - syncConfig.lastSyncAt.getTime()) / (1000 * 60) + : Infinity; + + // Sync if never synced, or if enough time has passed (based on syncFrequency) + const needsSync = !syncConfig.lastSyncAt || + minutesSinceLastSync >= syncConfig.syncFrequency; + + console.log(`[AGENDA] Infomaniak sync config ${syncConfig.id}: lastSyncAt=${syncConfig.lastSyncAt}, minutesSinceLastSync=${minutesSinceLastSync.toFixed(1)}, needsSync=${needsSync}, syncFrequency=${syncConfig.syncFrequency}`); + + if (needsSync) { + console.log(`[AGENDA] Triggering background sync for Infomaniak calendar ${syncConfig.id}`); + // Trigger sync in background (don't await to avoid blocking page load) + // The sync will update the database, and the next page load will show the events + // Use forceSync=true because we've already checked that sync is needed + import('@/lib/services/caldav-sync').then(({ syncInfomaniakCalendar }) => { + syncInfomaniakCalendar(syncConfig.id, true).then((result) => { + console.log(`[AGENDA] Infomaniak sync completed:`, { + calendarSyncId: syncConfig.id, + calendarId: syncConfig.calendarId, + synced: result.synced, + created: result.created, + updated: result.updated, + deleted: result.deleted, + }); + + // Verify events were created by checking the database + prisma.event.count({ + where: { calendarId: syncConfig.calendarId } + }).then((count) => { + console.log(`[AGENDA] Total events in calendar ${syncConfig.calendarId} after sync: ${count}`); + }).catch((err) => { + console.error('[AGENDA] Error counting events:', err); + }); + }).catch((error) => { + console.error('[AGENDA] Background sync failed for Infomaniak calendar', { + calendarSyncId: syncConfig.id, + calendarId: syncConfig.calendarId, + error: error instanceof Error ? error.message : String(error), + stack: error instanceof Error ? error.stack : undefined, + }); + }); + }); + } else { + console.log(`[AGENDA] Infomaniak sync skipped - too soon since last sync (${minutesSinceLastSync.toFixed(1)} min < ${syncConfig.syncFrequency} min)`); + } + } + // Auto-sync Microsoft calendars if needed (background, don't block page load) const microsoftSyncConfigs = await prisma.calendarSync.findMany({ where: {