NeahStable/app/api/events/route.ts
2026-01-15 17:41:10 +01:00

316 lines
9.9 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/options";
import { prisma } from "@/lib/prisma";
import { updateMicrosoftEvent, deleteMicrosoftEvent } from "@/lib/services/microsoft-calendar-sync";
import { logger } from "@/lib/logger";
import { invalidateCalendarCache } from "@/lib/redis";
// Helper function to check if user can manage events in a mission calendar
async function canManageMissionCalendar(userId: string, calendarId: string): Promise<boolean> {
const calendar = await prisma.calendar.findUnique({
where: { id: calendarId },
include: {
mission: {
include: {
missionUsers: true
}
}
}
});
// If calendar is not linked to a mission, allow (it's a regular calendar)
if (!calendar?.missionId || !calendar.mission) {
return true;
}
const mission = calendar.mission;
// Check if user is the creator of the mission
if (mission.creatorId === userId) {
return true;
}
// Check if user is a gardien-temps (time guardian) for this mission
const isGardienTemps = mission.missionUsers.some(
(mu) => mu.userId === userId && mu.role === 'gardien-temps'
);
return isGardienTemps;
}
export async function POST(req: NextRequest) {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
}
try {
const { title, description, start, end, allDay, location, calendarId } = await req.json();
// Validation
if (!title || !start || !end || !calendarId) {
return NextResponse.json(
{ error: "Titre, début, fin et calendrier sont requis" },
{ status: 400 }
);
}
// Verify calendar ownership
const calendar = await prisma.calendar.findFirst({
where: {
id: calendarId,
userId: session.user.id,
},
});
if (!calendar) {
return NextResponse.json(
{ error: "Calendrier non trouvé ou non autorisé" },
{ status: 404 }
);
}
// If calendar is linked to a mission, check permissions
if (calendar.missionId) {
const canManage = await canManageMissionCalendar(session.user.id, calendarId);
if (!canManage) {
return NextResponse.json(
{ error: "Seul le créateur de la mission ou le gardien-temps peut créer des événements" },
{ status: 403 }
);
}
}
// Create event with all required fields
const event = await prisma.event.create({
data: {
title,
description: description || null,
start: new Date(start),
end: new Date(end),
isAllDay: allDay || false,
location: location || null,
calendarId,
userId: session.user.id,
},
});
// Invalidate calendar cache so the new event appears immediately
try {
await invalidateCalendarCache(session.user.id);
logger.debug('[EVENTS] Invalidated calendar cache after event creation', {
eventId: event.id,
calendarId,
userId: session.user.id,
});
} catch (cacheError) {
// Log but don't fail the request if cache invalidation fails
logger.error('[EVENTS] Error invalidating calendar cache', {
error: cacheError instanceof Error ? cacheError.message : String(cacheError),
});
}
console.log("Created event:", event);
return NextResponse.json(event, { status: 201 });
} catch (error) {
console.error("Erreur lors de la création de l'événement:", error);
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
}
}
export async function PUT(req: NextRequest) {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
}
try {
const data = await req.json();
console.log("Received event update data:", data);
const { id, title, description, start, end, allDay, location, calendarId } = data;
// Validation
if (!id || !title || !start || !end || !calendarId) {
console.log("Validation failed. Missing fields:", {
id: !id,
title: !title,
start: !start,
end: !end,
calendarId: !calendarId
});
return NextResponse.json(
{ error: "ID, titre, début, fin et calendrier sont requis" },
{ status: 400 }
);
}
// Verify calendar ownership and get event with sync config
const calendar = await prisma.calendar.findFirst({
where: {
id: calendarId,
userId: session.user.id,
},
include: {
events: {
where: {
id
}
},
syncConfig: {
include: {
mailCredential: true
}
}
}
});
console.log("Found calendar:", calendar);
if (!calendar || calendar.events.length === 0) {
console.log("Calendar or event not found:", {
calendarFound: !!calendar,
eventsFound: calendar?.events.length
});
return NextResponse.json(
{ error: "Événement non trouvé ou non autorisé" },
{ status: 404 }
);
}
// If calendar is linked to a mission, check permissions
if (calendar.missionId) {
const canManage = await canManageMissionCalendar(session.user.id, calendarId);
if (!canManage) {
return NextResponse.json(
{ error: "Seul le créateur de la mission ou le gardien-temps peut modifier des événements" },
{ status: 403 }
);
}
}
const existingEvent = calendar.events[0];
// Update event in local database
const event = await prisma.event.update({
where: { id },
data: {
title,
description,
start: new Date(start),
end: new Date(end),
isAllDay: allDay || false,
location,
calendarId,
},
});
// Invalidate calendar cache so the updated event appears immediately
try {
await invalidateCalendarCache(session.user.id);
logger.debug('[EVENTS] Invalidated calendar cache after event update', {
eventId: event.id,
calendarId,
userId: session.user.id,
});
} catch (cacheError) {
// Log but don't fail the request if cache invalidation fails
logger.error('[EVENTS] Error invalidating calendar cache', {
error: cacheError instanceof Error ? cacheError.message : String(cacheError),
});
}
// If event has externalEventId and calendar has Microsoft sync, update Microsoft too
if (existingEvent.externalEventId && calendar.syncConfig && calendar.syncConfig.provider === 'microsoft' && calendar.syncConfig.syncEnabled) {
const syncConfig = calendar.syncConfig;
const mailCredential = syncConfig.mailCredential;
if (mailCredential && mailCredential.use_oauth && mailCredential.refresh_token) {
try {
// Prepare Microsoft event data
const startDate = new Date(start);
const endDate = new Date(end);
// Microsoft Graph API expects timezone-aware dates
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const microsoftEventData: any = {
subject: title,
};
if (allDay) {
// For all-day events, Microsoft uses date format
microsoftEventData.isAllDay = true;
microsoftEventData.start = {
date: startDate.toISOString().split('T')[0],
timeZone: 'UTC'
};
microsoftEventData.end = {
date: endDate.toISOString().split('T')[0],
timeZone: 'UTC'
};
} else {
// For timed events, use dateTime
microsoftEventData.isAllDay = false;
microsoftEventData.start = {
dateTime: startDate.toISOString(),
timeZone: timeZone
};
microsoftEventData.end = {
dateTime: endDate.toISOString(),
timeZone: timeZone
};
}
if (description) {
microsoftEventData.body = {
contentType: 'HTML',
content: description
};
}
if (location) {
microsoftEventData.location = {
displayName: location
};
}
// Update Microsoft event
await updateMicrosoftEvent(
session.user.id,
mailCredential.email,
syncConfig.externalCalendarId || '',
existingEvent.externalEventId,
microsoftEventData
);
logger.info('Successfully synced event update to Microsoft', {
eventId: id,
externalEventId: existingEvent.externalEventId,
email: mailCredential.email,
});
} catch (syncError: any) {
// Log error but don't fail the request - local update succeeded
// Don't disable syncConfig for permission errors (403) - user just needs to re-authenticate
const isPermissionError = syncError.response?.status === 403;
logger.error('Failed to sync event update to Microsoft', {
eventId: id,
externalEventId: existingEvent.externalEventId,
error: syncError instanceof Error ? syncError.message : String(syncError),
isPermissionError,
suggestion: isPermissionError ? 'User needs to re-authenticate with Calendars.ReadWrite scope' : undefined,
});
}
}
}
console.log("Updated event:", event);
return NextResponse.json(event);
} catch (error) {
console.error("Erreur lors de la mise à jour de l'événement:", error);
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
}
}