diff --git a/server/routes.ts b/server/routes.ts index 437e355..31793dc 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -830,7 +830,11 @@ export async function registerRoutes(app: Express): Promise { // Calcola fine settimana (weekStart + 6 giorni) const weekEndDate = format(addDays(parsedWeekStart, 6), "yyyy-MM-dd"); - // Ottieni tutti i siti attivi della sede + // Timestamp per filtro contratti + const weekStartTimestampForContract = new Date(weekStartDate); + const weekEndTimestampForContract = new Date(weekEndDate); + + // Ottieni tutti i siti attivi della sede con contratto valido nelle date della settimana const activeSites = await db .select() .from(sites) @@ -838,7 +842,11 @@ export async function registerRoutes(app: Express): Promise { .where( and( eq(sites.isActive, true), - eq(sites.location, location as any) + eq(sites.location, location as any), + // Contratto deve essere valido in almeno un giorno della settimana + // contractStartDate <= weekEnd AND contractEndDate >= weekStart + lte(sites.contractStartDate, weekEndTimestampForContract), + gte(sites.contractEndDate, weekStartTimestampForContract) ) ); @@ -992,11 +1000,38 @@ export async function registerRoutes(app: Express): Promise { }); } + // Calcola guardie totali necessarie per l'intera settimana + let totalGuardsNeededForWeek = 0; + let totalGuardsAssignedForWeek = 0; + + // Set per tracciare guardie uniche assegnate nella settimana + const uniqueGuardsInWeek = new Set(); + + for (const day of weekData) { + for (const siteData of day.sites) { + // Somma guardie necessarie (giĆ  calcolate per sito/giorno) + totalGuardsNeededForWeek += (siteData.guardsAssigned + siteData.missingGuards); + + // Traccia guardie uniche + for (const guard of siteData.guards) { + uniqueGuardsInWeek.add(guard.guardId); + } + } + } + + totalGuardsAssignedForWeek = uniqueGuardsInWeek.size; + const totalGuardsMissingForWeek = Math.max(0, totalGuardsNeededForWeek - totalGuardsAssignedForWeek); + res.json({ weekStart: weekStartDate, weekEnd: weekEndDate, location, days: weekData, + summary: { + totalGuardsNeeded: totalGuardsNeededForWeek, + totalGuardsAssigned: totalGuardsAssignedForWeek, + totalGuardsMissing: totalGuardsMissingForWeek, + } }); } catch (error) { console.error("Error fetching general planning:", error);