Compare commits

..

No commits in common. "main" and "v1.0.49" have entirely different histories.

34 changed files with 346 additions and 2655 deletions

View File

@ -19,10 +19,6 @@ externalPort = 80
localPort = 33035 localPort = 33035
externalPort = 3001 externalPort = 3001
[[ports]]
localPort = 40417
externalPort = 8000
[[ports]] [[ports]]
localPort = 41295 localPort = 41295
externalPort = 5173 externalPort = 5173
@ -39,10 +35,6 @@ externalPort = 4200
localPort = 42175 localPort = 42175
externalPort = 3002 externalPort = 3002
[[ports]]
localPort = 42187
externalPort = 6800
[[ports]] [[ports]]
localPort = 43169 localPort = 43169
externalPort = 5000 externalPort = 5000

View File

@ -30,7 +30,6 @@ import PlanningMobile from "@/pages/planning-mobile";
import MyShiftsFixed from "@/pages/my-shifts-fixed"; import MyShiftsFixed from "@/pages/my-shifts-fixed";
import MyShiftsMobile from "@/pages/my-shifts-mobile"; import MyShiftsMobile from "@/pages/my-shifts-mobile";
import SitePlanningView from "@/pages/site-planning-view"; import SitePlanningView from "@/pages/site-planning-view";
import WeeklyGuards from "@/pages/weekly-guards";
function Router() { function Router() {
const { isAuthenticated, isLoading } = useAuth(); const { isAuthenticated, isLoading } = useAuth();
@ -58,7 +57,6 @@ function Router() {
<Route path="/my-shifts-fixed" component={MyShiftsFixed} /> <Route path="/my-shifts-fixed" component={MyShiftsFixed} />
<Route path="/my-shifts-mobile" component={MyShiftsMobile} /> <Route path="/my-shifts-mobile" component={MyShiftsMobile} />
<Route path="/site-planning-view" component={SitePlanningView} /> <Route path="/site-planning-view" component={SitePlanningView} />
<Route path="/weekly-guards" component={WeeklyGuards} />
<Route path="/reports" component={Reports} /> <Route path="/reports" component={Reports} />
<Route path="/notifications" component={Notifications} /> <Route path="/notifications" component={Notifications} />
<Route path="/users" component={Users} /> <Route path="/users" component={Users} />

View File

@ -12,11 +12,6 @@ import {
Car, Car,
Briefcase, Briefcase,
Navigation, Navigation,
ChevronDown,
FileText,
FolderKanban,
Building2,
Wrench,
} from "lucide-react"; } from "lucide-react";
import { Link, useLocation } from "wouter"; import { Link, useLocation } from "wouter";
import { import {
@ -28,31 +23,15 @@ import {
SidebarMenu, SidebarMenu,
SidebarMenuButton, SidebarMenuButton,
SidebarMenuItem, SidebarMenuItem,
SidebarMenuSub,
SidebarMenuSubItem,
SidebarMenuSubButton,
SidebarHeader, SidebarHeader,
SidebarFooter, SidebarFooter,
} from "@/components/ui/sidebar"; } from "@/components/ui/sidebar";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { useAuth } from "@/hooks/useAuth"; import { useAuth } from "@/hooks/useAuth";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { ThemeToggle } from "@/components/theme-toggle"; import { ThemeToggle } from "@/components/theme-toggle";
interface MenuItem { const menuItems = [
title: string;
url?: string;
icon: any;
roles: string[];
items?: MenuItem[];
}
const menuItems: MenuItem[] = [
{ {
title: "Dashboard", title: "Dashboard",
url: "/", url: "/",
@ -60,123 +39,100 @@ const menuItems: MenuItem[] = [
roles: ["admin", "coordinator", "guard", "client"], roles: ["admin", "coordinator", "guard", "client"],
}, },
{ {
title: "Planning", title: "Turni",
icon: FolderKanban, url: "/shifts",
roles: ["admin", "coordinator"], icon: Calendar,
items: [ roles: ["admin", "coordinator", "guard"],
{
title: "Fissi",
url: "/general-planning",
icon: Calendar,
roles: ["admin", "coordinator"],
},
{
title: "Mobili",
url: "/planning-mobile",
icon: Navigation,
roles: ["admin", "coordinator"],
},
{
title: "Vista",
url: "/service-planning",
icon: ClipboardList,
roles: ["admin", "coordinator"],
},
{
title: "Guardie Settimanale",
url: "/weekly-guards",
icon: Users,
roles: ["admin", "coordinator"],
},
],
}, },
{ {
title: "Scadenziario", title: "Pianificazione",
url: "/advanced-planning", url: "/planning",
icon: ClipboardList,
roles: ["admin", "coordinator"],
},
{
title: "Pianificazione Operativa",
url: "/operational-planning",
icon: Calendar, icon: Calendar,
roles: ["admin", "coordinator"], roles: ["admin", "coordinator"],
}, },
{ {
title: "Anagrafiche", title: "Planning Fissi",
icon: Building2, url: "/general-planning",
icon: BarChart3,
roles: ["admin", "coordinator"], roles: ["admin", "coordinator"],
items: [
{
title: "Guardie",
url: "/guards",
icon: Users,
roles: ["admin", "coordinator"],
},
{
title: "Siti",
url: "/sites",
icon: MapPin,
roles: ["admin", "coordinator", "client"],
},
{
title: "Clienti",
url: "/customers",
icon: Briefcase,
roles: ["admin", "coordinator"],
},
{
title: "Automezzi",
url: "/vehicles",
icon: Car,
roles: ["admin", "coordinator"],
},
],
}, },
{ {
title: "Tipologia", title: "Planning Mobile",
icon: Wrench, url: "/planning-mobile",
icon: Navigation,
roles: ["admin", "coordinator"],
},
{
title: "Planning di Servizio",
url: "/service-planning",
icon: ClipboardList,
roles: ["admin", "coordinator"],
},
{
title: "Gestione Pianificazioni",
url: "/advanced-planning",
icon: ClipboardList,
roles: ["admin", "coordinator"],
},
{
title: "Guardie",
url: "/guards",
icon: Users,
roles: ["admin", "coordinator"],
},
{
title: "Siti",
url: "/sites",
icon: MapPin,
roles: ["admin", "coordinator", "client"],
},
{
title: "Clienti",
url: "/customers",
icon: Briefcase,
roles: ["admin", "coordinator"],
},
{
title: "Servizi",
url: "/services",
icon: Briefcase,
roles: ["admin", "coordinator"],
},
{
title: "Parco Automezzi",
url: "/vehicles",
icon: Car,
roles: ["admin", "coordinator"], roles: ["admin", "coordinator"],
items: [
{
title: "Servizi",
url: "/services",
icon: Briefcase,
roles: ["admin", "coordinator"],
},
{
title: "Contratti",
url: "/parameters",
icon: Settings,
roles: ["admin", "coordinator"],
},
],
}, },
{ {
title: "Report", title: "Report",
url: "/reports",
icon: BarChart3, icon: BarChart3,
roles: ["admin", "coordinator", "client"], roles: ["admin", "coordinator", "client"],
items: [
{
title: "Report Amministrativo",
url: "/reports",
icon: FileText,
roles: ["admin", "coordinator", "client"],
},
],
}, },
{ {
title: "Utilità", title: "Notifiche",
icon: Settings, url: "/notifications",
icon: Bell,
roles: ["admin", "coordinator", "guard"], roles: ["admin", "coordinator", "guard"],
items: [ },
{ {
title: "Utenti", title: "Utenti",
url: "/users", url: "/users",
icon: UserCog, icon: UserCog,
roles: ["admin"], roles: ["admin"],
}, },
{ {
title: "Notifiche", title: "Parametri",
url: "/notifications", url: "/parameters",
icon: Bell, icon: Settings,
roles: ["admin", "coordinator", "guard"], roles: ["admin", "coordinator"],
},
],
}, },
]; ];
@ -184,78 +140,9 @@ export function AppSidebar() {
const { user } = useAuth(); const { user } = useAuth();
const [location] = useLocation(); const [location] = useLocation();
const filterMenuItems = (items: MenuItem[]): MenuItem[] => { const filteredItems = menuItems.filter(
if (!user) return []; (item) => user && item.roles.includes(user.role)
);
return items.filter((item) => {
const hasRole = item.roles.includes(user.role);
if (!hasRole) return false;
if (item.items) {
item.items = filterMenuItems(item.items);
return item.items.length > 0;
}
return true;
});
};
const filteredItems = filterMenuItems(menuItems);
const renderMenuItem = (item: MenuItem) => {
// Menu item con sottomenu
if (item.items && item.items.length > 0) {
const isAnySubItemActive = item.items.some((subItem) => location === subItem.url);
return (
<Collapsible key={item.title} defaultOpen={isAnySubItemActive} className="group/collapsible">
<SidebarMenuItem>
<CollapsibleTrigger asChild>
<SidebarMenuButton data-testid={`menu-${item.title.toLowerCase()}`}>
<item.icon className="h-4 w-4" />
<span>{item.title}</span>
<ChevronDown className="ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-180" />
</SidebarMenuButton>
</CollapsibleTrigger>
<CollapsibleContent>
<SidebarMenuSub>
{item.items.map((subItem) => (
<SidebarMenuSubItem key={subItem.title}>
<SidebarMenuSubButton
asChild
isActive={location === subItem.url}
data-testid={`link-${subItem.title.toLowerCase().replace(/\s+/g, '-')}`}
>
<Link href={subItem.url!}>
<subItem.icon className="h-4 w-4" />
<span>{subItem.title}</span>
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
))}
</SidebarMenuSub>
</CollapsibleContent>
</SidebarMenuItem>
</Collapsible>
);
}
// Menu item semplice
return (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton
asChild
isActive={location === item.url}
data-testid={`link-${item.title.toLowerCase().replace(/\s+/g, '-')}`}
>
<Link href={item.url!}>
<item.icon className="h-4 w-4" />
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
);
};
return ( return (
<Sidebar> <Sidebar>
@ -274,7 +161,20 @@ export function AppSidebar() {
<SidebarGroupLabel>Menu Principale</SidebarGroupLabel> <SidebarGroupLabel>Menu Principale</SidebarGroupLabel>
<SidebarGroupContent> <SidebarGroupContent>
<SidebarMenu> <SidebarMenu>
{filteredItems.map(renderMenuItem)} {filteredItems.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton
asChild
isActive={location === item.url}
data-testid={`link-${item.title.toLowerCase()}`}
>
<Link href={item.url}>
<item.icon className="h-4 w-4" />
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu> </SidebarMenu>
</SidebarGroupContent> </SidebarGroupContent>
</SidebarGroup> </SidebarGroup>

View File

@ -8,7 +8,7 @@ import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { ChevronLeft, ChevronRight, Calendar, MapPin, Users, AlertTriangle, Car, Edit, CheckCircle2, Plus, Trash2, Clock, Copy, Circle } from "lucide-react"; import { ChevronLeft, ChevronRight, Calendar, MapPin, Users, AlertTriangle, Car, Edit, CheckCircle2, Plus, Trash2, Clock } from "lucide-react";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
import { import {
@ -85,14 +85,14 @@ interface GeneralPlanningResponse {
} }
// Helper per formattare orario in formato italiano 24h (HH:MM) // Helper per formattare orario in formato italiano 24h (HH:MM)
// IMPORTANTE: Gli orari nel DB sono UTC, visualizzali in timezone Europe/Rome // IMPORTANTE: usa timeZone UTC per evitare shift di +2 ore
const formatTime = (dateString: string) => { const formatTime = (dateString: string) => {
const date = new Date(dateString); const date = new Date(dateString);
return date.toLocaleTimeString("it-IT", { return date.toLocaleTimeString("it-IT", {
hour: "2-digit", hour: "2-digit",
minute: "2-digit", minute: "2-digit",
hour12: false, hour12: false,
timeZone: "Europe/Rome" // Converti da UTC a Italy time timeZone: "UTC" // Evita conversione timezone locale (+2h in Italia)
}); });
}; };
@ -117,7 +117,6 @@ export default function GeneralPlanning() {
const [consecutiveDays, setConsecutiveDays] = useState<number>(1); const [consecutiveDays, setConsecutiveDays] = useState<number>(1);
const [showOvertimeGuards, setShowOvertimeGuards] = useState<boolean>(false); const [showOvertimeGuards, setShowOvertimeGuards] = useState<boolean>(false);
const [ccnlConfirmation, setCcnlConfirmation] = useState<{ message: string; data: any } | null>(null); const [ccnlConfirmation, setCcnlConfirmation] = useState<{ message: string; data: any } | null>(null);
const [showCopyWeekConfirmation, setShowCopyWeekConfirmation] = useState<boolean>(false);
// Query per dati planning settimanale // Query per dati planning settimanale
const { data: planningData, isLoading } = useQuery<GeneralPlanningResponse>({ const { data: planningData, isLoading } = useQuery<GeneralPlanningResponse>({
@ -276,54 +275,6 @@ export default function GeneralPlanning() {
}, },
}); });
// Mutation per copiare turni settimanali
const copyWeekMutation = useMutation({
mutationFn: async () => {
return apiRequest("POST", "/api/shift-assignments/copy-week", {
weekStart: format(weekStart, "yyyy-MM-dd"),
location: selectedLocation,
});
},
onSuccess: async (response: any) => {
const data = await response.json();
toast({
title: "Settimana copiata!",
description: `${data.copiedShifts} turni e ${data.copiedAssignments} assegnazioni copiate nella settimana successiva`,
});
// Invalida cache e naviga alla settimana successiva
await queryClient.invalidateQueries({ queryKey: ["/api/general-planning"] });
setWeekStart(addWeeks(weekStart, 1)); // Naviga alla settimana copiata
setShowCopyWeekConfirmation(false);
},
onError: (error: any) => {
let errorMessage = "Impossibile copiare la settimana";
if (error.message) {
const match = error.message.match(/^(\d+):\s*(.+)$/);
if (match) {
try {
const parsed = JSON.parse(match[2]);
errorMessage = parsed.message || errorMessage;
} catch {
errorMessage = match[2];
}
} else {
errorMessage = error.message;
}
}
toast({
title: "Errore Copia Settimana",
description: errorMessage,
variant: "destructive",
});
setShowCopyWeekConfirmation(false);
},
});
// Handler per submit form assegnazione guardia // Handler per submit form assegnazione guardia
const handleAssignGuard = () => { const handleAssignGuard = () => {
if (!selectedCell || !selectedGuardId) return; if (!selectedCell || !selectedGuardId) return;
@ -407,7 +358,7 @@ export default function GeneralPlanning() {
</div> </div>
{/* Navigazione settimana */} {/* Navigazione settimana */}
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2">
<Button <Button
variant="outline" variant="outline"
size="icon" size="icon"
@ -434,16 +385,6 @@ export default function GeneralPlanning() {
> >
<ChevronRight className="h-4 w-4" /> <ChevronRight className="h-4 w-4" />
</Button> </Button>
<Button
variant="default"
onClick={() => setShowCopyWeekConfirmation(true)}
disabled={isLoading || !planningData || copyWeekMutation.isPending}
data-testid="button-copy-week"
>
<Copy className="h-4 w-4 mr-2" />
{copyWeekMutation.isPending ? "Copia in corso..." : "Copia Turno Settimanale"}
</Button>
</div> </div>
{/* Info settimana */} {/* Info settimana */}
@ -717,19 +658,19 @@ export default function GeneralPlanning() {
})()} })()}
</div> </div>
{/* Select guardia (tutte, evidenziate in rosso se impegnate) */} {/* Select guardia disponibile */}
{(() => { {(() => {
// Mostra TUTTE le guardie, ma filtra solo per ore ordinarie/straordinario // Filtra guardie: mostra solo con ore ordinarie se toggle è off
const filteredGuards = availableGuards?.filter(g => const filteredGuards = availableGuards?.filter(g =>
showOvertimeGuards || !g.requiresOvertime g.isAvailable && (showOvertimeGuards || !g.requiresOvertime)
) || []; ) || [];
const hasOvertimeGuards = availableGuards?.some(g => g.requiresOvertime) || false; const hasOvertimeGuards = availableGuards?.some(g => g.requiresOvertime && g.isAvailable) || false;
return ( return (
<div className="space-y-2"> <div className="space-y-2">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<Label htmlFor="guard-select">Guardia</Label> <Label htmlFor="guard-select">Guardia Disponibile</Label>
{!isLoadingGuards && hasOvertimeGuards && ( {!isLoadingGuards && hasOvertimeGuards && (
<Button <Button
variant="outline" variant="outline"
@ -758,20 +699,15 @@ export default function GeneralPlanning() {
{filteredGuards.length > 0 ? ( {filteredGuards.length > 0 ? (
filteredGuards.map((guard) => ( filteredGuards.map((guard) => (
<SelectItem key={guard.guardId} value={guard.guardId}> <SelectItem key={guard.guardId} value={guard.guardId}>
<div className={`flex items-center gap-1.5 ${guard.isAvailable ? "" : "text-destructive font-medium"}`}> {guard.guardName} ({guard.badgeNumber}) - {guard.ordinaryHoursRemaining}h ord.
{!guard.isAvailable && <Circle className="h-3 w-3 fill-current" />} {guard.requiresOvertime && ` + ${guard.overtimeHoursRemaining}h strao.`}
<span> {guard.requiresOvertime && " 🔸"}
{guard.guardName} ({guard.badgeNumber}) - {guard.ordinaryHoursRemaining}h ord.
{guard.requiresOvertime && ` + ${guard.overtimeHoursRemaining}h strao.`}
{guard.requiresOvertime && " 🔸"}
</span>
</div>
</SelectItem> </SelectItem>
)) ))
) : ( ) : (
<SelectItem value="no-guards" disabled> <SelectItem value="no-guards" disabled>
{showOvertimeGuards {showOvertimeGuards
? "Nessuna guardia" ? "Nessuna guardia disponibile"
: "Nessuna guardia con ore ordinarie (prova 'Mostra Straordinario')"} : "Nessuna guardia con ore ordinarie (prova 'Mostra Straordinario')"}
</SelectItem> </SelectItem>
)} )}
@ -779,7 +715,7 @@ export default function GeneralPlanning() {
</Select> </Select>
{filteredGuards.length === 0 && !showOvertimeGuards && hasOvertimeGuards && ( {filteredGuards.length === 0 && !showOvertimeGuards && hasOvertimeGuards && (
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Alcune guardie richiedono straordinario. Clicca "Mostra Straordinario" per vederle. Alcune guardie disponibili richiedono straordinario. Clicca "Mostra Straordinario" per vederle.
</p> </p>
)} )}
{filteredGuards.length > 0 && selectedGuardId && ( {filteredGuards.length > 0 && selectedGuardId && (
@ -1052,60 +988,6 @@ export default function GeneralPlanning() {
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
{/* Dialog conferma copia settimana */}
<AlertDialog open={showCopyWeekConfirmation} onOpenChange={setShowCopyWeekConfirmation}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<Copy className="h-5 w-5" />
Copia Turno Settimanale
</AlertDialogTitle>
<AlertDialogDescription asChild>
<div className="space-y-3">
<p className="text-foreground font-medium">
Vuoi copiare tutti i turni della settimana corrente nella settimana successiva?
</p>
{planningData && (
<div className="space-y-2 bg-muted/30 p-3 rounded-md">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Settimana corrente:</span>
<span className="font-medium">
{format(new Date(planningData.weekStart), "dd MMM", { locale: it })} -{" "}
{format(new Date(planningData.weekEnd), "dd MMM yyyy", { locale: it })}
</span>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Verrà copiata in:</span>
<span className="font-medium">
{format(addWeeks(new Date(planningData.weekStart), 1), "dd MMM", { locale: it })} -{" "}
{format(addWeeks(new Date(planningData.weekEnd), 1), "dd MMM yyyy", { locale: it })}
</span>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Sede:</span>
<span className="font-medium">{formatLocation(selectedLocation)}</span>
</div>
</div>
)}
<p className="text-sm text-muted-foreground">
Tutti i turni e le assegnazioni guardie verranno duplicati con le stesse caratteristiche (orari, dotazioni, veicoli).
</p>
</div>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel data-testid="button-cancel-copy-week">Annulla</AlertDialogCancel>
<AlertDialogAction
onClick={() => copyWeekMutation.mutate()}
data-testid="button-confirm-copy-week"
disabled={copyWeekMutation.isPending}
>
{copyWeekMutation.isPending ? "Copia in corso..." : "Conferma Copia"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div> </div>
); );
} }

View File

@ -159,31 +159,21 @@ export default function MyShiftsFixed() {
</div> </div>
) : ( ) : (
dayShifts.map((shift) => { dayShifts.map((shift) => {
// Parsing sicuro orari (DB in UTC → visualizza in Europe/Rome) // Parsing sicuro orari
let startTime = "N/A"; let startTime = "N/A";
let endTime = "N/A"; let endTime = "N/A";
if (shift.plannedStartTime) { if (shift.plannedStartTime) {
const parsedStart = new Date(shift.plannedStartTime); const parsedStart = parseISO(shift.plannedStartTime);
if (isValid(parsedStart)) { if (isValid(parsedStart)) {
startTime = parsedStart.toLocaleTimeString("it-IT", { startTime = format(parsedStart, "HH:mm");
hour: "2-digit",
minute: "2-digit",
hour12: false,
timeZone: "Europe/Rome"
});
} }
} }
if (shift.plannedEndTime) { if (shift.plannedEndTime) {
const parsedEnd = new Date(shift.plannedEndTime); const parsedEnd = parseISO(shift.plannedEndTime);
if (isValid(parsedEnd)) { if (isValid(parsedEnd)) {
endTime = parsedEnd.toLocaleTimeString("it-IT", { endTime = format(parsedEnd, "HH:mm");
hour: "2-digit",
minute: "2-digit",
hour12: false,
timeZone: "Europe/Rome"
});
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -140,7 +140,7 @@ export default function ServicePlanning() {
{/* Header */} {/* Header */}
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<h1 className="text-3xl font-bold">Planning di Servizio</h1> <h1 className="text-3xl font-bold">Visione Servizi</h1>
<p className="text-muted-foreground"> <p className="text-muted-foreground">
Visualizza orari e dotazioni per agente fisso, agente mobile o per sito Visualizza orari e dotazioni per agente fisso, agente mobile o per sito
</p> </p>

View File

@ -201,31 +201,21 @@ export default function SitePlanningView() {
</div> </div>
) : ( ) : (
dayGuards.map((guard, index) => { dayGuards.map((guard, index) => {
// Parsing sicuro orari (DB in UTC → visualizza in Europe/Rome) // Parsing sicuro orari
let startTime = "N/A"; let startTime = "N/A";
let endTime = "N/A"; let endTime = "N/A";
if (guard.plannedStartTime) { if (guard.plannedStartTime) {
const parsedStart = new Date(guard.plannedStartTime); const parsedStart = parseISO(guard.plannedStartTime);
if (isValid(parsedStart)) { if (isValid(parsedStart)) {
startTime = parsedStart.toLocaleTimeString("it-IT", { startTime = format(parsedStart, "HH:mm");
hour: "2-digit",
minute: "2-digit",
hour12: false,
timeZone: "Europe/Rome"
});
} }
} }
if (guard.plannedEndTime) { if (guard.plannedEndTime) {
const parsedEnd = new Date(guard.plannedEndTime); const parsedEnd = parseISO(guard.plannedEndTime);
if (isValid(parsedEnd)) { if (isValid(parsedEnd)) {
endTime = parsedEnd.toLocaleTimeString("it-IT", { endTime = format(parsedEnd, "HH:mm");
hour: "2-digit",
minute: "2-digit",
hour12: false,
timeZone: "Europe/Rome"
});
} }
} }

View File

@ -1,448 +0,0 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Calendar as CalendarIcon, ChevronLeft, ChevronRight, Users, Clock, MapPin, Navigation, ExternalLink } from "lucide-react";
import { format, parseISO, addDays, startOfWeek, addWeeks } from "date-fns";
import { it } from "date-fns/locale";
import { Link } from "wouter";
type AbsenceType = "sick_leave" | "vacation" | "personal_leave" | "injury";
interface GuardScheduleData {
guard: {
id: string;
firstName: string;
lastName: string;
badgeNumber: string;
};
fixedShifts: Array<{
assignmentId: string;
shiftId: string;
plannedStartTime: Date;
plannedEndTime: Date;
siteName: string;
siteId: string;
}>;
mobileShifts: Array<{
routeId: string;
shiftDate: string;
startTime: string;
endTime: string;
}>;
absences: Array<{
id: string;
type: AbsenceType;
startDate: string;
endDate: string;
}>;
}
interface WeeklyScheduleResponse {
weekStart: string;
weekEnd: string;
location: string;
guards: GuardScheduleData[];
}
const ABSENCE_LABELS: Record<AbsenceType, string> = {
sick_leave: "Malattia",
vacation: "Ferie",
personal_leave: "Permesso",
injury: "Infortunio",
};
type DialogData = {
type: "fixed" | "mobile";
guardName: string;
date: string;
data: any;
} | null;
export default function WeeklyGuards() {
const [selectedLocation, setSelectedLocation] = useState<string>("roccapiemonte");
const [currentWeekStart, setCurrentWeekStart] = useState<Date>(() =>
startOfWeek(new Date(), { weekStartsOn: 1 }) // Inizia lunedì
);
const [dialogData, setDialogData] = useState<DialogData>(null);
const { data: scheduleData, isLoading, error } = useQuery<WeeklyScheduleResponse>({
queryKey: ["/api/weekly-guards-schedule", selectedLocation, format(currentWeekStart, "yyyy-MM-dd")],
queryFn: async () => {
const startDate = format(currentWeekStart, "yyyy-MM-dd");
const response = await fetch(
`/api/weekly-guards-schedule?location=${selectedLocation}&startDate=${startDate}`
);
if (!response.ok) {
throw new Error("Failed to fetch weekly schedule");
}
return response.json();
},
enabled: !!selectedLocation,
});
// Helper per ottenere i giorni della settimana
const getWeekDays = () => {
const days = [];
for (let i = 0; i < 7; i++) {
days.push(addDays(currentWeekStart, i));
}
return days;
};
const weekDays = getWeekDays();
// Helper per trovare l'attività di una guardia in un giorno specifico
const getDayActivity = (guardData: GuardScheduleData, date: Date) => {
const dateStr = format(date, "yyyy-MM-dd");
// Controlla assenze
const absence = guardData.absences.find(abs => {
const startDate = abs.startDate;
const endDate = abs.endDate;
return dateStr >= startDate && dateStr <= endDate;
});
if (absence) {
return {
type: "absence" as const,
label: ABSENCE_LABELS[absence.type],
data: absence,
};
}
// Controlla turni fissi
const fixedShift = guardData.fixedShifts.find(shift => {
const shiftDate = format(new Date(shift.plannedStartTime), "yyyy-MM-dd");
return shiftDate === dateStr;
});
if (fixedShift) {
const startTime = format(new Date(fixedShift.plannedStartTime), "HH:mm");
const endTime = format(new Date(fixedShift.plannedEndTime), "HH:mm");
return {
type: "fixed" as const,
label: `${fixedShift.siteName} ${startTime}-${endTime}`,
data: fixedShift,
};
}
// Controlla turni mobili
const mobileShift = guardData.mobileShifts.find(shift => shift.shiftDate === dateStr);
if (mobileShift) {
return {
type: "mobile" as const,
label: `Pattuglia ${mobileShift.startTime}-${mobileShift.endTime}`,
data: mobileShift,
};
}
return null;
};
const handlePreviousWeek = () => {
setCurrentWeekStart(prev => addWeeks(prev, -1));
};
const handleNextWeek = () => {
setCurrentWeekStart(prev => addWeeks(prev, 1));
};
const handleCellClick = (guardData: GuardScheduleData, activity: ReturnType<typeof getDayActivity>, date: Date) => {
if (!activity || activity.type === "absence") return;
const guardName = `${guardData.guard.lastName} ${guardData.guard.firstName}`;
const dateStr = format(date, "EEEE dd MMMM yyyy", { locale: it });
setDialogData({
type: activity.type,
guardName,
date: dateStr,
data: activity.data,
});
};
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold flex items-center gap-2">
<Users className="h-8 w-8 text-primary" />
Guardie Settimanale
</h1>
<p className="text-muted-foreground mt-1">
Vista riepilogativa delle assegnazioni settimanali per sede
</p>
</div>
</div>
{/* Filtri */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<CalendarIcon className="h-5 w-5" />
Filtri Visualizzazione
</CardTitle>
<CardDescription>
Seleziona sede e settimana per visualizzare le assegnazioni
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-end gap-4">
<div className="flex-1">
<label className="text-sm font-medium mb-2 block">Sede</label>
<Select
value={selectedLocation}
onValueChange={setSelectedLocation}
data-testid="select-location"
>
<SelectTrigger>
<SelectValue placeholder="Seleziona sede" />
</SelectTrigger>
<SelectContent>
<SelectItem value="roccapiemonte">Roccapiemonte</SelectItem>
<SelectItem value="milano">Milano</SelectItem>
<SelectItem value="roma">Roma</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="icon"
onClick={handlePreviousWeek}
data-testid="button-previous-week"
>
<ChevronLeft className="h-4 w-4" />
</Button>
<div className="px-4 py-2 border rounded-md bg-muted min-w-[280px] text-center">
<span className="font-medium">
{format(currentWeekStart, "d MMM", { locale: it })} - {format(addDays(currentWeekStart, 6), "d MMM yyyy", { locale: it })}
</span>
</div>
<Button
variant="outline"
size="icon"
onClick={handleNextWeek}
data-testid="button-next-week"
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
{/* Griglia Settimanale */}
{isLoading ? (
<Card>
<CardContent className="p-6">
<p className="text-center text-muted-foreground">Caricamento...</p>
</CardContent>
</Card>
) : error ? (
<Card>
<CardContent className="p-6">
<p className="text-center text-destructive">
Errore nel caricamento della pianificazione. Riprova più tardi.
</p>
</CardContent>
</Card>
) : scheduleData && scheduleData.guards.length > 0 ? (
<Card>
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full border-collapse">
<thead>
<tr className="border-b bg-muted/50">
<th className="sticky left-0 z-10 bg-muted/50 text-left p-3 font-medium min-w-[180px]">
Guardia
</th>
{weekDays.map((day, index) => (
<th key={index} className="text-center p-3 font-medium min-w-[200px]">
<div>{format(day, "EEE", { locale: it })}</div>
<div className="text-xs text-muted-foreground font-normal">
{format(day, "dd/MM")}
</div>
</th>
))}
</tr>
</thead>
<tbody>
{scheduleData.guards.map((guardData) => (
<tr
key={guardData.guard.id}
className="border-b hover:bg-muted/30"
data-testid={`row-guard-${guardData.guard.id}`}
>
<td className="sticky left-0 z-10 bg-background p-3 font-medium border-r">
<div className="flex flex-col">
<span className="text-sm">
{guardData.guard.lastName} {guardData.guard.firstName}
</span>
<span className="text-xs text-muted-foreground">
#{guardData.guard.badgeNumber}
</span>
</div>
</td>
{weekDays.map((day, dayIndex) => {
const activity = getDayActivity(guardData, day);
return (
<td
key={dayIndex}
className="p-2 text-center align-middle"
>
{activity ? (
activity.type === "absence" ? (
<div
className="text-xs px-2 py-1.5 rounded bg-amber-100 dark:bg-amber-900/30 text-amber-900 dark:text-amber-300"
data-testid={`cell-absence-${guardData.guard.id}-${dayIndex}`}
>
{activity.label}
</div>
) : (
<Button
variant="outline"
size="sm"
className="w-full h-auto text-xs px-2 py-1.5 whitespace-normal hover-elevate"
onClick={() => handleCellClick(guardData, activity, day)}
data-testid={`button-shift-${guardData.guard.id}-${dayIndex}`}
>
{activity.label}
</Button>
)
) : (
<span className="text-xs text-muted-foreground">-</span>
)}
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
</CardContent>
</Card>
) : (
<Card>
<CardContent className="p-6">
<p className="text-center text-muted-foreground">
Nessuna guardia trovata per la sede selezionata
</p>
</CardContent>
</Card>
)}
{/* Dialog Dettaglio Turno */}
<Dialog open={!!dialogData} onOpenChange={() => setDialogData(null)}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{dialogData?.type === "fixed" ? (
<>
<MapPin className="h-5 w-5" />
Turno Fisso - {dialogData?.guardName}
</>
) : (
<>
<Navigation className="h-5 w-5" />
Turno Mobile - {dialogData?.guardName}
</>
)}
</DialogTitle>
<DialogDescription>
{dialogData?.date}
</DialogDescription>
</DialogHeader>
{dialogData && (
<div className="space-y-4">
{dialogData.type === "fixed" ? (
// Dettagli turno fisso
<div className="space-y-3">
<div className="bg-muted/30 p-3 rounded-md space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">Sito</span>
<span className="text-sm font-medium">{dialogData.data.siteName}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">Orario</span>
<div className="flex items-center gap-1 text-sm font-medium">
<Clock className="h-3 w-3" />
{format(new Date(dialogData.data.plannedStartTime), "HH:mm")} - {format(new Date(dialogData.data.plannedEndTime), "HH:mm")}
</div>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">Durata</span>
<span className="text-sm font-bold">
{Math.round((new Date(dialogData.data.plannedEndTime).getTime() - new Date(dialogData.data.plannedStartTime).getTime()) / (1000 * 60 * 60))}h
</span>
</div>
</div>
<div className="p-3 bg-blue-500/10 border border-blue-500/20 rounded-md">
<p className="text-sm text-muted-foreground">
Per modificare questo turno, vai alla pagina <Link href="/general-planning" className="text-primary font-medium hover:underline">Planning Fissi</Link>
</p>
</div>
</div>
) : (
// Dettagli turno mobile
<div className="space-y-3">
<div className="bg-muted/30 p-3 rounded-md space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">Tipo</span>
<Badge variant="outline">Pattuglia</Badge>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">Orario</span>
<div className="flex items-center gap-1 text-sm font-medium">
<Clock className="h-3 w-3" />
{dialogData.data.startTime} - {dialogData.data.endTime}
</div>
</div>
</div>
<div className="p-3 bg-blue-500/10 border border-blue-500/20 rounded-md">
<p className="text-sm text-muted-foreground">
Per visualizzare il percorso completo e modificare il turno, vai alla pagina <Link href="/planning-mobile" className="text-primary font-medium hover:underline">Planning Mobile</Link>
</p>
</div>
</div>
)}
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setDialogData(null)}>
Chiudi
</Button>
{dialogData?.type === "fixed" ? (
<Link href="/general-planning">
<Button data-testid="button-goto-planning-fissi">
<ExternalLink className="h-4 w-4 mr-2" />
Vai a Planning Fissi
</Button>
</Link>
) : (
<Link href="/planning-mobile">
<Button data-testid="button-goto-planning-mobile">
<ExternalLink className="h-4 w-4 mr-2" />
Vai a Planning Mobile
</Button>
</Link>
)}
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

56
package-lock.json generated
View File

@ -9,9 +9,6 @@
"version": "1.0.0", "version": "1.0.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@hookform/resolvers": "^3.10.0", "@hookform/resolvers": "^3.10.0",
"@jridgewell/trace-mapping": "^0.3.25", "@jridgewell/trace-mapping": "^0.3.25",
"@neondatabase/serverless": "^0.10.4", "@neondatabase/serverless": "^0.10.4",
@ -420,59 +417,6 @@
"node": ">=6.9.0" "node": ">=6.9.0"
} }
}, },
"node_modules/@dnd-kit/accessibility": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0"
}
},
"node_modules/@dnd-kit/core": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
"license": "MIT",
"dependencies": {
"@dnd-kit/accessibility": "^3.1.1",
"@dnd-kit/utilities": "^3.2.2",
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/@dnd-kit/sortable": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
"license": "MIT",
"dependencies": {
"@dnd-kit/utilities": "^3.2.2",
"tslib": "^2.0.0"
},
"peerDependencies": {
"@dnd-kit/core": "^6.3.0",
"react": ">=16.8.0"
}
},
"node_modules/@dnd-kit/utilities": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0"
}
},
"node_modules/@drizzle-team/brocli": { "node_modules/@drizzle-team/brocli": {
"version": "0.10.2", "version": "0.10.2",
"resolved": "https://registry.npmjs.org/@drizzle-team/brocli/-/brocli-0.10.2.tgz", "resolved": "https://registry.npmjs.org/@drizzle-team/brocli/-/brocli-0.10.2.tgz",

View File

@ -11,9 +11,6 @@
"db:push": "drizzle-kit push" "db:push": "drizzle-kit push"
}, },
"dependencies": { "dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@hookform/resolvers": "^3.10.0", "@hookform/resolvers": "^3.10.0",
"@jridgewell/trace-mapping": "^0.3.25", "@jridgewell/trace-mapping": "^0.3.25",
"@neondatabase/serverless": "^0.10.4", "@neondatabase/serverless": "^0.10.4",

140
replit.md
View File

@ -1,7 +1,7 @@
# VigilanzaTurni - Sistema Gestione Turni per Istituti di Vigilanza # VigilanzaTurni - Sistema Gestione Turni per Istituti di Vigilanza
## Overview ## Overview
VigilanzaTurni is a professional 24/7 shift management system for security companies, designed to streamline operations and enhance efficiency. It supports multi-role authentication (Admin, Coordinator, Guard, Client) and multi-location operations, managing over 250 security personnel across different branches. Key capabilities include comprehensive guard and site management, 24/7 shift planning, a live operational dashboard with KPIs, reporting for worked hours, and a notification system. The project aims to provide a robust, scalable solution for security companies, improving operational control and resource allocation. VigilanzaTurni is a professional 24/7 shift management system for security companies, designed to streamline operations and enhance efficiency. It supports multi-role authentication (Admin, Coordinator, Guard, Client) and multi-location operations, managing over 250 security personnel across different branches (Roccapiemonte, Milano, Roma). Key capabilities include comprehensive guard and site management, 24/7 shift planning, a live operational dashboard with KPIs, reporting for worked hours, and a notification system.
## User Preferences ## User Preferences
- Interfaccia in italiano - Interfaccia in italiano
@ -29,41 +29,20 @@ VigilanzaTurni is a professional 24/7 shift management system for security compa
- **Componenti**: Shadcn UI with an operational design. - **Componenti**: Shadcn UI with an operational design.
### Database Schema ### Database Schema
The database supports managing users, guards, certifications, sites, shifts, shift assignments, notifications, customers, and service types. It also includes tables for advanced scheduling constraints such as guard constraints, site preferences, contract parameters, training courses, holidays, and absences. Service types include specialized parameters like `fixedPostHours`, `patrolPassages`, `inspectionFrequency`, and `responseTimeMinutes`. The database includes tables for `users`, `guards`, `certifications`, `sites`, `shifts`, `shift_assignments`, `notifications`, `customers`, `service_types`, and various tables for advanced scheduling and constraints (`guard_constraints`, `site_preferences`, `contract_parameters`, `training_courses`, `holidays`, `holiday_assignments`, `absences`, `absence_affected_shifts`). Service types include specialized parameters like `fixedPostHours`, `patrolPassages`, `inspectionFrequency`, and `responseTimeMinutes`. Sites support multi-location (`location` field), contract management (`contractReference`, `contractStartDate`, `contractEndDate`), and service type association (`serviceTypeId` FK to `service_types.id`).
### Core Features ### Core Features
- **Multi-Sede Operational Planning**: Location-first approach for shift planning, filtering resources by selected branch. - **Multi-Sede Operational Planning**: Location-first approach for shift planning, filtering sites, guards, and vehicles by selected branch.
- **Service Type Classification**: Classifies services as "fisso" (fixed posts) or "mobile" (patrols, inspections) to route sites to appropriate planning modules. - **Service Type Classification**: Service types are classified as "fisso" (fixed posts) or "mobile" (patrols, inspections) to route sites to appropriate planning modules (Planning Fissi, Planning Mobile).
- **Planning Fissi**: Weekly planning grid for fixed posts, enabling shift creation with guard availability checks. Includes weekly shift duplication feature with confirmation dialog and automatic navigation. - **Planning Fissi**: Weekly planning grid showing all sites with active contracts, allowing direct shift creation for multiple days with guard availability checks.
- **Planning Mobile**: Guard-centric interface for mobile services, displaying guard availability and hours, with an interactive Leaflet map showing sites. Features include: - **Planning Mobile**: Dedicated guard-centric interface for mobile services, displaying guard availability and hours for mobile-classified sites. Includes interactive Leaflet map showing sites with GPS coordinates and automatic re-centering based on selected location.
- **Smart Site Assignment Indicators**: Sites already in patrol routes display "Assegnato a [Guard Name]" button with scroll-to functionality; unassigned sites show "Non assegnato" text - **Customer Management**: Full CRUD operations for customers with comprehensive details.
- **Drag-and-Drop Reordering**: Interactive drag-and-drop using @dnd-kit library for patrol route stops with visual feedback and automatic sequenceOrder persistence - **Customer-Centric Reports**: New reports aggregating data by customer, replacing site-based billing, with specific counters for fixed posts (hours), patrols (passages), inspections, and interventions. CSV export is supported.
- **Route Optimization**: OSRM API integration with TSP (Traveling Salesman Problem) nearest neighbor algorithm; displays total distance (km) and estimated travel time in dedicated dialog
- **Patrol Sequence List View**: Daily view of planned patrol routes with stops visualization
- **Custom Shift Timing**: Configurable start time and duration for each patrol route (replaces hardcoded 08:00-20:00)
- **Shift Overlap Validation**: POST /api/patrol-routes/check-overlaps endpoint verifies:
- No conflicts with existing fixed post shifts (shift_assignments)
- No conflicts with other mobile patrol routes
- Weekly hours compliance with contract parameters (maxHoursPerWeek + maxOvertimePerWeek)
- **Force-Save Dialog**: Interactive conflict resolution when saving patrol routes with overlaps or contractual limit violations; shows detailed conflict information and allows coordinator override
- **Multi-Day Duplication**: Duplication dialog supports "numero giorni consecutivi" field to create patrol sequences across N consecutive days; includes overlap validation (conservative approach: blocks entire operation if any day has conflicts)
- **Customer Management**: Full CRUD operations for customer details and customer-centric reporting with CSV export.
- **Dashboard Operativa**: Live KPIs and real-time shift status. - **Dashboard Operativa**: Live KPIs and real-time shift status.
- **Gestione Guardie**: Complete profiles with skill matrix, certification management, and badge numbers. - **Gestione Guardie**: Complete profiles with skill matrix, certification management, and unique badge numbers.
- **Gestione Siti/Commesse**: Sites are associated with service types, including schedule, contract management, and location assignment. Automatic geocoding is supported. - **Gestione Siti/Commesse**: Sites are associated with service types from the `service_types` table via `serviceTypeId` (FK). Service types are managed in the "Tipologie Servizi" page and include specialized parameters. Sites include service schedule, contract management, location assignment, and customer assignment (`customerId` FK to `customers.id`).
- **Pianificazione Turni**: 24/7 calendar, manual guard assignment, basic constraints, and shift statuses. - **Pianificazione Turni**: 24/7 calendar, manual guard assignment, basic constraints, and shift statuses.
- **Advanced Planning**: Management of guard constraints, site preferences, contract parameters, training courses, holidays, and absences. Includes patrol route persistence and exclusivity constraints between fixed and mobile shifts. - **Advanced Planning**: Management of guard constraints, site preferences, contract parameters, training courses, holidays, and absences.
- **Guard Planning Views**: Dedicated views for guards to see their fixed post shifts and mobile patrol routes.
- **Site Planning View**: Coordinators can view all guards assigned to a specific site over a week.
- **Shift Duplication Features**:
- **Weekly Copy (Planning Fissi)**: POST /api/shift-assignments/copy-week endpoint duplicates all shifts and assignments from selected week to next week (+7 days) with atomic transaction. Frontend includes confirmation dialog with week details and success feedback.
- **Patrol Sequence Duplication (Planning Mobili)**: POST /api/patrol-routes/duplicate endpoint with dual behavior: UPDATE when target date = source date (modifies guard), CREATE when different date (duplicates route with all stops). Frontend shows daily sequence list with duplication dialog (date picker defaulting to next day, guard selector pre-filled but changeable).
- **Guardie Settimanale**: Compact weekly schedule view showing all guards' assignments across the week in a grid format. Features include:
- **Weekly Grid View**: Guard names in first column, 7 daily columns (Mon-Sun) with compact cell display
- **Multi-Source Aggregation**: GET /api/weekly-guards-schedule endpoint aggregates fixed shifts, patrol routes, and absences by location and week
- **Compact Cell Format**: Fixed posts show "Site Name HH:mm-HH:mm", mobile patrols show "Pattuglia HH:mm-HH:mm", absences show status (Ferie/Malattia/Permesso/Riposo)
- **Read-Only Dialogs**: Clicking cells opens appropriate dialog (fixed shift details or mobile patrol info) with navigation links to Planning Fissi/Mobile for edits
- **Location and Week Filters**: Dropdown for branch selection, week navigation with prev/next buttons displaying "Settimana dal DD MMM al DD MMM YYYY"
### User Roles ### User Roles
- **Admin**: Full access. - **Admin**: Full access.
@ -72,7 +51,96 @@ The database supports managing users, guards, certifications, sites, shifts, shi
- **Client**: View assigned sites, service reporting, KPIs. - **Client**: View assigned sites, service reporting, KPIs.
### Critical Date/Timezone Handling ### Critical Date/Timezone Handling
The system handles timezone conversions for shift times, converting Italy local time from the frontend to UTC for database storage, and back to Italy local time for display, accounting for DST. To prevent timezone-related bugs, especially when assigning shifts, dates should always be constructed from components (`new Date(year, month-1, day)`) and never parsed from ISO strings directly using `parseISO()` or `new Date(string ISO)`. Date validation should use regex instead of `parseISO()`.
## Recent Changes (October 2025)
### Automatic Geocoding Integration (October 23, 2025)
- **Issue**: Users had to manually find and enter GPS coordinates for sites, which was time-consuming and error-prone
- **Solution**:
- **Backend (`server/routes.ts`)**:
- Created POST `/api/geocode` endpoint integrating Nominatim API (OpenStreetMap)
- Implemented in-memory rate limiter enforcing 1 request/second to comply with Nominatim usage policy
- Added compliant User-Agent header: "VigilanzaTurni/1.0 (Security Shift Management System; contact: support@vigilanzaturni.it)"
- Returns latitude, longitude, displayName, and full address object
- **Frontend (`client/src/pages/sites.tsx`)**:
- Added "📍 Trova Coordinate" button in both create and edit site dialogs
- Button auto-populates latitude/longitude fields from address
- Disabled state when address missing or geocoding in progress
- Toast notifications for success (with found address) and error handling
- Dedicated section with bg-muted/50 highlighting for GPS coordinates
- **Impact**: Users can now automatically geocode site addresses with a single click, ensuring accurate GPS positioning for Planning Mobile map without manual coordinate lookup
### Planning Mobile - Leaflet Map Integration (October 23, 2025)
- **Issue**: Planning Mobile page had errors in backend endpoints and lacked interactive map functionality
- **Solution**:
- **Backend Fixes**:
- Removed non-existent fields (`city` from sites, `isActive` from guards) from queries
- Changed `innerJoin` to `leftJoin` for service types to handle sites without serviceTypeId
- Fixed `orderBy` syntax (single field instead of multiple)
- Added `hasDriverLicense` filter for guards (mobile services require driving)
- **Map Integration**:
- Implemented Leaflet + react-leaflet with OpenStreetMap tiles (100% free, no API key)
- Interactive markers for sites with GPS coordinates and classification="mobile"
- Popup details showing site name, address, and service type
- Automatic re-centering via `key={selectedLocation}` forcing MapContainer remount
- Graceful fallback for sites without coordinates
- **Impact**: Planning Mobile now fully functional with interactive map for patrol/inspection route planning
### Planning Mobile - Interactive Features (October 23, 2025)
- **Issue**: Planning Mobile needed interactive map controls and patrol route sequencing workflow
- **Critical Bug Fix - Geocoding**:
- **Problem**: Toast showed "Indirizzo: undefined" when geocoding sites
- **Root Cause**: `apiRequest()` returns Response object, not parsed JSON
- **Fix**: Added `const result = await response.json()` after apiRequest in both handleGeocode() and handleGeocodeEdit()
- **Impact**: Geocoding now correctly displays full address from Nominatim (e.g., "Via Tiburtina, Roma, Lazio, Italia")
- **New Features**:
- **Zoom-to-Site**:
- MapController component with useMap() hook for programmatic map control
- Navigation button on each site card triggers flyTo() animation (zoom level 16)
- Toast feedback: "Mappa centrata - Visualizzazione di [nome sito]"
- **Guard Assignment**:
- "Assegna Guardia" button on site cards
- Validates guard selection from dropdown
- Toast feedback: "[Sito] assegnato a [Nome Cognome Guardia]"
- **Patrol Route Sequencing**:
- Click markers on map to build patrol route sequence
- Visual feedback: Green "Tappa N" badges on markers and site cards
- Dedicated UI section showing route in construction with numbered sequence
- Remove/clear/save route controls
- Auto-reset route when changing guard or location
- **Note**: Backend persistence (save to database) not yet implemented - marked as TODO for future development
- **Impact**: Operators can now interact with the map, assign guards to sites, and visually plan patrol routes by clicking sites in sequence
### Sites Form Fix - ServiceTypeId Integration (October 2025)
- **Issue**: Sites form used hardcoded `shiftType` enum values instead of dynamic service types from the database
- **Solution**:
- Changed Sites form to use `serviceTypeId` (FK to `service_types.id`) instead of deprecated `shiftType` field
- Added dynamic service type dropdown loading from `/api/service-types` endpoint
- Updated both create and edit forms to properly handle service type selection
- Card display now shows service type label from database instead of hardcoded labels
- **Impact**: Sites now correctly reference service types configured in "Tipologie Servizi" page, ensuring consistency across the system
### Advanced Planning System Complete (October 23, 2025)
- **Implementation**: Full planning system with guard views, exclusivity constraints, and database persistence
- **Features**:
- **Patrol Route Database Persistence**:
- Backend endpoints: GET/POST/PUT/DELETE `/api/patrol-routes`
- Database schema: `patrol_routes` table with `patrol_route_stops` for sequence
- Planning Mobile loads existing routes when guard selected, saves to DB
- Green markers on map for sites in current patrol route
- **Exclusivity Constraint (fisso/mobile)**:
- Validation in 3 backend endpoints: POST `/api/patrol-routes`, POST `/api/shift-assignments`, POST `/api/shifts/:shiftId/assignments`
- Guards cannot be assigned to both fixed posts and mobile patrols on same date
- Clear error messages when constraint violated
- **Guard Planning Views**:
- `/my-shifts-fixed`: Guards view their fixed post shifts with orari, dotazioni (armato, automezzo), location, sito
- `/my-shifts-mobile`: Guards view patrol routes with sequenced site list, addresses, vehicle assignment
- Backend endpoints: GET `/api/my-shifts/fixed`, GET `/api/my-shifts/mobile` with date range filters
- **Site Planning View**:
- `/site-planning-view`: Coordinators view all guards assigned to a site across a week
- Shows guard name, badge, orari, dotazioni for each assignment
- Backend endpoint: GET `/api/site-planning/:siteId` with date range filters
- **Impact**: Complete end-to-end planning system supporting both coordinator and guard roles with database-backed route planning and operational equipment tracking
## External Dependencies ## External Dependencies
- **Replit Auth**: For OpenID Connect (OIDC) based authentication. - **Replit Auth**: For OpenID Connect (OIDC) based authentication.
@ -83,7 +151,5 @@ The system handles timezone conversions for shift times, converting Italy local
- **TanStack Query**: For data fetching and state management. - **TanStack Query**: For data fetching and state management.
- **Wouter**: For client-side routing. - **Wouter**: For client-side routing.
- **date-fns**: For date manipulation and formatting. - **date-fns**: For date manipulation and formatting.
- **Leaflet**: Interactive map library with react-leaflet bindings and OpenStreetMap tiles. - **Leaflet**: Interactive map library with react-leaflet bindings and OpenStreetMap tiles (free).
- **Nominatim**: OpenStreetMap geocoding API for automatic address-to-coordinates conversion. - **Nominatim**: OpenStreetMap geocoding API for automatic address-to-coordinates conversion (free, rate limited to 1 req/sec).
- **OSRM (Open Source Routing Machine)**: Public API (router.project-osrm.org) for distance matrix calculation and route optimization in Planning Mobile. No authentication required.
- **@dnd-kit**: Drag-and-drop library (@dnd-kit/core, @dnd-kit/sortable, @dnd-kit/utilities) for interactive patrol route reordering.

View File

@ -4,71 +4,12 @@ import { storage } from "./storage";
import { setupAuth as setupReplitAuth, isAuthenticated as isAuthenticatedReplit } from "./replitAuth"; import { setupAuth as setupReplitAuth, isAuthenticated as isAuthenticatedReplit } from "./replitAuth";
import { setupLocalAuth, isAuthenticated as isAuthenticatedLocal } from "./localAuth"; import { setupLocalAuth, isAuthenticated as isAuthenticatedLocal } from "./localAuth";
import { db } from "./db"; import { db } from "./db";
import { guards, certifications, sites, shifts, shiftAssignments, users, insertShiftSchema, contractParameters, vehicles, serviceTypes, createMultiDayShiftSchema, insertCustomerSchema, customers, patrolRoutes, patrolRouteStops, insertPatrolRouteSchema, absences } from "@shared/schema"; import { guards, certifications, sites, shifts, shiftAssignments, users, insertShiftSchema, contractParameters, vehicles, serviceTypes, createMultiDayShiftSchema, insertCustomerSchema, customers, patrolRoutes, patrolRouteStops, insertPatrolRouteSchema } from "@shared/schema";
import { eq, and, gte, lte, lt, desc, asc, ne, sql } from "drizzle-orm"; import { eq, and, gte, lte, desc, asc, ne, sql } from "drizzle-orm";
import { differenceInDays, differenceInHours, differenceInMinutes, startOfWeek, endOfWeek, startOfMonth, endOfMonth, isWithinInterval, startOfDay, isSameDay, parseISO, format, isValid, addDays } from "date-fns"; import { differenceInDays, differenceInHours, differenceInMinutes, startOfWeek, endOfWeek, startOfMonth, endOfMonth, isWithinInterval, startOfDay, isSameDay, parseISO, format, isValid, addDays } from "date-fns";
import { z } from "zod"; import { z } from "zod";
import { fromZodError } from "zod-validation-error"; import { fromZodError } from "zod-validation-error";
/**
* Calcola l'offset di Europe/Rome rispetto a UTC per una specifica data/ora.
* Gestisce correttamente orari serali e transizioni DST.
* Italy: UTC+1 (ora solare inverno) / UTC+2 (ora legale estate)
* @param year, month (0-11), day, hour, minute
* @returns offset in ore (1 o 2)
*/
function getItalyTimezoneOffsetHours(year: number, month: number, day: number, hour: number, minute: number = 0): number {
// Crea timestamp UTC esatto per l'input Italy time
// Useremo formatToParts per ottenere tutti i componenti date/time
const utcTimestamp = Date.UTC(year, month, day, hour, minute, 0);
const utcDate = new Date(utcTimestamp);
// Ottieni tutti i componenti in Europe/Rome timezone
const formatter = new Intl.DateTimeFormat('en-US', {
timeZone: 'Europe/Rome',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false
});
const parts = formatter.formatToParts(utcDate);
const italyYear = parseInt(parts.find(p => p.type === 'year')?.value || '0');
const italyMonth = parseInt(parts.find(p => p.type === 'month')?.value || '0') - 1;
const italyDay = parseInt(parts.find(p => p.type === 'day')?.value || '0');
let italyHour = parseInt(parts.find(p => p.type === 'hour')?.value || '0');
const italyMinute = parseInt(parts.find(p => p.type === 'minute')?.value || '0');
// formatToParts restituisce hour=24 per mezzanotte (00:00 del giorno successivo)
// Il giorno è già stato incrementato automaticamente da formatToParts
// Normalizziamo solo l'ora: 24:00 → 00:00
const normalizedHour = italyHour === 24 ? 0 : italyHour;
// Crea timestamp Italy come se fosse UTC (per calcolare differenza)
const italyAsUtcTimestamp = Date.UTC(italyYear, italyMonth, italyDay, normalizedHour, italyMinute, 0);
// Calcola differenza in millisecondi e converti in ore
const offsetMs = italyAsUtcTimestamp - utcTimestamp;
const offsetHours = Math.round(offsetMs / (1000 * 60 * 60));
console.log("🕐 Offset calculation:", {
input: `${year}-${String(month+1).padStart(2,'0')}-${String(day).padStart(2,'0')} ${String(hour).padStart(2,'0')}:${String(minute).padStart(2,'0')}`,
utcTimestamp: utcDate.toISOString(),
italyComponents: { year: italyYear, month: italyMonth+1, day: italyDay, hour: italyHour, minute: italyMinute },
offsetHours
});
// Italy è sempre UTC+1 o UTC+2
if (offsetHours !== 1 && offsetHours !== 2) {
console.error("⚠️ Unexpected offset:", offsetHours, "- defaulting to UTC+1");
return 1;
}
return offsetHours;
}
// Determina quale sistema auth usare basandosi sull'ambiente // Determina quale sistema auth usare basandosi sull'ambiente
const USE_LOCAL_AUTH = process.env.DOMAIN === "vt.alfacom.it" || !process.env.REPLIT_DOMAINS; const USE_LOCAL_AUTH = process.env.DOMAIN === "vt.alfacom.it" || !process.env.REPLIT_DOMAINS;
@ -988,7 +929,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
const weekEndTimestampForContract = new Date(weekEndYear, weekEndMonth - 1, weekEndDay, 23, 59, 59, 999); const weekEndTimestampForContract = new Date(weekEndYear, weekEndMonth - 1, weekEndDay, 23, 59, 59, 999);
// Ottieni tutti i siti attivi della sede con contratto valido nelle date della settimana // Ottieni tutti i siti attivi della sede con contratto valido nelle date della settimana
const allActiveSites = await db const activeSites = await db
.select() .select()
.from(sites) .from(sites)
.leftJoin(serviceTypes, eq(sites.serviceTypeId, serviceTypes.id)) .leftJoin(serviceTypes, eq(sites.serviceTypeId, serviceTypes.id))
@ -1003,12 +944,6 @@ export async function registerRoutes(app: Express): Promise<Server> {
) )
); );
// Filtra solo siti FISSI in base alla classificazione del serviceType
// Esclude siti con classificazione "mobile" che vanno gestiti in Planning Mobile
const activeSites = allActiveSites.filter((s: any) =>
!s.service_types || s.service_types.classification?.toLowerCase() === "fisso"
);
// Ottieni tutti i turni della settimana per la sede // Ottieni tutti i turni della settimana per la sede
// ✅ CORRETTO: Usa timestamp già creati correttamente sopra // ✅ CORRETTO: Usa timestamp già creati correttamente sopra
const weekStartTimestamp = weekStartTimestampForContract; const weekStartTimestamp = weekStartTimestampForContract;
@ -1337,143 +1272,11 @@ export async function registerRoutes(app: Express): Promise<Server> {
} }
}); });
// Copy weekly shift assignments to next week
app.post("/api/shift-assignments/copy-week", isAuthenticated, async (req, res) => {
try {
const { weekStart, location } = req.body;
if (!weekStart || !location) {
return res.status(400).json({ message: "Missing required fields: weekStart, location" });
}
// Parse week start date
const [year, month, day] = weekStart.split("-").map(Number);
if (!year || !month || !day) {
return res.status(400).json({ message: "Invalid weekStart format. Expected YYYY-MM-DD" });
}
// Calculate week boundaries (Monday to Sunday)
const weekStartDate = new Date(year, month - 1, day, 0, 0, 0, 0);
const weekEndDate = new Date(year, month - 1, day + 6, 23, 59, 59, 999);
console.log("📋 Copying weekly shifts:", {
weekStart: weekStartDate.toISOString(),
weekEnd: weekEndDate.toISOString(),
location
});
// Transaction: copy all shifts and assignments
const result = await db.transaction(async (tx) => {
// 1. Find all shifts in the source week filtered by location
const sourceShifts = await tx
.select({
shift: shifts,
site: sites
})
.from(shifts)
.innerJoin(sites, eq(shifts.siteId, sites.id))
.where(
and(
gte(shifts.startTime, weekStartDate),
lte(shifts.startTime, weekEndDate),
eq(sites.location, location)
)
);
if (sourceShifts.length === 0) {
throw new Error("Nessun turno trovato nella settimana selezionata");
}
console.log(`📋 Found ${sourceShifts.length} shifts to copy`);
let copiedShiftsCount = 0;
let copiedAssignmentsCount = 0;
// 2. For each shift, copy to next week (+7 days)
for (const { shift: sourceShift, site } of sourceShifts) {
// Calculate new dates (+7 days)
const newStartTime = new Date(sourceShift.startTime);
newStartTime.setDate(newStartTime.getDate() + 7);
const newEndTime = new Date(sourceShift.endTime);
newEndTime.setDate(newEndTime.getDate() + 7);
// Create new shift
const [newShift] = await tx
.insert(shifts)
.values({
siteId: sourceShift.siteId,
startTime: newStartTime,
endTime: newEndTime,
status: "planned",
vehicleId: sourceShift.vehicleId,
notes: sourceShift.notes,
})
.returning();
copiedShiftsCount++;
// 3. Copy all assignments for this shift
const sourceAssignments = await tx
.select()
.from(shiftAssignments)
.where(eq(shiftAssignments.shiftId, sourceShift.id));
for (const sourceAssignment of sourceAssignments) {
// Calculate new planned times (+7 days)
const newPlannedStart = new Date(sourceAssignment.plannedStartTime);
newPlannedStart.setDate(newPlannedStart.getDate() + 7);
const newPlannedEnd = new Date(sourceAssignment.plannedEndTime);
newPlannedEnd.setDate(newPlannedEnd.getDate() + 7);
// Create new assignment
await tx
.insert(shiftAssignments)
.values({
shiftId: newShift.id,
guardId: sourceAssignment.guardId,
plannedStartTime: newPlannedStart,
plannedEndTime: newPlannedEnd,
isArmedOnDuty: sourceAssignment.isArmedOnDuty,
assignedVehicleId: sourceAssignment.assignedVehicleId,
});
copiedAssignmentsCount++;
}
}
return { copiedShiftsCount, copiedAssignmentsCount };
});
res.json({
message: `Settimana copiata con successo: ${result.copiedShiftsCount} turni, ${result.copiedAssignmentsCount} assegnazioni`,
copiedShifts: result.copiedShiftsCount,
copiedAssignments: result.copiedAssignmentsCount,
});
} catch (error: any) {
console.error("❌ Error copying weekly shifts:", error);
res.status(500).json({
message: error.message || "Errore durante la copia dei turni settimanali",
error: String(error)
});
}
});
// Assign guard to site/date with specific time slot (supports multi-day assignments) // Assign guard to site/date with specific time slot (supports multi-day assignments)
app.post("/api/general-planning/assign-guard", isAuthenticated, async (req, res) => { app.post("/api/general-planning/assign-guard", isAuthenticated, async (req, res) => {
try { try {
const { siteId, date, guardId, startTime, durationHours, consecutiveDays = 1, vehicleId, force = false } = req.body; const { siteId, date, guardId, startTime, durationHours, consecutiveDays = 1, vehicleId, force = false } = req.body;
// DEBUG: Log per capire il problema timezone
console.log("🔍 DEBUG assign-guard - Input ricevuto:", {
date,
startTime,
durationHours,
serverTimezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
serverOffset: new Date().getTimezoneOffset()
});
if (!siteId || !date || !guardId || !startTime || !durationHours) { if (!siteId || !date || !guardId || !startTime || !durationHours) {
return res.status(400).json({ return res.status(400).json({
message: "Missing required fields: siteId, date, guardId, startTime, durationHours" message: "Missing required fields: siteId, date, guardId, startTime, durationHours"
@ -1503,16 +1306,6 @@ export async function registerRoutes(app: Express): Promise<Server> {
} }
const [hours, minutes] = startTime.split(":").map(Number); const [hours, minutes] = startTime.split(":").map(Number);
// CRITICAL: Gli orari dal frontend sono in fuso orario Europe/Rome (UTC+1 o UTC+2)
// Calcola offset corretto per convertire a UTC
const italyOffsetHours = getItalyTimezoneOffsetHours(year, month - 1, day, hours, minutes);
console.log("🕐 DEBUG Timezone setup:", {
inputDate: date,
inputTime: `${String(hours).padStart(2,'0')}:${String(minutes).padStart(2,'0')}`,
italyOffsetHours,
isDST: italyOffsetHours === 2
});
// Atomic transaction: create assignments for all consecutive days // Atomic transaction: create assignments for all consecutive days
const result = await db.transaction(async (tx) => { const result = await db.transaction(async (tx) => {
const createdAssignments = []; const createdAssignments = [];
@ -1543,20 +1336,9 @@ export async function registerRoutes(app: Express): Promise<Server> {
} }
} }
// Calculate planned start and end times converting from Europe/Rome to UTC // Calculate planned start and end times in LOCAL timezone
// IMPORTANTE: l'utente inserisce orari in fuso orario Italia (Europe/Rome) const plannedStart = new Date(actualYear, actualMonth, actualDay, hours, minutes, 0, 0);
// Il server è in UTC, quindi dobbiamo convertire Italy time → UTC const plannedEnd = new Date(actualYear, actualMonth, actualDay, hours + durationHours, minutes, 0, 0);
// Formula: UTC time = Italy time - offset
// Esempio: 09:00 Italy (UTC+2) = 07:00 UTC
const plannedStart = new Date(Date.UTC(actualYear, actualMonth, actualDay, hours - italyOffsetHours, minutes, 0, 0));
const plannedEnd = new Date(Date.UTC(actualYear, actualMonth, actualDay, hours + durationHours - italyOffsetHours, minutes, 0, 0));
console.log("🕐 DEBUG Timestamp conversion:", {
inputTime: `${String(hours).padStart(2,'0')}:${String(minutes).padStart(2,'0')}`,
italyOffset: `UTC+${italyOffsetHours}`,
plannedStartUTC: plannedStart.toISOString(),
plannedEndUTC: plannedEnd.toISOString()
});
// Find or create shift for this site/date (full day boundaries in LOCAL timezone) // Find or create shift for this site/date (full day boundaries in LOCAL timezone)
const dayStart = new Date(actualYear, actualMonth, actualDay, 0, 0, 0, 0); const dayStart = new Date(actualYear, actualMonth, actualDay, 0, 0, 0, 0);
@ -1719,7 +1501,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
.select() .select()
.from(guards) .from(guards)
.where(eq(guards.location, location as any)) .where(eq(guards.location, location as any))
.orderBy(guards.firstName, guards.lastName); .orderBy(guards.fullName);
// Ottieni tutti i turni della settimana // Ottieni tutti i turni della settimana
const allWeekShifts = await db const allWeekShifts = await db
@ -1744,7 +1526,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
// Filtra solo turni FISSI in base alla classificazione del serviceType // Filtra solo turni FISSI in base alla classificazione del serviceType
const weekShifts = allWeekShifts.filter((s: any) => const weekShifts = allWeekShifts.filter((s: any) =>
s.serviceType && s.serviceType.classification?.toLowerCase() === "fisso" s.serviceType && s.serviceType.classification === "fisso"
); );
// Ottieni tutte le assegnazioni per i turni della settimana // Ottieni tutte le assegnazioni per i turni della settimana
@ -1797,7 +1579,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
return { return {
guardId: guard.id, guardId: guard.id,
guardName: `${guard.firstName} ${guard.lastName}`, guardName: guard.fullName,
badgeNumber: guard.badgeNumber, badgeNumber: guard.badgeNumber,
shifts, shifts,
totalHours, totalHours,
@ -1834,7 +1616,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
.select() .select()
.from(guards) .from(guards)
.where(eq(guards.location, location as any)) .where(eq(guards.location, location as any))
.orderBy(guards.firstName, guards.lastName); .orderBy(guards.fullName);
// Ottieni tutte le patrol routes della settimana per la sede // Ottieni tutte le patrol routes della settimana per la sede
const weekRoutes = await db const weekRoutes = await db
@ -1864,7 +1646,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
}) })
.from(patrolRouteStops) .from(patrolRouteStops)
.innerJoin(sites, eq(patrolRouteStops.siteId, sites.id)) .innerJoin(sites, eq(patrolRouteStops.siteId, sites.id))
.where(eq(patrolRouteStops.patrolRouteId, routeData.route.id)) .where(eq(patrolRouteStops.routeId, routeData.route.id))
.orderBy(asc(patrolRouteStops.sequenceOrder)); .orderBy(asc(patrolRouteStops.sequenceOrder));
return { return {
@ -1898,7 +1680,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
return { return {
guardId: guard.id, guardId: guard.id,
guardName: `${guard.firstName} ${guard.lastName}`, guardName: guard.fullName,
badgeNumber: guard.badgeNumber, badgeNumber: guard.badgeNumber,
routes: guardRoutes, routes: guardRoutes,
totalRoutes, totalRoutes,
@ -1941,7 +1723,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
.select() .select()
.from(guards) .from(guards)
.where(eq(guards.location, location as any)) .where(eq(guards.location, location as any))
.orderBy(guards.firstName, guards.lastName); .orderBy(guards.fullName);
// Ottieni tutti i turni della settimana per la sede (con JOIN su sites per filtrare location) // Ottieni tutti i turni della settimana per la sede (con JOIN su sites per filtrare location)
const weekShifts = await db const weekShifts = await db
@ -2010,7 +1792,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
return { return {
guardId: guard.id, guardId: guard.id,
guardName: `${guard.firstName} ${guard.lastName}`, guardName: guard.fullName,
badgeNumber: guard.badgeNumber, badgeNumber: guard.badgeNumber,
shifts, shifts,
totalHours, totalHours,
@ -2179,7 +1961,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
.select() .select()
.from(guards) .from(guards)
.where(eq(guards.location, location as any)) .where(eq(guards.location, location as any))
.orderBy(guards.firstName, guards.lastName); .orderBy(guards.fullName);
// Ottieni tutti i turni del mese per la sede // Ottieni tutti i turni del mese per la sede
const monthShifts = await db const monthShifts = await db
@ -4256,282 +4038,6 @@ export async function registerRoutes(app: Express): Promise<Server> {
} }
}); });
// POST - Duplica o modifica patrol route
app.post("/api/patrol-routes/duplicate", isAuthenticated, async (req: any, res) => {
try {
const { sourceRouteId, targetDate, guardId } = req.body;
if (!sourceRouteId || !targetDate) {
return res.status(400).json({
message: "sourceRouteId e targetDate sono obbligatori"
});
}
// Carica patrol route sorgente con tutti gli stops
const sourceRoute = await db.query.patrolRoutes.findFirst({
where: eq(patrolRoutes.id, sourceRouteId),
with: {
stops: {
orderBy: (stops, { asc }) => [asc(stops.sequenceOrder)],
},
},
});
if (!sourceRoute) {
return res.status(404).json({ message: "Sequenza pattuglia sorgente non trovata" });
}
// Controlla se targetDate è uguale a sourceRoute.shiftDate
const sourceDate = new Date(sourceRoute.shiftDate).toISOString().split('T')[0];
const targetDateNormalized = new Date(targetDate).toISOString().split('T')[0];
if (sourceDate === targetDateNormalized) {
// UPDATE: stessa data, modifica solo guardia se fornita
if (guardId && guardId !== sourceRoute.guardId) {
const updated = await db
.update(patrolRoutes)
.set({ guardId })
.where(eq(patrolRoutes.id, sourceRouteId))
.returning();
return res.json({
action: "updated",
route: updated[0],
message: "Guardia assegnata alla sequenza esistente",
});
} else {
return res.status(400).json({
message: "Nessuna modifica da applicare (stessa data e stessa guardia)"
});
}
} else {
// CREATE: data diversa, duplica sequenza con stops
// Crea nuova patrol route
const newRoute = await db
.insert(patrolRoutes)
.values({
guardId: guardId || sourceRoute.guardId, // Usa nuova guardia o mantieni originale
shiftDate: targetDate,
startTime: sourceRoute.startTime,
endTime: sourceRoute.endTime,
status: "planned", // Nuova sequenza sempre in stato planned
location: sourceRoute.location,
notes: sourceRoute.notes,
})
.returning();
const newRouteId = newRoute[0].id;
// Duplica tutti gli stops
if (sourceRoute.stops && sourceRoute.stops.length > 0) {
const stopsData = sourceRoute.stops.map((stop) => ({
patrolRouteId: newRouteId,
siteId: stop.siteId,
sequenceOrder: stop.sequenceOrder,
estimatedArrivalTime: stop.estimatedArrivalTime,
}));
await db.insert(patrolRouteStops).values(stopsData);
}
return res.json({
action: "created",
route: newRoute[0],
copiedStops: sourceRoute.stops?.length || 0,
message: "Sequenza pattuglia duplicata con successo",
});
}
} catch (error) {
console.error("Error duplicating patrol route:", error);
res.status(500).json({ message: "Errore durante duplicazione sequenza pattuglia" });
}
});
// POST - Verifica sovrapposizioni turni e calcola ore settimanali
app.post("/api/patrol-routes/check-overlaps", isAuthenticated, async (req: any, res) => {
try {
const { guardId, shiftDate, startTime, endTime, excludeRouteId } = req.body;
if (!guardId || !shiftDate || !startTime || !endTime) {
return res.status(400).json({
message: "guardId, shiftDate, startTime e endTime sono obbligatori"
});
}
// Converte orari in timestamp per confronto
const shiftDateObj = new Date(shiftDate);
const [startHour, startMin] = startTime.split(':').map(Number);
const [endHour, endMin] = endTime.split(':').map(Number);
const startTimestamp = new Date(shiftDateObj);
startTimestamp.setHours(startHour, startMin, 0, 0);
const endTimestamp = new Date(shiftDateObj);
endTimestamp.setHours(endHour, endMin, 0, 0);
// Se endTime è minore di startTime, il turno attraversa la mezzanotte
if (endTimestamp <= startTimestamp) {
endTimestamp.setDate(endTimestamp.getDate() + 1);
}
const conflicts = [];
// 1. Controlla sovrapposizioni con shift_assignments (turni fissi)
const fixedShifts = await db
.select({
id: shiftAssignments.id,
siteName: sites.name,
plannedStartTime: shiftAssignments.plannedStartTime,
plannedEndTime: shiftAssignments.plannedEndTime,
})
.from(shiftAssignments)
.leftJoin(shifts, eq(shiftAssignments.shiftId, shifts.id))
.leftJoin(sites, eq(shifts.siteId, sites.id))
.where(eq(shiftAssignments.guardId, guardId));
for (const shift of fixedShifts) {
const shiftStart = new Date(shift.plannedStartTime);
const shiftEnd = new Date(shift.plannedEndTime);
// Controlla sovrapposizione
if (startTimestamp < shiftEnd && endTimestamp > shiftStart) {
conflicts.push({
type: 'fisso',
siteName: shift.siteName,
startTime: shift.plannedStartTime,
endTime: shift.plannedEndTime,
});
}
}
// 2. Controlla sovrapposizioni con patrol_routes (turni mobili)
const mobileShifts = await db
.select()
.from(patrolRoutes)
.where(
and(
eq(patrolRoutes.guardId, guardId),
excludeRouteId ? ne(patrolRoutes.id, excludeRouteId) : undefined
)
);
for (const route of mobileShifts) {
const routeDateObj = new Date(route.shiftDate);
const [rStartHour, rStartMin] = route.startTime.split(':').map(Number);
const [rEndHour, rEndMin] = route.endTime.split(':').map(Number);
const routeStart = new Date(routeDateObj);
routeStart.setHours(rStartHour, rStartMin, 0, 0);
const routeEnd = new Date(routeDateObj);
routeEnd.setHours(rEndHour, rEndMin, 0, 0);
if (routeEnd <= routeStart) {
routeEnd.setDate(routeEnd.getDate() + 1);
}
// Controlla sovrapposizione
if (startTimestamp < routeEnd && endTimestamp > routeStart) {
conflicts.push({
type: 'mobile',
shiftDate: route.shiftDate,
startTime: route.startTime,
endTime: route.endTime,
});
}
}
// 3. Calcola ore settimanali
const weekStart = new Date(shiftDateObj);
weekStart.setDate(weekStart.getDate() - weekStart.getDay() + (weekStart.getDay() === 0 ? -6 : 1));
weekStart.setHours(0, 0, 0, 0);
const weekEnd = new Date(weekStart);
weekEnd.setDate(weekEnd.getDate() + 7);
let totalWeeklyHours = 0;
// Ore da turni fissi
const weeklyFixedShifts = await db
.select({
plannedStartTime: shiftAssignments.plannedStartTime,
plannedEndTime: shiftAssignments.plannedEndTime,
})
.from(shiftAssignments)
.where(
and(
eq(shiftAssignments.guardId, guardId),
gte(shiftAssignments.plannedStartTime, weekStart),
lt(shiftAssignments.plannedStartTime, weekEnd)
)
);
for (const shift of weeklyFixedShifts) {
const start = new Date(shift.plannedStartTime);
const end = new Date(shift.plannedEndTime);
const hours = (end.getTime() - start.getTime()) / (1000 * 60 * 60);
totalWeeklyHours += hours;
}
// Ore da turni mobili
const weeklyMobileShifts = await db
.select()
.from(patrolRoutes)
.where(
and(
eq(patrolRoutes.guardId, guardId),
gte(patrolRoutes.shiftDate, weekStart.toISOString().split('T')[0]),
lt(patrolRoutes.shiftDate, weekEnd.toISOString().split('T')[0]),
excludeRouteId ? ne(patrolRoutes.id, excludeRouteId) : undefined
)
);
for (const route of weeklyMobileShifts) {
const [rStartHour, rStartMin] = route.startTime.split(':').map(Number);
const [rEndHour, rEndMin] = route.endTime.split(':').map(Number);
let hours = rEndHour - rStartHour + (rEndMin - rStartMin) / 60;
if (hours < 0) hours += 24; // Turno attraversa mezzanotte
totalWeeklyHours += hours;
}
// Aggiungi ore del nuovo turno
const newShiftHours = (endTimestamp.getTime() - startTimestamp.getTime()) / (1000 * 60 * 60);
const totalHoursWithNew = totalWeeklyHours + newShiftHours;
// 4. Recupera limiti contrattuali
const contractParams = await db
.select()
.from(contractParameters)
.limit(1);
const maxHours = contractParams[0]?.maxHoursPerWeek || 40;
const maxOvertime = contractParams[0]?.maxOvertimePerWeek || 8;
const totalMaxHours = maxHours + maxOvertime;
const exceedsContractLimit = totalHoursWithNew > totalMaxHours;
res.json({
hasConflicts: conflicts.length > 0,
conflicts,
weeklyHours: {
current: Math.round(totalWeeklyHours * 100) / 100,
withNewShift: Math.round(totalHoursWithNew * 100) / 100,
newShiftHours: Math.round(newShiftHours * 100) / 100,
maxRegular: maxHours,
maxOvertime: maxOvertime,
maxTotal: totalMaxHours,
exceedsLimit: exceedsContractLimit,
},
});
} catch (error) {
console.error("Error checking overlaps:", error);
res.status(500).json({ message: "Errore verifica sovrapposizioni" });
}
});
// ============= GEOCODING API (Nominatim/OSM) ============= // ============= GEOCODING API (Nominatim/OSM) =============
// Rate limiter semplice per rispettare 1 req/sec di Nominatim // Rate limiter semplice per rispettare 1 req/sec di Nominatim
@ -4596,217 +4102,6 @@ export async function registerRoutes(app: Express): Promise<Server> {
} }
}); });
// ============= ROUTE OPTIMIZATION API (OSRM + TSP) =============
app.post("/api/optimize-route", isAuthenticated, async (req: any, res) => {
try {
const { coordinates } = req.body;
// Validazione: array di coordinate [{lat, lon, id}]
if (!Array.isArray(coordinates) || coordinates.length < 2) {
return res.status(400).json({
message: "Almeno 2 coordinate richieste per l'ottimizzazione"
});
}
// Verifica formato coordinate
for (const coord of coordinates) {
if (!coord.lat || !coord.lon || !coord.id) {
return res.status(400).json({
message: "Ogni coordinata deve avere lat, lon e id"
});
}
}
// STEP 1: Calcola matrice distanze usando OSRM Table API
const coordsString = coordinates.map(c => `${c.lon},${c.lat}`).join(';');
const osrmTableUrl = `https://router.project-osrm.org/table/v1/driving/${coordsString}?annotations=distance,duration`;
const osrmResponse = await fetch(osrmTableUrl);
if (!osrmResponse.ok) {
throw new Error(`OSRM API error: ${osrmResponse.status}`);
}
const osrmData = await osrmResponse.json();
if (osrmData.code !== 'Ok' || !osrmData.distances || !osrmData.durations) {
throw new Error("OSRM non ha restituito dati validi");
}
const distances = osrmData.distances; // Matrice NxN in metri
const durations = osrmData.durations; // Matrice NxN in secondi
// STEP 2: Applica algoritmo TSP Nearest Neighbor
// Inizia dalla prima tappa (indice 0)
const n = coordinates.length;
const visited = new Set<number>();
const route: number[] = [];
let current = 0;
let totalDistance = 0;
let totalDuration = 0;
visited.add(current);
route.push(current);
// Trova sempre il vicino più vicino non visitato
for (let i = 1; i < n; i++) {
let nearest = -1;
let minDistance = Infinity;
for (let j = 0; j < n; j++) {
if (!visited.has(j) && distances[current][j] < minDistance) {
minDistance = distances[current][j];
nearest = j;
}
}
if (nearest !== -1) {
totalDistance += distances[current][nearest];
totalDuration += durations[current][nearest];
visited.add(nearest);
route.push(nearest);
current = nearest;
}
}
// Ritorna al punto di partenza (circuito chiuso)
totalDistance += distances[current][0];
totalDuration += durations[current][0];
// STEP 3: Prepara risposta
const optimizedRoute = route.map(index => ({
...coordinates[index],
order: route.indexOf(index) + 1,
}));
res.json({
optimizedRoute,
totalDistanceMeters: Math.round(totalDistance),
totalDistanceKm: (totalDistance / 1000).toFixed(2),
totalDurationSeconds: Math.round(totalDuration),
totalDurationMinutes: Math.round(totalDuration / 60),
estimatedTimeFormatted: formatDuration(totalDuration),
});
} catch (error) {
console.error("Error optimizing route:", error);
res.status(500).json({ message: "Errore durante l'ottimizzazione del percorso" });
}
});
// Helper per formattare durata in ore e minuti
function formatDuration(seconds: number): string {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (hours > 0) {
return `${hours}h ${minutes}m`;
}
return `${minutes}m`;
}
// ============= WEEKLY GUARDS SCHEDULE =============
app.get("/api/weekly-guards-schedule", isAuthenticated, async (req: any, res) => {
try {
const location = req.query.location as string;
const startDate = req.query.startDate as string;
if (!location || !startDate) {
return res.status(400).json({ message: "Location e startDate richiesti" });
}
// Calcola l'intervallo della settimana (7 giorni da startDate)
const weekStart = parseISO(startDate);
const weekEnd = addDays(weekStart, 6);
// Recupera tutte le guardie della sede
const guardsInLocation = await db
.select()
.from(guards)
.where(eq(guards.location, location))
.orderBy(guards.lastName, guards.firstName);
// Prepara la struttura dati
const guardsSchedule = [];
for (const guard of guardsInLocation) {
// Recupera turni fissi della settimana (shift_assignments)
const fixedShifts = await db
.select({
assignmentId: shiftAssignments.id,
shiftId: shifts.id,
plannedStartTime: shiftAssignments.plannedStartTime,
plannedEndTime: shiftAssignments.plannedEndTime,
siteName: sites.name,
siteId: sites.id,
})
.from(shiftAssignments)
.innerJoin(shifts, eq(shiftAssignments.shiftId, shifts.id))
.innerJoin(sites, eq(shifts.siteId, sites.id))
.where(
and(
eq(shiftAssignments.guardId, guard.id),
gte(shiftAssignments.plannedStartTime, weekStart),
lte(shiftAssignments.plannedStartTime, weekEnd)
)
);
// Recupera turni mobili della settimana (patrol_routes)
const mobileShifts = await db
.select({
routeId: patrolRoutes.id,
shiftDate: patrolRoutes.shiftDate,
startTime: patrolRoutes.startTime,
endTime: patrolRoutes.endTime,
})
.from(patrolRoutes)
.where(
and(
eq(patrolRoutes.guardId, guard.id),
gte(sql`${patrolRoutes.shiftDate}`, startDate),
lte(sql`${patrolRoutes.shiftDate}`, format(weekEnd, 'yyyy-MM-dd'))
)
);
// Recupera assenze della settimana
const absencesData = await db
.select()
.from(absences)
.where(
and(
eq(absences.guardId, guard.id),
lte(sql`${absences.startDate}`, format(weekEnd, 'yyyy-MM-dd')),
gte(sql`${absences.endDate}`, startDate)
)
);
guardsSchedule.push({
guard: {
id: guard.id,
firstName: guard.firstName,
lastName: guard.lastName,
badgeNumber: guard.badgeNumber,
},
fixedShifts,
mobileShifts,
absences: absencesData,
});
}
res.json({
weekStart: format(weekStart, 'yyyy-MM-dd'),
weekEnd: format(weekEnd, 'yyyy-MM-dd'),
location,
guards: guardsSchedule,
});
} catch (error) {
console.error("Error fetching weekly guards schedule:", error);
res.status(500).json({ message: "Errore nel recupero della pianificazione settimanale" });
}
});
const httpServer = createServer(app); const httpServer = createServer(app);
return httpServer; return httpServer;
} }

View File

@ -1,73 +1,7 @@
{ {
"version": "1.1.1", "version": "1.0.49",
"lastUpdate": "2025-11-15T10:11:44.404Z", "lastUpdate": "2025-10-23T17:04:52.044Z",
"changelog": [ "changelog": [
{
"version": "1.1.1",
"date": "2025-11-15",
"type": "patch",
"description": "Deployment automatico v1.1.1"
},
{
"version": "1.1.0",
"date": "2025-10-25",
"type": "minor",
"description": "Deployment automatico v1.1.0"
},
{
"version": "1.0.58",
"date": "2025-10-25",
"type": "patch",
"description": "Deployment automatico v1.0.58"
},
{
"version": "1.0.57",
"date": "2025-10-25",
"type": "patch",
"description": "Deployment automatico v1.0.57"
},
{
"version": "1.0.56",
"date": "2025-10-25",
"type": "patch",
"description": "Deployment automatico v1.0.56"
},
{
"version": "1.0.55",
"date": "2025-10-25",
"type": "patch",
"description": "Deployment automatico v1.0.55"
},
{
"version": "1.0.54",
"date": "2025-10-24",
"type": "patch",
"description": "Deployment automatico v1.0.54"
},
{
"version": "1.0.53",
"date": "2025-10-24",
"type": "patch",
"description": "Deployment automatico v1.0.53"
},
{
"version": "1.0.52",
"date": "2025-10-24",
"type": "patch",
"description": "Deployment automatico v1.0.52"
},
{
"version": "1.0.51",
"date": "2025-10-24",
"type": "patch",
"description": "Deployment automatico v1.0.51"
},
{
"version": "1.0.50",
"date": "2025-10-24",
"type": "patch",
"description": "Deployment automatico v1.0.50"
},
{ {
"version": "1.0.49", "version": "1.0.49",
"date": "2025-10-23", "date": "2025-10-23",
@ -301,6 +235,72 @@
"date": "2025-10-17", "date": "2025-10-17",
"type": "patch", "type": "patch",
"description": "Deployment automatico v1.0.11" "description": "Deployment automatico v1.0.11"
},
{
"version": "1.0.10",
"date": "2025-10-17",
"type": "patch",
"description": "Deployment automatico v1.0.10"
},
{
"version": "1.0.9",
"date": "2025-10-17",
"type": "patch",
"description": "Deployment automatico v1.0.9"
},
{
"version": "1.0.8",
"date": "2025-10-17",
"type": "patch",
"description": "Deployment automatico v1.0.8"
},
{
"version": "1.0.7",
"date": "2025-10-17",
"type": "patch",
"description": "Deployment automatico v1.0.7"
},
{
"version": "1.0.6",
"date": "2025-10-17",
"type": "patch",
"description": "Deployment automatico v1.0.6"
},
{
"version": "1.0.5",
"date": "2025-10-17",
"type": "patch",
"description": "Deployment automatico v1.0.5"
},
{
"version": "1.0.4",
"date": "2025-10-17",
"type": "patch",
"description": "Deployment automatico v1.0.4"
},
{
"version": "1.0.3",
"date": "2025-10-17",
"type": "patch",
"description": "Deployment automatico v1.0.3"
},
{
"version": "1.0.2",
"date": "2025-10-17",
"type": "patch",
"description": "Deployment automatico v1.0.2"
},
{
"version": "1.0.1",
"date": "2025-10-17",
"type": "patch",
"description": "Deployment automatico v1.0.1"
},
{
"version": "1.0.0",
"date": "2025-01-17",
"type": "initial",
"description": "Versione iniziale VigilanzaTurni - Sistema completo gestione turni vigilanza"
} }
] ]
} }