7 Commits
master ... V.3

Author SHA1 Message Date
luca.mustacchio@outlook.it
4bbed5a7a4 sistemato alcuni bag 2026-03-31 22:13:18 +02:00
luca.mustacchio@outlook.it
09b1342892 sistematole modifiche provvisorie e i salvataggi 2026-03-31 20:10:06 +02:00
luca.mustacchio@outlook.it
cbeff856d4 sistemato controllo dipendenti dal database e colori combo. problema nelle modifiche provvisorie deve ignorare i ruoli presenti 2026-03-31 15:01:36 +02:00
luca.mustacchio@outlook.it
1ff1145b8a sisstemato combobox e colori, ma bisogna anche controllare nel d se ci sono turni assegnaticontrollo turni in fasce differenze di ogni dipendente 2026-03-29 22:22:23 +02:00
luca.mustacchio@outlook.it
73e7c090bf AGGIUNTO CALCOLO DELLE ORE DI ASSENZA 2026-03-28 13:37:54 +01:00
luca.mustacchio@outlook.it
99b2e7c325 sistemato colorazione combobox 2026-03-27 19:35:23 +01:00
luca.mustacchio@outlook.it
d88967d9fc colorazione combobox 2026-03-27 15:27:09 +01:00
21 changed files with 4363 additions and 666 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -184,7 +184,10 @@ Public Class DatabaseManager
FOREIGN KEY(FasciaID) REFERENCES Fasce(ID)
);"
cmd.ExecuteNonQuery()
cmd.CommandText = "
CREATE UNIQUE INDEX IF NOT EXISTS IDX_AssenzeFasce_Unico
ON AssenzeFasce(TipoAssenzaID, FasciaID);"
cmd.ExecuteNonQuery()
'' ------------------- RECORD assenza totale-------------------
cmd.CommandText = "
INSERT OR IGNORE INTO TipiAssenza (Nome, Retribuita, Descrizione) VALUES

View File

@@ -4,6 +4,7 @@ Imports System.Drawing.Text
Public Class FasciaRowControl
' ✅ TIPO PER TRACCIARE LE COMBOBOX
Private Class ComboInfo
Friend RuoloID As Integer
Public Property ComboBox As ComboBox
Public Property FasciaID As Integer
Public Property Slot As Integer
@@ -14,16 +15,20 @@ Public Class FasciaRowControl
Private _tutteCombo As New List(Of ComboInfo)()
Public righeTabella As RigheTabella
Public Data As Date
Public Property Data As Date?
Public W As Integer = 0
Private Property HRow As Integer = 35
Private Property WCol As Single = 100.0F
' ✅ DICHIARA IL COMPONENTE TOOLTIP
Private _toolTip As New System.Windows.Forms.ToolTip()
' ✅ EVENTI PUBBLICI PER IL FORM
Public Event InizializzazioneCompletata(larghezza As Integer)
' ✅ MODIFICA L'EVENTO (aggiungi haConflittoGrave)
Public Event ComboBoxDipendenteCambiato(data As Date, fasciaID As Integer, slot As Integer,
dipendenteID As Integer, haConflitto As Boolean)
dipendenteID As Integer, haConflitto As Boolean,
haConflittoGrave As Boolean)
Public Sub New(data As Date, righeTabella As RigheTabella)
Me.righeTabella = righeTabella
@@ -39,20 +44,45 @@ Public Class FasciaRowControl
Private Sub InizializzaTabella()
Try
CreaColonne()
CreaTimelineFasce()
CreaTimelineFasce() ' ← Crea le ComboBox
CreaAltezzaTabella()
' ✅ CALCOLA E SALVA W
Me.W = tlpFasce.Width
Debug.WriteLine($"[Controllo {Data:dd/MM}] Inizializzato | W={Me.W}")
' ✅ FORZA AGGIORNAMENTO LAYOUT
tlpFasce.PerformLayout()
Me.PerformLayout()
Application.DoEvents()
' ✅ APPLICA DIPENDENTI ASSEGNATI (LEGGE DA RIGHETABELLA)
ApplicaDipendentiAssegnati() ' ← Imposta SelectedValue e Colori
Debug.WriteLine($"[Controllo {Data:dd/MM}] Inizializzato | W={Me.W} | Combo: {_tutteCombo.Count}")
' ✅ NOTIFICA AL FORM
RaiseEvent InizializzazioneCompletata(Me.W)
Catch ex As Exception
Debug.WriteLine($"[ERRORE] InizializzaTabella: {ex.Message}")
End Try
End Sub
Public Sub ApplicaDipendentiAssegnati()
If righeTabella.Fasce Is Nothing Then Return
Debug.WriteLine($"[Controllo {Data:dd/MM}] Applico dipendenti assegnati...")
For Each fascia In righeTabella.Fasce
For slot As Integer = 1 To fascia.PersoneNecessarie
If slot <= fascia.DipendentiAssegnati.Count Then
Dim dip = fascia.DipendentiAssegnati(slot - 1)
If dip IsNot Nothing AndAlso dip.ID > 0 Then
Debug.WriteLine($" Fascia={fascia.FasciaOraria.ID}, Slot={slot}, Dip={dip.ID} ({dip.Cognome})")
ImpostaComboBoxConColore(fascia.FasciaOraria.ID, slot, dip.ID)
End If
End If
Next
Next
End Sub
Private Sub CreaColonne()
Dim numColonne As Integer = CalcolaNumeroColonne() + 1 ' +1 per descrizione
@@ -84,7 +114,7 @@ Public Class FasciaRowControl
' Label Data
Dim lblData As New Label With {
.Text = Data.ToString("dddd dd MMMM yyyy"),
.Text = If(Data.HasValue, Data.Value.ToString("dddd dd MMMM yyyy", New System.Globalization.CultureInfo("it-IT")), String.Empty),
.BackColor = Color.FromArgb(200, 200, 200),
.TextAlign = ContentAlignment.MiddleCenter,
.Dock = DockStyle.Fill,
@@ -139,7 +169,51 @@ Public Class FasciaRowControl
tlpFasce.Height = HRow * 2
tlpFasce.ResumeLayout()
End Sub
Private Sub ImpostaComboBoxConColore(fasciaID As Integer, slot As Integer, dipendenteID As Integer)
Dim comboInfo = _tutteCombo.FirstOrDefault(Function(c) c.FasciaID = fasciaID AndAlso c.Slot = slot)
If comboInfo Is Nothing Then
Debug.WriteLine($"⚠️ ComboBox non trovata: Fascia={fasciaID}, Slot={slot}")
Return
End If
' Imposta SelectedValue
comboInfo.ComboBox.SelectedValue = dipendenteID
' Controlla conflitto
Dim haConflitto As Boolean = False
Dim haConflittoGrave As Boolean = False
If dipendenteID > 0 Then
Dim fasciaCorrente = righeTabella.Fasce.FirstOrDefault(Function(f) f.FasciaOraria.ID = fasciaID)
For Each c In _tutteCombo.Where(Function(x) x.FasciaID <> fasciaID)
If c.ComboBox.SelectedValue IsNot Nothing AndAlso CInt(c.ComboBox.SelectedValue) = dipendenteID Then
haConflitto = True
If fasciaCorrente IsNot Nothing Then
Dim fasciaAltra = righeTabella.Fasce.FirstOrDefault(Function(f) f.FasciaOraria.ID = c.FasciaID)
If fasciaAltra IsNot Nothing AndAlso FasceSiSovrappongono(fasciaCorrente, fasciaAltra) Then
haConflittoGrave = True
Exit For
End If
End If
End If
Next
End If
' Applica colore (3 livelli)
If dipendenteID = 0 Then
comboInfo.ComboBox.BackColor = Color.White
ElseIf haConflittoGrave Then
comboInfo.ComboBox.BackColor = Color.FromArgb(255, 150, 150) ' 🔴 Rosso
ElseIf haConflitto Then
comboInfo.ComboBox.BackColor = Color.FromArgb(255, 255, 150) ' 🟡 Giallo
Else
comboInfo.ComboBox.BackColor = Color.FromArgb(150, 255, 150) ' 🟢 Verde
End If
comboInfo.ComboBox.Refresh()
End Sub
Private Sub CreaTimelineFasce()
If righeTabella.Fasce Is Nothing OrElse righeTabella.Fasce.Count = 0 Then Return
@@ -181,7 +255,7 @@ Public Class FasciaRowControl
If colonneDaCoprire < 1 Then colonneDaCoprire = 1
' Lista dipendenti
Dim listaDip As List(Of Dipendente) = fascia.DipentiPresenti
Dim listaDip As List(Of Dipendente) = fascia.DipentiDisponibili
Dim listaDipCopia As New List(Of Dipendente)(listaDip)
listaDipCopia.Insert(0, New Dipendente With {.ID = 0, .Nome = "", .Cognome = "-- VUOTO --"})
@@ -222,11 +296,11 @@ Public Class FasciaRowControl
' ✅ TRACCIA LA COMBOBOX
_tutteCombo.Add(New ComboInfo With {
.ComboBox = cmb,
.FasciaID = fascia.FasciaOraria.ID,
.Slot = slot,
.ListaOriginale = listaCopia
})
.ComboBox = cmb,
.FasciaID = fascia.FasciaOraria.ID,
.Slot = slot,
.ListaOriginale = listaCopia
})
' ✅ HANDLER
AddHandler cmb.SelectedIndexChanged, AddressOf ComboBoxDipendente_SelectedIndexChanged
@@ -243,8 +317,36 @@ Public Class FasciaRowControl
tlpFasce.ResumeLayout()
End Sub
' ✅ TROVA DIPENDENTI OCCUPATI IN FASCE CHE SI SOVRAPPONGONO
Private Function GetDipendentiOccupatiInFasceSovrapposte(fasciaIDTarget As Integer, comboDaIgnorare As ComboBox) As List(Of Integer)
Dim bloccati As New List(Of Integer)
' Recupera l'oggetto Fascia della ComboBox che stiamo filtrando
Dim fasciaTargetObj = righeTabella.Fasce.FirstOrDefault(Function(f) f.FasciaOraria.ID = fasciaIDTarget)
If fasciaTargetObj Is Nothing Then Return bloccati
' Scansiona tutte le altre ComboBox
For Each ci In _tutteCombo
' Ignora la ComboBox che stiamo attualmente filtrando (per non bloccare la selezione corrente su se stessa)
If ci.ComboBox Is comboDaIgnorare Then Continue For
' Se non c'è selezione, salta
If ci.ComboBox.SelectedValue Is Nothing OrElse CInt(ci.ComboBox.SelectedValue) = 0 Then Continue For
Dim dipID = CInt(ci.ComboBox.SelectedValue)
' Recupera la Fascia dell'altra ComboBox
Dim fasciaAltraObj = righeTabella.Fasce.FirstOrDefault(Function(f) f.FasciaOraria.ID = ci.FasciaID)
' Se le fasce si sovrappongono, aggiungi il dipendente alla lista dei bloccati
If fasciaAltraObj IsNot Nothing AndAlso FasceSiSovrappongono(fasciaTargetObj, fasciaAltraObj) Then
If Not bloccati.Contains(dipID) Then bloccati.Add(dipID)
End If
Next
Return bloccati
End Function
Private Sub ComboBoxDipendente_SelectedIndexChanged(sender As Object, e As EventArgs)
' ✅ ESCI SE STA GIA' AGGIORNANDO
If _staAggiornando Then Return
Dim cmb As ComboBox = CType(sender, ComboBox)
@@ -256,70 +358,314 @@ Public Class FasciaRowControl
Dim slot As Integer = comboInfo.Slot
Dim dipendenteID As Integer = If(cmb.SelectedValue IsNot Nothing, CInt(cmb.SelectedValue), 0)
' ✅ CONTROLLA CONFLITTO
Dim haConflitto As Boolean = False
If dipendenteID > 0 Then
For Each c In _tutteCombo.Where(Function(x) x.FasciaID <> fasciaID)
If c.ComboBox.SelectedValue IsNot Nothing AndAlso CInt(c.ComboBox.SelectedValue) = dipendenteID Then
haConflitto = True
Exit For
End If
Next
End If
' ✅ APPLICA COLORE
' ✅ 1. SE VUOTO, PULISCI E ESCI
If dipendenteID = 0 Then
cmb.BackColor = Color.White
ElseIf haConflitto Then
cmb.BackColor = Color.Yellow
Else
cmb.BackColor = Color.LightGreen
AggiornaFiltriComboEsclusa(cmb)
RicalcolaColoriTutteCombo()
RaiseEvent ComboBoxDipendenteCambiato(Me.Data, fasciaID, slot, 0, False, False)
Return
End If
' ✅ AGGIORNA ALTRE COMBO (SOLO FILTRO, NON DATASOURCE)
' ✅ 2. CONTROLLA CONFLITTI ESTERNI (ALTRI RUOLI - DATABASE)
Dim fasciaCorrente = righeTabella.Fasce.FirstOrDefault(Function(f) f.FasciaOraria.ID = fasciaID)
Dim conflittoEsterno = VerificaConflittiEsterni(dipendenteID, fasciaCorrente)
Dim haConflittoEsterno As Boolean = conflittoEsterno.HaConflitto
If conflittoEsterno.HaConflitto Then
' ✅ CONFLITTO TROVATO IN ALTRI RUOLI
Dim formPadre As Form = Me.FindForm()
Dim titolo As String = "Conflitto Turni"
If conflittoEsterno.HaSovrapposizione Then
' ❌ SOVRAPPOSIZIONE ORARIA (CRITICO)
Dim res = MessageBox.Show(formPadre,
$"⛔ CONFLITTO GRAVE!{vbCrLf}{vbCrLf}" &
$"Il dipendente è già assegnato in un altro ruolo:{vbCrLf}" &
$"{conflittoEsterno.Messaggio}{vbCrLf}{vbCrLf}" &
$"Le fasce orarie si sovrappongono.{vbCrLf}{vbCrLf}" &
$"La selezione verrà annullata.",
titolo, MessageBoxButtons.OK, MessageBoxIcon.Error)
' 🔄 RESETTA LA COMBOBOX SENZA TRIGGERARE EVENTI
_staAggiornando = True
RemoveHandler cmb.SelectedIndexChanged, AddressOf ComboBoxDipendente_SelectedIndexChanged
cmb.SelectedValue = 0
cmb.BackColor = Color.White
AddHandler cmb.SelectedIndexChanged, AddressOf ComboBoxDipendente_SelectedIndexChanged
_staAggiornando = False
' Aggiorna filtri e colori per riflettere il reset
AggiornaFiltriComboEsclusa(cmb)
RicalcolaColoriTutteCombo()
' Notifica cambio a vuoto
RaiseEvent ComboBoxDipendenteCambiato(Me.Data, fasciaID, slot, 0, False, False)
Return ' ⛔ ESCI SUBITO, NON SALVARE
Else
Dim nomeRuoloConflitto As String = $"Ruolo ID {conflittoEsterno.TurnoConflitto.RuoloID}"
Try
If Gestionale.gestioneRuoli IsNot Nothing Then
Dim r = Gestionale.gestioneRuoli.GetRuolo(conflittoEsterno.TurnoConflitto.RuoloID)
If r IsNot Nothing Then nomeRuoloConflitto = r.Nome
End If
Catch : End Try
' ⚠️ STESSO GIORNO, MA ORARI DIVERSI (AVVISO)
_toolTip.SetToolTip(cmb,
$"⚠️ ATTENZIONE!{vbCrLf}{vbCrLf}" &
$"Il dipendente ha già un turno in:{vbCrLf}" &
$"🏢 Ruolo: {nomeRuoloConflitto}{vbCrLf}" &
$"📅 Data: {Me.Data:dd/MM/yyyy}{vbCrLf}" &
$"⏰ Orario: {conflittoEsterno.FasciaConflitto.FasciaOraria.OraInizio} - {conflittoEsterno.FasciaConflitto.FasciaOraria.OraFine}{vbCrLf}{vbCrLf}" &
$"Non c'è sovrapposizione, ma verifica la fattibilità.")
'Dim res = MessageBox.Show(formPadre,
' $"⚠️ ATTENZIONE!{vbCrLf}{vbCrLf}" &
' $"Il dipendente ha già un turno in un altro ruolo:{vbCrLf}" &
' $"{conflittoEsterno.Messaggio}{vbCrLf}{vbCrLf}" &
' $"Non c'è sovrapposizione oraria, ma verifica la fattibilità.",
' titolo, MessageBoxButtons.OK, MessageBoxIcon.Warning)
haConflittoEsterno = True
' Prosegui con la selezione (non facciamo Return)
End If
End If
' ✅ 3. CONTROLLA CONFLITTI INTERNI (STESSO RUOLO - UI)
Dim haConflittoInterno As Boolean = False
Dim haConflittoGraveInterno As Boolean = False
For Each c In _tutteCombo.Where(Function(x) x.FasciaID <> fasciaID)
If c.ComboBox.SelectedValue IsNot Nothing AndAlso CInt(c.ComboBox.SelectedValue) = dipendenteID Then
haConflittoInterno = True
If fasciaCorrente IsNot Nothing Then
Dim fasciaAltra = righeTabella.Fasce.FirstOrDefault(Function(f) f.FasciaOraria.ID = c.FasciaID)
If fasciaAltra IsNot Nothing AndAlso FasceSiSovrappongono(fasciaCorrente, fasciaAltra) Then
haConflittoGraveInterno = True
Exit For
End If
End If
End If
Next
' ✅ 4. APPLICA COLORE (a questa combo)
If haConflittoGraveInterno OrElse (haConflittoEsterno AndAlso conflittoEsterno.HaSovrapposizione) Then
' 🔴 ROSSO: Conflitto grave interno OPPURE sovrapposizione esterna
cmb.BackColor = Color.FromArgb(255, 150, 150)
ElseIf haConflittoEsterno OrElse haConflittoInterno Then
' 🟡 GIALLO: Conflitto esterno (stesso giorno, no sovrapposizione) OPPURE conflitto interno (stesso giorno, no sovrapposizione)
cmb.BackColor = Color.FromArgb(255, 255, 150)
Else
' 🟢 VERDE: Nessuno conflitto
cmb.BackColor = Color.FromArgb(150, 255, 150)
End If
' ✅ 5. AGGIORNA FILTRI ALTRE COMBO
AggiornaFiltriComboEsclusa(cmb)
' ✅ NOTIFICA AL FORM
RaiseEvent ComboBoxDipendenteCambiato(Me.Data, fasciaID, slot, dipendenteID, haConflitto)
' ✅ 6. RICALCOLA COLORI DI TUTTE LE COMBO
RicalcolaColoriTutteCombo()
Debug.WriteLine($"[Controllo] Combo: Fascia={fasciaID}, Slot={slot}, Dip={dipendenteID}, Conflitto={haConflitto}")
' ✅ 7. NOTIFICA AL FORM
' Se c'è un conflitto esterno, segnalalo come conflitto "interno" ai fini della UI generale,
' così il form padre sa che c'è un'avvertenza da gestire.
Dim segnalaConflittoUI As Boolean = haConflittoInterno OrElse haConflittoEsterno
Dim segnalaConflittoGraveUI As Boolean = haConflittoGraveInterno OrElse (haConflittoEsterno AndAlso conflittoEsterno.HaSovrapposizione)
RaiseEvent ComboBoxDipendenteCambiato(Me.Data, fasciaID, slot, dipendenteID, segnalaConflittoUI, segnalaConflittoGraveUI)
Debug.WriteLine($"[Controllo] Fascia={fasciaID}, Slot={slot}, Dip={dipendenteID}, ConflittoUI={haConflittoInterno}")
End Sub
' ✅ CONTROLLA CONFLITTI CON ALTRI RUOLI (DATABASE)
Private Function VerificaConflittiEsterni(dipendenteID As Integer, fasciaCorrente As Fascia) As ConflittoInfo
Dim info As New ConflittoInfo()
Try
' Recupera tutti i turni del dipendente nella data corrente
Dim turniEsistenti = Gestionale.gestioneTurni.GetTurniDipendente(dipendenteID, Me.Data, Me.Data)
For Each turno In turniEsistenti
' 1. Escludi il turno corrente se stiamo modificando lo stesso identico turno
If turno.RuoloID = righeTabella.RuoloID Then
Continue For ' Stesso ruolo, gestito dai controlli interni UI
End If
' 2. Recupera dettagli fascia del turno trovato
Dim fasciaTurno = Gestionale.gestioneFasce.GetFasciaById(turno.FasciaID)
If fasciaTurno Is Nothing OrElse fasciaTurno.FasciaOraria Is Nothing Then Continue For
' ✅ 3. RECUPERA NOME RUOLO (SPOSTATO PRIMA DEL CONTROLLO SOVRAPPOSIZIONE)
Dim nomeRuolo As String = $"Ruolo ID {turno.RuoloID}"
Try
If Gestionale.gestioneRuoli IsNot Nothing Then
Dim r = Gestionale.gestioneRuoli.GetRuolo(turno.RuoloID)
If r IsNot Nothing Then nomeRuolo = r.Nome
End If
Catch : End Try
' 4. Controlla sovrapposizione
If FasceSiSovrappongono(fasciaCorrente, fasciaTurno) Then
' ❌ SOVRAPPOSIZIONE TROVATA (GRAVE)
info.HaConflitto = True
info.HaSovrapposizione = True
info.TurnoConflitto = turno
info.FasciaConflitto = fasciaTurno
info.Messaggio = $"Data: {Me.Data:dd/MM/yyyy}{vbCrLf}" &
$"Ruolo: {nomeRuolo}{vbCrLf}" &
$"Orario: {fasciaTurno.FasciaOraria.OraInizio} - {fasciaTurno.FasciaOraria.OraFine}"
Return info ' Esci subito al primo conflitto grave
Else
' ⚠️ STESSO GIORNO, NESSUNA SOVRAPPOSIZIONE (AVVISO)
info.HaConflitto = True
info.HaSovrapposizione = False
info.TurnoConflitto = turno ' ✅ SALVA I DATI PER IL TOOLTIP
info.FasciaConflitto = fasciaTurno ' ✅ SALVA I DATI PER IL TOOLTIP
' Salva il messaggio solo se non esiste già (precedenza al grave)
If String.IsNullOrEmpty(info.Messaggio) Then
info.Messaggio = $"Data: {Me.Data:dd/MM/yyyy}{vbCrLf}" &
$"Ruolo: {nomeRuolo}{vbCrLf}" &
$"Orario: {fasciaTurno.FasciaOraria.OraInizio} - {fasciaTurno.FasciaOraria.OraFine}"
End If
' Non fare Return, continua a cercare se c'è qualche sovrapposizione grave
End If
Next
Catch ex As Exception
Debug.WriteLine($"[ERRORE DB] VerificaConflittiEsterni: {ex.Message}")
End Try
Return info
End Function
Private Function ControllaConflittiDatabase(dipendenteID As Integer,
ruoloEsclusoID As Integer,
fasciaCorrente As Fascia,
data As Date) As Boolean
Try
' ← Recupera turni esistenti dal database
Dim turniEsistenti = Gestionale.gestioneTurni.GetTurniDipendente(dipendenteID, data, data)
For Each turno In turniEsistenti
' ← Escludi il turno corrente (se stiamo modificando)
If turno.RuoloID = ruoloEsclusoID AndAlso turno.FasciaID = fasciaCorrente.FasciaOraria.ID Then
Continue For
End If
' ← Recupera fascia del turno esistente
Dim fasciaTurno = Gestionale.gestioneFasce.GetFasciaById(turno.FasciaID)
If fasciaTurno IsNot Nothing AndAlso fasciaTurno.FasciaOraria IsNot Nothing Then
' ← Controlla sovrapposizione
If FasceSiSovrappongono(fasciaCorrente, fasciaTurno) Then
Debug.WriteLine($"[DB Conflitto] Dip={dipendenteID} ha già turno il {data:dd/MM} fascia {turno.FasciaID}")
Return True
End If
End If
Next
Catch ex As Exception
Debug.WriteLine($"[ERRORE DB] Controllo conflitti: {ex.Message}")
End Try
Return False
End Function
' ✅ ESTRAE TUTTI I TURNI DA QUESTO PANNELLO
Public Function EstraiTurni() As List(Of Turno)
Dim turni As New List(Of Turno)()
' ← CICLO SINGOLO (non duplicato)
For Each fascia In righeTabella.Fasce
' ← CREA VARIABILI LOCALI PER CATTURARE I VALORI
Dim fasciaCorrente = fascia
Dim fasciaID As Integer = fascia.FasciaOraria.ID
Dim personeNecessarie As Integer = fascia.PersoneNecessarie
For slot As Integer = 1 To personeNecessarie
' ← CATTURA IL VALORE DI SLOT IN VARIABILE LOCALE
Dim slotCorrente As Integer = slot
Dim comboInfo = _tutteCombo.FirstOrDefault(Function(c) c.FasciaID = fasciaID AndAlso c.Slot = slotCorrente)
If comboInfo IsNot Nothing AndAlso comboInfo.ComboBox.SelectedValue IsNot Nothing Then
Dim dipID As Integer = CInt(comboInfo.ComboBox.SelectedValue)
If dipID > 0 Then
Dim dip = comboInfo.ListaOriginale.FirstOrDefault(Function(d) d.ID = dipID)
turni.Add(New Turno With {
.Data = Me.Data,
.RuoloID = righeTabella.RuoloID,
.FasciaID = fasciaID,
.DipendenteID = dipID,
.DipendenteNome = If(dip IsNot Nothing, dip.Nome, ""),
.DipendenteCognome = If(dip IsNot Nothing, dip.Cognome, ""),
.OrdineVisualizzazione = slotCorrente
})
End If
End If
Next
Next
Debug.WriteLine($"[Controllo {Data:dd/MM}] Estratti {turni.Count} turni")
Return turni
End Function
' ✅ CONTROLLA SE DUE FASCE SI SOVRAPPONGONO
Private Function FasceSiSovrappongono(fascia1 As Fascia, fascia2 As Fascia) As Boolean
Dim inizio1 As TimeSpan
Dim fine1 As TimeSpan
Dim inizio2 As TimeSpan
Dim fine2 As TimeSpan
If Not TimeSpan.TryParse(fascia1.FasciaOraria.OraInizio, inizio1) Then Return False
If Not TimeSpan.TryParse(fascia1.FasciaOraria.OraFine, fine1) Then Return False
If Not TimeSpan.TryParse(fascia2.FasciaOraria.OraInizio, inizio2) Then Return False
If Not TimeSpan.TryParse(fascia2.FasciaOraria.OraFine, fine2) Then Return False
' Gestione mezzanotte
If fine1 < inizio1 Then fine1 = fine1.Add(New TimeSpan(24, 0, 0))
If fine2 < inizio2 Then fine2 = fine2.Add(New TimeSpan(24, 0, 0))
' ✅ LOGICA SOVRAPPOSIZIONE: due intervalli si sovrappongono se...
' inizio1 < fine2 AND inizio2 < fine1
Return inizio1 < fine2 AndAlso inizio2 < fine1
End Function
' ✅ AGGIORNA SOLO I FILTRI DELLE ALTRE COMBO (SENZA CAMBIARE DATASOURCE)
' ✅ AGGIORNA SOLO I FILTRI DELLE ALTRE COMBO (CON CONTROLLO SOVRAPPOSIZIONE)
Private Sub AggiornaFiltriComboEsclusa(comboEsclusa As ComboBox)
_staAggiornando = True
Try
' ✅ OTTIENI DIPENDENTI SELEZIONATI IN TUTTE LE FASCE
Dim selezionatiPerFascia As New Dictionary(Of Integer, List(Of Integer))()
For Each ci In _tutteCombo
If ci.ComboBox.SelectedValue IsNot Nothing AndAlso CInt(ci.ComboBox.SelectedValue) > 0 Then
If Not selezionatiPerFascia.ContainsKey(ci.FasciaID) Then
selezionatiPerFascia(ci.FasciaID) = New List(Of Integer)()
End If
selezionatiPerFascia(ci.FasciaID).Add(CInt(ci.ComboBox.SelectedValue))
End If
Next
' ✅ AGGIORNA OGNI COMBO (TRANNE QUELLA CHE HA TRIGGERATO)
For Each ci In _tutteCombo
If ci.ComboBox Is comboEsclusa Then Continue For
' ✅ SALVA SELEZIONE CORRENTE
' ✅ SALVA SELEZIONE CORRENTE DI QUESTA SPECIFICA COMBO
Dim selezioneCorrente = ci.ComboBox.SelectedValue
Dim selezioneCorrenteID As Integer = If(selezioneCorrente IsNot Nothing, CInt(selezioneCorrente), 0)
' ✅ FILTRA LISTA
Dim selezionatiNellaStessaFascia As New List(Of Integer)() ' ✅ CORRETTO
If selezionatiPerFascia.ContainsKey(ci.FasciaID) Then
selezionatiNellaStessaFascia = selezionatiPerFascia(ci.FasciaID) _
.Where(Function(id) id <> CInt(If(selezioneCorrente IsNot Nothing, selezioneCorrente, 0))) _
.ToList()
End If
' ✅ 1. OTTIENI DIPENDENTI BLOCCATI PER SOVRAPPOSIZIONE ORARIA
Dim bloccatiPerOrario = GetDipendentiOccupatiInFasceSovrapposte(ci.FasciaID, ci.ComboBox)
Dim listaFiltrata = ci.ListaOriginale.Where(Function(d) d.ID = 0 OrElse Not selezionatiNellaStessaFascia.Contains(d.ID)).ToList()
' ✅ 2. OTTIENI DIPENDENTI BLOCCATI PER STESSA FASCIA (Duplicati)
Dim bloccatiStessaFascia As New List(Of Integer)()
For Each c In _tutteCombo.Where(Function(x) x.FasciaID = ci.FasciaID AndAlso x.ComboBox IsNot ci.ComboBox)
If c.ComboBox.SelectedValue IsNot Nothing AndAlso CInt(c.ComboBox.SelectedValue) > 0 Then
bloccatiStessaFascia.Add(CInt(c.ComboBox.SelectedValue))
End If
Next
' ✅ AGGIORNA DATASOURCE SENZA TRIGGERARE EVENTO
' ✅ 3. UNISCI LE LISTE DI BLOCCO
Dim tuttiIBloccati = bloccatiPerOrario.Union(bloccatiStessaFascia).Distinct().ToList()
' ✅ 4. FILTRA LISTA
' NOTA: Manteniamo la selezioneCorrente nella lista anche se è bloccata,
' per non cancellare automaticamente una selezione esistente (che magari è rossa per conflitto)
Dim listaFiltrata = ci.ListaOriginale.Where(Function(d) d.ID = 0 OrElse
Not tuttiIBloccati.Contains(d.ID) OrElse
d.ID = selezioneCorrenteID
).ToList()
' ✅ 5. AGGIORNA DATASOURCE SENZA TRIGGERARE EVENTO
RemoveHandler ci.ComboBox.SelectedIndexChanged, AddressOf ComboBoxDipendente_SelectedIndexChanged
ci.ComboBox.DataSource = New BindingSource(listaFiltrata, Nothing)
ci.ComboBox.DisplayMember = "NomeCompleto"
@@ -335,31 +681,38 @@ Public Class FasciaRowControl
_staAggiornando = False
End Try
End Sub
' ✅ FILTRA LISTA QUANDO SI APRE IL DROPDOWN (CON CONTROLLO SOVRAPPOSIZIONE)
Private Sub ComboBoxDropDown_FiltraLista(sender As Object, e As EventArgs)
' ✅ ESCI SE STA GIA' AGGIORNANDO
If _staAggiornando Then Return
Dim cmb As ComboBox = CType(sender, ComboBox)
Dim comboInfo = _tutteCombo.FirstOrDefault(Function(c) c.ComboBox Is cmb)
If comboInfo Is Nothing Then Return
' ✅ OTTIENI DIPENDENTI GIA' SELEZIONATI NELLA STESSA FASCIA
Dim selezionatiNellaFascia As New List(Of Integer)()
For Each c In _tutteCombo.Where(Function(x) x.FasciaID = comboInfo.FasciaID AndAlso x.ComboBox IsNot cmb)
If c.ComboBox.SelectedValue IsNot Nothing AndAlso CInt(c.ComboBox.SelectedValue) > 0 Then
selezionatiNellaFascia.Add(CInt(c.ComboBox.SelectedValue))
End If
Next
' ✅ SALVA SELEZIONE CORRENTE
Dim selezioneCorrente = cmb.SelectedValue
Dim selezioneCorrenteID As Integer = If(selezioneCorrente IsNot Nothing, CInt(selezioneCorrente), 0)
' ✅ FILTRA LISTA
Dim listaFiltrata = comboInfo.ListaOriginale.Where(Function(d) d.ID = 0 OrElse Not selezionatiNellaFascia.Contains(d.ID)).ToList()
' ✅ 1. OTTIENI DIPENDENTI BLOCCATI PER SOVRAPPOSIZIONE ORARIA
Dim bloccatiPerOrario = GetDipendentiOccupatiInFasceSovrapposte(comboInfo.FasciaID, cmb)
' ✅ AGGIORNA DATASOURCE SENZA TRIGGERARE EVENTO
' ✅ 2. OTTIENI DIPENDENTI BLOCCATI PER STESSA FASCIA (Duplicati)
Dim bloccatiStessaFascia As New List(Of Integer)()
For Each c In _tutteCombo.Where(Function(x) x.FasciaID = comboInfo.FasciaID AndAlso x.ComboBox IsNot cmb)
If c.ComboBox.SelectedValue IsNot Nothing AndAlso CInt(c.ComboBox.SelectedValue) > 0 Then
bloccatiStessaFascia.Add(CInt(c.ComboBox.SelectedValue))
End If
Next
' ✅ 3. UNISCI E FILTRA
Dim tuttiIBloccati = bloccatiPerOrario.Union(bloccatiStessaFascia).Distinct().ToList()
Dim listaFiltrata = comboInfo.ListaOriginale.Where(Function(d) d.ID = 0 OrElse
Not tuttiIBloccati.Contains(d.ID) OrElse
d.ID = selezioneCorrenteID
).ToList()
' ✅ AGGIORNA DATASOURCE
RemoveHandler cmb.SelectedIndexChanged, AddressOf ComboBoxDipendente_SelectedIndexChanged
cmb.DataSource = New BindingSource(listaFiltrata, Nothing)
cmb.DisplayMember = "NomeCompleto"
@@ -371,7 +724,7 @@ Public Class FasciaRowControl
End If
AddHandler cmb.SelectedIndexChanged, AddressOf ComboBoxDipendente_SelectedIndexChanged
End Sub
End Sub
' ✅ AGGIORNA TUTTE LE COMBOBOX DOPO UN CAMBIAMENTO
Private Sub AggiornaTutteLeCombo()
For Each comboInfo In _tutteCombo
@@ -482,6 +835,55 @@ Public Class FasciaRowControl
_tutteCombo.Clear()
MyBase.OnHandleDestroyed(e)
End Sub
' ✅ RICALCOLA I COLORI DI TUTTE LE COMBOBOX (INCLUSI CONFLITTI ESTERNI)
Private Sub RicalcolaColoriTutteCombo()
For Each comboInfo In _tutteCombo
Dim cmb = comboInfo.ComboBox
Dim fasciaID = comboInfo.FasciaID
Dim slot = comboInfo.Slot
Dim dipendenteID = If(cmb.SelectedValue IsNot Nothing, CInt(cmb.SelectedValue), 0)
' Se vuoto, bianco
If dipendenteID = 0 Then
cmb.BackColor = Color.White
Continue For
End If
' ✅ 1. CONTROLLA CONFLITTI ESTERNI (DATABASE)
Dim fasciaCorrente = righeTabella.Fasce.FirstOrDefault(Function(f) f.FasciaOraria.ID = fasciaID)
Dim conflittoEsterno = VerificaConflittiEsterni(dipendenteID, fasciaCorrente)
Dim haConflittoEsterno As Boolean = conflittoEsterno.HaConflitto
' ✅ 2. CONTROLLA CONFLITTI INTERNI (UI)
Dim haConflittoInterno As Boolean = False
Dim haConflittoGraveInterno As Boolean = False
For Each c In _tutteCombo.Where(Function(x) x.FasciaID <> fasciaID)
If c.ComboBox.SelectedValue IsNot Nothing AndAlso CInt(c.ComboBox.SelectedValue) = dipendenteID Then
haConflittoInterno = True
If fasciaCorrente IsNot Nothing Then
Dim fasciaAltra = righeTabella.Fasce.FirstOrDefault(Function(f) f.FasciaOraria.ID = c.FasciaID)
If fasciaAltra IsNot Nothing AndAlso FasceSiSovrappongono(fasciaCorrente, fasciaAltra) Then
haConflittoGraveInterno = True
Exit For
End If
End If
End If
Next
' ✅ 3. APPLICA COLORE (3 livelli con priorità)
If haConflittoGraveInterno OrElse (haConflittoEsterno AndAlso conflittoEsterno.HaSovrapposizione) Then
cmb.BackColor = Color.FromArgb(255, 150, 150) ' 🔴 Rosso
ElseIf haConflittoEsterno OrElse haConflittoInterno Then
cmb.BackColor = Color.FromArgb(255, 255, 150) ' 🟡 Giallo
Else
cmb.BackColor = Color.FromArgb(150, 255, 150) ' 🟢 Verde
End If
cmb.Refresh()
Next
End Sub
Private Sub tlpFasce_Paint(sender As Object, e As PaintEventArgs) Handles tlpFasce.Paint
@@ -490,7 +892,7 @@ End Class
Public Class RigheTabella
Private _fascia As List(Of Fascia)
Public data As Date
Public Property Fasce As List(Of Fascia)
Get
Return _fascia
@@ -500,6 +902,8 @@ Public Class RigheTabella
End Set
End Property
Public Property RuoloID As Integer
' ✅ METODO UTILE PER CONTARE LE RIGHE TOTALI
Public Function GetTotaleRighe() As Integer
If _fascia Is Nothing Then Return 0

View File

@@ -22,27 +22,19 @@ Partial Class Form1
'Non modificarla mediante l'editor del codice.
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.Button1 = New System.Windows.Forms.Button()
Me.gridDipendenti = New System.Windows.Forms.DataGridView()
Me.Button2 = New System.Windows.Forms.Button()
Me.Button3 = New System.Windows.Forms.Button()
Me.BtnModificaDip = New System.Windows.Forms.Button()
Me.CheckedRuoli = New System.Windows.Forms.CheckedListBox()
Me.Button4 = New System.Windows.Forms.Button()
Me.BtnEliminaDip = New System.Windows.Forms.Button()
Me.Button5 = New System.Windows.Forms.Button()
Me.TextBox1 = New System.Windows.Forms.TextBox()
Me.lblRisultati = New System.Windows.Forms.Label()
Me.Button1 = New System.Windows.Forms.Button()
Me.CheckedRuoliTabella = New System.Windows.Forms.CheckedListBox()
CType(Me.gridDipendenti, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(12, 12)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(127, 23)
Me.Button1.TabIndex = 0
Me.Button1.Text = "Nuovo dipendente"
Me.Button1.UseVisualStyleBackColor = True
'
'gridDipendenti
'
Me.gridDipendenti.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
@@ -53,21 +45,21 @@ Partial Class Form1
'
'Button2
'
Me.Button2.Location = New System.Drawing.Point(145, 12)
Me.Button2.Location = New System.Drawing.Point(12, 12)
Me.Button2.Name = "Button2"
Me.Button2.Size = New System.Drawing.Size(75, 23)
Me.Button2.Size = New System.Drawing.Size(127, 23)
Me.Button2.TabIndex = 2
Me.Button2.Text = "Settaggi"
Me.Button2.UseVisualStyleBackColor = True
'
'Button3
'BtnModificaDip
'
Me.Button3.Location = New System.Drawing.Point(661, 206)
Me.Button3.Name = "Button3"
Me.Button3.Size = New System.Drawing.Size(127, 23)
Me.Button3.TabIndex = 3
Me.Button3.Text = "Modifica Dipendente"
Me.Button3.UseVisualStyleBackColor = True
Me.BtnModificaDip.Location = New System.Drawing.Point(661, 206)
Me.BtnModificaDip.Name = "BtnModificaDip"
Me.BtnModificaDip.Size = New System.Drawing.Size(127, 23)
Me.BtnModificaDip.TabIndex = 3
Me.BtnModificaDip.Text = "Modifica Dipendente"
Me.BtnModificaDip.UseVisualStyleBackColor = True
'
'CheckedRuoli
'
@@ -78,14 +70,14 @@ Partial Class Form1
Me.CheckedRuoli.Size = New System.Drawing.Size(120, 154)
Me.CheckedRuoli.TabIndex = 4
'
'Button4
'BtnEliminaDip
'
Me.Button4.Location = New System.Drawing.Point(12, 206)
Me.Button4.Name = "Button4"
Me.Button4.Size = New System.Drawing.Size(127, 23)
Me.Button4.TabIndex = 5
Me.Button4.Text = "Elimina dipendente"
Me.Button4.UseVisualStyleBackColor = True
Me.BtnEliminaDip.Location = New System.Drawing.Point(12, 206)
Me.BtnEliminaDip.Name = "BtnEliminaDip"
Me.BtnEliminaDip.Size = New System.Drawing.Size(127, 23)
Me.BtnEliminaDip.TabIndex = 5
Me.BtnEliminaDip.Text = "Elimina dipendente"
Me.BtnEliminaDip.UseVisualStyleBackColor = True
'
'Button5
'
@@ -112,20 +104,38 @@ Partial Class Form1
Me.lblRisultati.TabIndex = 8
Me.lblRisultati.Text = "Label1"
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(12, 308)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(75, 23)
Me.Button1.TabIndex = 9
Me.Button1.Text = "Button1"
Me.Button1.UseVisualStyleBackColor = True
'
'CheckedRuoliTabella
'
Me.CheckedRuoliTabella.FormattingEnabled = True
Me.CheckedRuoliTabella.Location = New System.Drawing.Point(93, 308)
Me.CheckedRuoliTabella.Name = "CheckedRuoliTabella"
Me.CheckedRuoliTabella.Size = New System.Drawing.Size(120, 94)
Me.CheckedRuoliTabella.TabIndex = 10
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(958, 450)
Me.Controls.Add(Me.CheckedRuoliTabella)
Me.Controls.Add(Me.Button1)
Me.Controls.Add(Me.lblRisultati)
Me.Controls.Add(Me.TextBox1)
Me.Controls.Add(Me.Button5)
Me.Controls.Add(Me.Button4)
Me.Controls.Add(Me.BtnEliminaDip)
Me.Controls.Add(Me.CheckedRuoli)
Me.Controls.Add(Me.Button3)
Me.Controls.Add(Me.BtnModificaDip)
Me.Controls.Add(Me.Button2)
Me.Controls.Add(Me.gridDipendenti)
Me.Controls.Add(Me.Button1)
Me.Name = "Form1"
Me.Text = "Form1"
CType(Me.gridDipendenti, System.ComponentModel.ISupportInitialize).EndInit()
@@ -133,14 +143,14 @@ Partial Class Form1
Me.PerformLayout()
End Sub
Friend WithEvents Button1 As Button
Friend WithEvents gridDipendenti As DataGridView
Friend WithEvents Button2 As Button
Friend WithEvents Button3 As Button
Friend WithEvents BtnModificaDip As Button
Friend WithEvents CheckedRuoli As CheckedListBox
Friend WithEvents Button4 As Button
Friend WithEvents BtnEliminaDip As Button
Friend WithEvents Button5 As Button
Friend WithEvents TextBox1 As TextBox
Friend WithEvents lblRisultati As Label
Friend WithEvents Button1 As Button
Friend WithEvents CheckedRuoliTabella As CheckedListBox
End Class

View File

@@ -18,6 +18,7 @@
End If
Gestionale.PopolaCheckedListBox_T(Of Ruolo)(CheckedRuoli, Gestionale.gestioneRuoli.GetRuoli)
Gestionale.PopolaCheckedListBox_T(Of Ruolo)(CheckedRuoliTabella, Gestionale.gestioneRuoli.GetRuoli)
PopolaGrigliaDipendenti()
End Sub
@@ -38,7 +39,7 @@
lblRisultati.Text = $"Dipendenti trovati: {listaFiltrata.Count}"
Gestionale.PopolaGriglia(gridDipendenti, listaFiltrata)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Private Sub BtnNuovoDip_Click(sender As Object, e As EventArgs)
FormDipendente.Show()
End Sub
@@ -48,7 +49,7 @@
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles BtnModificaDip.Click
Dim dip = DipendenteSelezionato()
'If dip Is Nothing Then
@@ -79,7 +80,7 @@
Gestionale.ChecklistBox_Spunta(CheckedRuoli, lista)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles BtnEliminaDip.Click
Dim dip = DipendenteSelezionato()
If dip IsNot Nothing Then
@@ -103,4 +104,57 @@
Private Sub CheckedRuoli_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CheckedRuoli.SelectedIndexChanged
Me.BeginInvoke(Sub() PopolaGrigliaDipendenti())
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim listaID = Gestionale.listaID_ChecklistBox(CheckedRuoliTabella)
Try
Dim dataInizio As Date = Date.Today
Dim dataFine As Date = Date.Today.AddDays(6)
Debug.WriteLine($"📅 Intervallo: {dataInizio:dd/MM} - {dataFine:dd/MM}")
Dim configurazioni As New List(Of TabellaConfig)()
Dim dataCorrente As Date = dataInizio
While dataCorrente <= dataFine
Dim Ruoli As New List(Of Ruolo)
For Each id In listaID
Ruoli.Add(Gestionale.gestioneRuoli.GetRuolo(id))
Next
' ✅ CARICA FASCE CON TURNI ESISTENTI DAL DB
Dim fasce = Gestionale.gestioneOrariFasce.GetFasce_Complete(dataCorrente, Ruoli)
configurazioni.Add(New TabellaConfig With {
.Data = dataCorrente,
.Fasce = fasce
})
dataCorrente = dataCorrente.AddDays(1)
End While
Dim form As New FormTabella()
form.CaricaMultipleGiornate(configurazioni)
form.DateTimeDal.Value = dataInizio
form.DateTimeAl.Value = dataFine
form.Show()
Catch ex As Exception
Debug.WriteLine($"❌ ERRORE: {ex.ToString()}")
MessageBox.Show($"Errore: {ex.Message}", "Errore")
End Try
End Sub
'Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Dim ruolo = Gestionale.gestioneRuoli.GetRuoli()(0)
' Dim fasce = Gestionale.gestioneOrariFasce.GetFasce_Complete(Date.Today, ruolo.ID)
' Dim config As New TabellaConfig With {
' .Data = DateTime.Today, .RuoloID = ruolo.ID, .RuoloNome = ruolo.Nome, .Fasce = fasce
' }
' Dim form As New FormTabella()
' form.CaricaTabelle(New List(Of TabellaConfig) From {config}, New List(Of Dipendente)())
' form.Show()
'End Sub
End Class

View File

@@ -72,6 +72,7 @@ Partial Class FormDipendente
Me.ComboTipoAssenza = New System.Windows.Forms.ComboBox()
Me.Label10 = New System.Windows.Forms.Label()
Me.Label9 = New System.Windows.Forms.Label()
Me.BtnNuovoDip = New System.Windows.Forms.Button()
Me.GroupBox1.SuspendLayout()
Me.Panel1.SuspendLayout()
Me.GroupBox4.SuspendLayout()
@@ -83,6 +84,7 @@ Partial Class FormDipendente
'GroupBox1
'
Me.GroupBox1.BackColor = System.Drawing.SystemColors.ActiveCaption
Me.GroupBox1.Controls.Add(Me.BtnNuovoDip)
Me.GroupBox1.Controls.Add(Me.Panel1)
Me.GroupBox1.Controls.Add(Me.HScrollBar1)
Me.GroupBox1.Controls.Add(Me.TextTot)
@@ -136,11 +138,11 @@ Partial Class FormDipendente
'TextTot
'
Me.TextTot.BackColor = System.Drawing.Color.White
Me.TextTot.Location = New System.Drawing.Point(653, 13)
Me.TextTot.Location = New System.Drawing.Point(665, 13)
Me.TextTot.Multiline = True
Me.TextTot.Name = "TextTot"
Me.TextTot.ReadOnly = True
Me.TextTot.Size = New System.Drawing.Size(232, 153)
Me.TextTot.Size = New System.Drawing.Size(220, 228)
Me.TextTot.TabIndex = 40
'
'GroupBox4
@@ -183,16 +185,16 @@ Partial Class FormDipendente
'
'BtnAnnullla
'
Me.BtnAnnullla.Location = New System.Drawing.Point(654, 189)
Me.BtnAnnullla.Location = New System.Drawing.Point(181, 201)
Me.BtnAnnullla.Name = "BtnAnnullla"
Me.BtnAnnullla.Size = New System.Drawing.Size(155, 23)
Me.BtnAnnullla.Size = New System.Drawing.Size(148, 23)
Me.BtnAnnullla.TabIndex = 37
Me.BtnAnnullla.Text = "❌ Annulla"
Me.BtnAnnullla.UseVisualStyleBackColor = True
'
'btnSalvaDipendente
'
Me.btnSalvaDipendente.Location = New System.Drawing.Point(654, 218)
Me.btnSalvaDipendente.Location = New System.Drawing.Point(335, 201)
Me.btnSalvaDipendente.Name = "btnSalvaDipendente"
Me.btnSalvaDipendente.Size = New System.Drawing.Size(155, 23)
Me.btnSalvaDipendente.TabIndex = 33
@@ -413,7 +415,7 @@ Partial Class FormDipendente
'CheckedListFasce
'
Me.CheckedListFasce.FormattingEnabled = True
Me.CheckedListFasce.Location = New System.Drawing.Point(18, 150)
Me.CheckedListFasce.Location = New System.Drawing.Point(18, 180)
Me.CheckedListFasce.Name = "CheckedListFasce"
Me.CheckedListFasce.Size = New System.Drawing.Size(277, 169)
Me.CheckedListFasce.TabIndex = 34
@@ -430,7 +432,7 @@ Partial Class FormDipendente
'lblGiorniDettaglio
'
Me.lblGiorniDettaglio.AutoSize = True
Me.lblGiorniDettaglio.Location = New System.Drawing.Point(6, 418)
Me.lblGiorniDettaglio.Location = New System.Drawing.Point(6, 432)
Me.lblGiorniDettaglio.Name = "lblGiorniDettaglio"
Me.lblGiorniDettaglio.Size = New System.Drawing.Size(45, 13)
Me.lblGiorniDettaglio.TabIndex = 32
@@ -439,7 +441,7 @@ Partial Class FormDipendente
'Label13
'
Me.Label13.AutoSize = True
Me.Label13.Location = New System.Drawing.Point(15, 127)
Me.Label13.Location = New System.Drawing.Point(14, 96)
Me.Label13.Name = "Label13"
Me.Label13.Size = New System.Drawing.Size(67, 13)
Me.Label13.TabIndex = 31
@@ -447,7 +449,7 @@ Partial Class FormDipendente
'
'TxtMotivazione
'
Me.TxtMotivazione.Location = New System.Drawing.Point(88, 124)
Me.TxtMotivazione.Location = New System.Drawing.Point(87, 93)
Me.TxtMotivazione.Name = "TxtMotivazione"
Me.TxtMotivazione.Size = New System.Drawing.Size(207, 20)
Me.TxtMotivazione.TabIndex = 30
@@ -455,7 +457,7 @@ Partial Class FormDipendente
'lblPeriodo
'
Me.lblPeriodo.AutoSize = True
Me.lblPeriodo.Location = New System.Drawing.Point(6, 396)
Me.lblPeriodo.Location = New System.Drawing.Point(6, 419)
Me.lblPeriodo.Name = "lblPeriodo"
Me.lblPeriodo.Size = New System.Drawing.Size(45, 13)
Me.lblPeriodo.TabIndex = 29
@@ -463,7 +465,7 @@ Partial Class FormDipendente
'
'btnAnnullaAssenza
'
Me.btnAnnullaAssenza.Location = New System.Drawing.Point(220, 325)
Me.btnAnnullaAssenza.Location = New System.Drawing.Point(220, 355)
Me.btnAnnullaAssenza.Name = "btnAnnullaAssenza"
Me.btnAnnullaAssenza.Size = New System.Drawing.Size(75, 23)
Me.btnAnnullaAssenza.TabIndex = 10
@@ -472,7 +474,7 @@ Partial Class FormDipendente
'
'btnEliminaAssenza
'
Me.btnEliminaAssenza.Location = New System.Drawing.Point(112, 325)
Me.btnEliminaAssenza.Location = New System.Drawing.Point(112, 355)
Me.btnEliminaAssenza.Name = "btnEliminaAssenza"
Me.btnEliminaAssenza.Size = New System.Drawing.Size(75, 23)
Me.btnEliminaAssenza.TabIndex = 9
@@ -481,7 +483,7 @@ Partial Class FormDipendente
'
'btnSalvaAssenza
'
Me.btnSalvaAssenza.Location = New System.Drawing.Point(18, 325)
Me.btnSalvaAssenza.Location = New System.Drawing.Point(18, 355)
Me.btnSalvaAssenza.Name = "btnSalvaAssenza"
Me.btnSalvaAssenza.Size = New System.Drawing.Size(75, 23)
Me.btnSalvaAssenza.TabIndex = 8
@@ -493,7 +495,7 @@ Partial Class FormDipendente
Me.ChkApprovata.AutoSize = True
Me.ChkApprovata.Checked = True
Me.ChkApprovata.CheckState = System.Windows.Forms.CheckState.Checked
Me.ChkApprovata.Location = New System.Drawing.Point(182, 49)
Me.ChkApprovata.Location = New System.Drawing.Point(18, 127)
Me.ChkApprovata.Name = "ChkApprovata"
Me.ChkApprovata.Size = New System.Drawing.Size(75, 17)
Me.ChkApprovata.TabIndex = 7
@@ -503,7 +505,7 @@ Partial Class FormDipendente
'Label12
'
Me.Label12.AutoSize = True
Me.Label12.Location = New System.Drawing.Point(157, 93)
Me.Label12.Location = New System.Drawing.Point(156, 62)
Me.Label12.Name = "Label12"
Me.Label12.Size = New System.Drawing.Size(19, 13)
Me.Label12.TabIndex = 6
@@ -512,7 +514,7 @@ Partial Class FormDipendente
'Label11
'
Me.Label11.AutoSize = True
Me.Label11.Location = New System.Drawing.Point(6, 93)
Me.Label11.Location = New System.Drawing.Point(5, 62)
Me.Label11.Name = "Label11"
Me.Label11.Size = New System.Drawing.Size(26, 13)
Me.Label11.TabIndex = 5
@@ -521,7 +523,7 @@ Partial Class FormDipendente
'DtpAssenzaDal
'
Me.DtpAssenzaDal.Format = System.Windows.Forms.DateTimePickerFormat.[Short]
Me.DtpAssenzaDal.Location = New System.Drawing.Point(38, 87)
Me.DtpAssenzaDal.Location = New System.Drawing.Point(37, 56)
Me.DtpAssenzaDal.Name = "DtpAssenzaDal"
Me.DtpAssenzaDal.Size = New System.Drawing.Size(113, 20)
Me.DtpAssenzaDal.TabIndex = 4
@@ -529,7 +531,7 @@ Partial Class FormDipendente
'DtpAssenzaAl
'
Me.DtpAssenzaAl.Format = System.Windows.Forms.DateTimePickerFormat.[Short]
Me.DtpAssenzaAl.Location = New System.Drawing.Point(182, 87)
Me.DtpAssenzaAl.Location = New System.Drawing.Point(181, 56)
Me.DtpAssenzaAl.Name = "DtpAssenzaAl"
Me.DtpAssenzaAl.Size = New System.Drawing.Size(110, 20)
Me.DtpAssenzaAl.TabIndex = 3
@@ -537,15 +539,15 @@ Partial Class FormDipendente
'ComboTipoAssenza
'
Me.ComboTipoAssenza.FormattingEnabled = True
Me.ComboTipoAssenza.Location = New System.Drawing.Point(43, 45)
Me.ComboTipoAssenza.Location = New System.Drawing.Point(55, 150)
Me.ComboTipoAssenza.Name = "ComboTipoAssenza"
Me.ComboTipoAssenza.Size = New System.Drawing.Size(121, 21)
Me.ComboTipoAssenza.Size = New System.Drawing.Size(240, 21)
Me.ComboTipoAssenza.TabIndex = 2
'
'Label10
'
Me.Label10.AutoSize = True
Me.Label10.Location = New System.Drawing.Point(6, 48)
Me.Label10.Location = New System.Drawing.Point(14, 153)
Me.Label10.Name = "Label10"
Me.Label10.Size = New System.Drawing.Size(31, 13)
Me.Label10.TabIndex = 1
@@ -560,6 +562,15 @@ Partial Class FormDipendente
Me.Label9.TabIndex = 0
Me.Label9.Text = "📝 NUOVA ASSENZA / MODIFICA "
'
'BtnNuovoDip
'
Me.BtnNuovoDip.Location = New System.Drawing.Point(20, 201)
Me.BtnNuovoDip.Name = "BtnNuovoDip"
Me.BtnNuovoDip.Size = New System.Drawing.Size(155, 23)
Me.BtnNuovoDip.TabIndex = 29
Me.BtnNuovoDip.Text = "Nuovo Dipendente"
Me.BtnNuovoDip.UseVisualStyleBackColor = True
'
'FormDipendente
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
@@ -632,4 +643,5 @@ Partial Class FormDipendente
Friend WithEvents Panel1 As Panel
Friend WithEvents VScrollBar1 As VScrollBar
Friend WithEvents HScrollBar1 As HScrollBar
Friend WithEvents BtnNuovoDip As Button
End Class

View File

@@ -2,12 +2,12 @@
Public Class FormDipendente
' --- VARIABILI PRIVATE ---
Private _dipendenteSelezionato As Dipendente
Private listaDipendenti As List(Of Dipendente)
Private _assenzaSelezionata As Assenza = Nothing
Private index = 0
Public Event DipendenteSelezionatoChanged(ByVal dip As Dipendente)
Private index As Integer = 0
Private _dipendenteSelezionato As Dipendente
' ✅ PROPERTY CON EVENTO (SOLO QUESTA, NON _dipendenteSelezionato)
Public Property dipendenteSelezionato As Dipendente
Get
Return _dipendenteSelezionato
@@ -15,72 +15,107 @@ Public Class FormDipendente
Set(value As Dipendente)
_dipendenteSelezionato = value
RaiseEvent DipendenteSelezionatoChanged(value)
popolaForm()
End Set
End Property
Public Event DipendenteSelezionatoChanged(ByVal dip As Dipendente)
' --- COSTRUTTORI ---
Public Sub New()
InitializeComponent()
End Sub
Public Sub New(dip As Dipendente)
InitializeComponent()
Me.dipendenteSelezionato = dip
End Sub
' --- MODIFICA DIPENDENTE (Da Form Esterno) ---
Public Sub ModificaDipendente(dip As Dipendente)
dipendenteSelezionato = dip
Me.dipendenteSelezionato = dip
If dip IsNot Nothing Then
CaricaDatiDipendente()
End If
GroupAssenza.Enabled = True
Me.Show()
End Sub
' --- TITOLO FORM ---
Private Sub setText()
Me.Text = $"👤 {If(dipendenteSelezionato IsNot Nothing, dipendenteSelezionato.NomeCompleto, "Nuovo Dipendente")}"
Me.Text = $"👤 {If(dipendenteSelezionato IsNot Nothing, $"{dipendenteSelezionato.ID}) {dipendenteSelezionato.NomeCompleto}", "Nuovo Dipendente")}"
End Sub
' --- CARICAMENTO FORM ---
Private Sub FormDipendente_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Debug.WriteLine($"=== FORM DIPENDENTE LOAD ===")
Debug.WriteLine($"dipendenteSelezionato: {If(dipendenteSelezionato IsNot Nothing, dipendenteSelezionato.ID.ToString(), "NULL")}")
VScrollBar1.BackColor = Color.LightGray
VScrollBar1.ForeColor = Color.DarkBlue
' ⚠️ CARICA PRIMA LA LISTA
listaDipendenti = Gestionale.gestioneDipendenti.GetDipendenti("")
Debug.WriteLine($"Lista dipendenti caricata: {listaDipendenti.Count}")
If listaDipendenti.Count = 0 Then Return
If listaDipendenti.Count = 0 Then
Debug.WriteLine("⚠️ Nessun dipendente nella lista!")
MessageBox.Show("Nessun dipendente presente nel database!", "Attenzione", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Me.Close()
Return
End If
VScrollBar1.Maximum = listaDipendenti.Count - 1
' ✅ SELEZIONA IL DIPENDENTE CORRETTO
If dipendenteSelezionato Is Nothing Then
' Primo dipendente della lista
index = 0
dipendenteSelezionato = listaDipendenti(index)
Debug.WriteLine($"Nessun dipendente passato, uso il primo: {dipendenteSelezionato.ID}")
Else
' ⚠️ TROVA L'INDICE CONFRONTANDO L'ID (NON IL RIFERIMENTO!)
index = listaDipendenti.FindIndex(Function(d) d.ID = dipendenteSelezionato.ID)
' Se non trovato, usa il primo
If index < 0 Then index = 0
If index < 0 Then
Debug.WriteLine($"⚠️ Dipendente {dipendenteSelezionato.ID} non trovato, uso il primo")
index = 0
Else
Debug.WriteLine($"✓ Dipendente {dipendenteSelezionato.ID} trovato all'indice {index}")
End If
dipendenteSelezionato = listaDipendenti(index)
End If
VScrollBar1.Value = index
Debug.WriteLine($"VScrollBar1.Value: {VScrollBar1.Value}")
' ✅ POPOLA TUTTI I CONTROLLI (UNA SOLA VOLTA)
popolaForm()
End Sub
' --- POPOLA TUTTI I CONTROLLI ---
Private Sub popolaForm()
Gestionale.PopolaCheckedListBox_T(Of Ruolo)(CheckDipRuoli, Gestionale.gestioneRuoli.GetRuoli)
Dim lista As List(Of Orari_fascia) = Gestionale.gestioneFasce.GetOrari_Fasce()
Gestionale.PopolaCheckedListBox_T(Of Orari_fascia)(CheckedListFasce, lista)
'InizializzaControlli()
Debug.WriteLine($"[popolaForm] Dipendente: {dipendenteSelezionato?.ID}")
InizializzaControlliDipendente()
InizializzaControlliAssenze()
ConfiguraGriglia()
setText()
popolaTextTot()
End Sub
' --- INIZIALIZZA CONTROLLI DIPENDENTE ---
Private Sub InizializzaControlliDipendente()
' Popola CheckedListBox Ruoli
Gestionale.PopolaCheckedListBox_T(Of Ruolo)(CheckDipRuoli, Gestionale.gestioneRuoli.GetRuoli)
' Popola CheckedListBox Fasce
Dim listaFasce As List(Of FasciaOraria) = Gestionale.gestioneFasce.GetOrari_Fasce()
Gestionale.PopolaCheckedListBox_T(Of FasciaOraria)(CheckedListFasce, listaFasce)
' Carica dati dipendente nei textbox
If dipendenteSelezionato IsNot Nothing Then
CaricaDatiDipendente()
End If
End Sub
' --- CARICA DATI DIPENDENTE NEI TEXTBOX ---
Private Sub CaricaDatiDipendente()
TextDipNome.Text = dipendenteSelezionato.Nome
TextDipCognome.Text = dipendenteSelezionato.Cognome
@@ -89,25 +124,25 @@ Public Class FormDipendente
TextDipEmail.Text = dipendenteSelezionato.Email
TextDipTelefono.Text = dipendenteSelezionato.Telefono
DateTimeAssunzione.Value = If(String.IsNullOrEmpty(dipendenteSelezionato.DataAssunzione), DateTime.Today, DateTime.Parse(dipendenteSelezionato.DataAssunzione))
Gestionale.ChecklistBox_Spunta(CheckDipRuoli, dipendenteSelezionato.GetRuoli)
' Carica Ruoli nel CheckedListBox
' Seleziona i ruoli già assegnati (da implementare in Gestionale se esiste il metodo)
' Gestionale.SelezionaRuoliDipendente(CheckRuoli, d.ID)
' ✅ SELEZIONA RUOLI ASSEGNATI
Gestionale.ChecklistBox_Spunta(CheckDipRuoli, dipendenteSelezionato.GetRuoli)
End Sub
' --- INIZIALIZZA CONTROLLI ASSENZE ---
Private Sub InizializzaControlliAssenze()
Try
' 1. Controlla che la lista dei tipi assenza non sia Nothing
' 1. Carica tipi assenza (con Distinct per evitare duplicati)
Dim lista = Gestionale.gestioneTipiAssenze.GetTipiAssenza()
If lista Is Nothing Then
lista = New List(Of TipoAssenza)() ' lista vuota
End If
If lista Is Nothing Then lista = New List(Of TipoAssenza)()
' 2. Assicurati che la Combo esista
' 2. Popola ComboBox
If ComboTipoAssenza IsNot Nothing Then
ComboTipoAssenza.DataSource = lista
ComboTipoAssenza.DataSource = Nothing
ComboTipoAssenza.DataSource = lista.Distinct().ToList()
ComboTipoAssenza.DisplayMember = "Nome"
ComboTipoAssenza.ValueMember = "ID"
ComboTipoAssenza.SelectedIndex = 0
End If
' 3. Date Assenze (Dettaglio)
@@ -122,116 +157,153 @@ Public Class FormDipendente
If DtpDal IsNot Nothing AndAlso DtpAl IsNot Nothing Then
DtpDal.Format = DateTimePickerFormat.Long
DtpAl.Format = DateTimePickerFormat.Long
DtpAl.Value = DtpDal.Value.AddDays(10)
DtpDal.Value = DateTime.Today
DtpAl.Value = DateTime.Today.AddDays(10)
End If
Catch ex As Exception
' Log completo dell’errore
Console.WriteLine("Errore in InizializzaControlliAssenze(): " & ex.Message)
Console.WriteLine(ex.StackTrace)
End Try
' 5. Carica assenze
CaricaAssenze()
CaricaAssenze()
Catch ex As Exception
Debug.WriteLine($"[ERRORE] InizializzaControlliAssenze: {ex.Message}")
Debug.WriteLine(ex.StackTrace)
End Try
End Sub
' --- CARICA ASSENZE DAL DATABASE ---
Private Sub CaricaAssenze()
If dipendenteSelezionato IsNot Nothing Then
' ← LEGGI DIRETTAMENTE DAL DATABASE
Dim assenzeCorrenti As List(Of Assenza) = Gestionale.gestioneAssenze.GetAssenzeDipendente(
If dipendenteSelezionato Is Nothing Then
Debug.WriteLine("[CaricaAssenze] dipendenteSelezionato è NULL")
Return
End If
Debug.WriteLine($"[CaricaAssenze] Dip={dipendenteSelezionato.ID}, Dal={DtpDal.Value:dd/MM}, Al={DtpAl.Value:dd/MM}")
Dim assenzeCorrenti As List(Of Assenza) = Gestionale.gestioneAssenze.GetAssenzeDipendente(
dipendenteSelezionato.ID,
DtpDal.Value.Date,
DtpAl.Value.Date
)
DataGridAssenze.DataSource = Nothing
DataGridAssenze.DataSource = assenzeCorrenti
lblTotaleAssenze.Text = $"Totale assenze {assenzeCorrenti.Count} giorni"
Debug.WriteLine($"[CaricaAssenze] Trovate: {assenzeCorrenti.Count} assenze")
System.Diagnostics.Debug.WriteLine($"CaricaAssenze: {assenzeCorrenti.Count} assenze trovate")
End If
DataGridAssenze.DataSource = Nothing
DataGridAssenze.DataSource = assenzeCorrenti
DataGridAssenze.Refresh()
lblTotaleAssenze.Text = $"Totale assenze: {assenzeCorrenti.Count} giorni"
End Sub
' --- CONFIGURAZIONE GRIGLIA ASSENZE ---
Private Sub ConfiguraGriglia()
DataGridAssenze.AutoGenerateColumns = False
' Nel Form_Load o dopo DataSource
'For Each c As DataGridViewColumn In DataGridAssenze.Columns
' If c.Name.Contains("ID") Then c.Visible = False
' If c.Name.Contains("DataFine") Then c.Visible = False
' If c.Name.Contains("DataInizio") Then c.HeaderText = "Data"
'Next
For Each c As DataGridViewColumn In DataGridAssenze.Columns
If c.Name.Contains("ID") Then c.Visible = False
If c.Name.Contains("DataFine") Then c.Visible = False
If c.Name.Contains("DataInizio") Then
c.HeaderText = "Data"
c.DataPropertyName = "DataInizio"
End If
Next
' ✅ RIMUOVI HANDLER PRECEDENTI PER EVITARE DOPPI
RemoveHandler DataGridAssenze.CellFormatting, AddressOf DataGridAssenzeAssenze_CellFormatting
AddHandler DataGridAssenze.CellFormatting, AddressOf DataGridAssenzeAssenze_CellFormatting
End Sub
Private Sub DataGridAssenzeAssenze_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs)
If e.RowIndex < 0 Then Return
If DataGridAssenze.Rows(e.RowIndex).DataBoundItem Is Nothing Then Return
Dim assenza As Assenza = CType(DataGridAssenze.Rows(e.RowIndex).DataBoundItem, Assenza)
' Colonna Stato
' ✅ CAMBIA SOLO I COLORI, NON IL VALORE
If e.ColumnIndex = DataGridAssenze.Columns("Approvata").Index Then
e.Value = assenza.Approvata ' If(assenza.Approvata, "✅ Approvata", "⏳ In attesa")
' Non modificare e.Value se la colonna è Boolean
e.CellStyle.BackColor = If(assenza.Approvata, Color.LightGreen, Color.Orange)
e.CellStyle.ForeColor = Color.Black
e.FormattingApplied = True
End If
End Sub
' --- INIZIALIZZAZIONE CONTROLLI ---
Private Sub InizializzaControlli()
' Recupera le fasce dal database
Dim listaFasce As List(Of Orari_fascia) = Gestionale.gestioneFasce.GetOrari_Fasce()
' Crea lista combinata
Dim listaCombinata As New List(Of Object)
listaCombinata.Add(New ComboItem With {.ID = 0, .Nome = "-- Nessuna fascia --"})
listaCombinata.AddRange(listaFasce)
' --- SALVA DIPENDENTE ---
'Private Sub btnSalvaDipendente_Click(sender As Object, e As EventArgs) Handles btnSalvaDipendente.Click
' Dim lista = Gestionale.listaID_ChecklistBox(CheckDipRuoli)
ComboTipoAssenza.SelectedIndex = 0
' If lista.Count = 0 Then
' MessageBox.Show("Inserire almeno un ruolo!", "Attenzione", MessageBoxButtons.OK, MessageBoxIcon.Warning)
' Return
' End If
' If dipendenteSelezionato Is Nothing Then
' dipendenteSelezionato = New Dipendente(
' nome:=TextDipNome.Text,
' cognome:=TextDipCognome.Text,
' dataNascita:=DateTimeDipNascita.Value.Date,
' telefono:=TextDipTelefono.Text,
' email:=TextDipEmail.Text,
' dataAssunzione:=DateTimeAssunzione.Value.Date,
' attivo:=CheckAttivo.Checked
' )
' Else
' dipendenteSelezionato.Nome = TextDipNome.Text
' dipendenteSelezionato.Cognome = TextDipCognome.Text
' dipendenteSelezionato.DataNascita = DateTimeDipNascita.Value.Date
' dipendenteSelezionato.Attivo = CheckAttivo.Checked
' dipendenteSelezionato.Email = TextDipEmail.Text
' dipendenteSelezionato.Telefono = TextDipTelefono.Text
' dipendenteSelezionato.DataAssunzione = DateTimeAssunzione.Value.Date
' End If
' 3. Griglia Assenze
ConfiguraGriglia()
' 4. Date Assenze (Dettaglio)
DtpAssenzaDal.Format = DateTimePickerFormat.Short
DtpAssenzaAl.Format = DateTimePickerFormat.Short
DtpAssenzaDal.Value = DateTime.Today
DtpAssenzaAl.Value = DateTime.Today
' 5. Date Assenze (Filtro)
DtpDal.Format = DateTimePickerFormat.Short
DtpAl.Format = DateTimePickerFormat.Short
End Sub
' ==========================================
' GESTIONE DIPENDENTE (ANAGRAFICA E RUOLI)
' ==========================================
' Gestionale.gestioneDipendenti.SalvaDipendente(dipendenteSelezionato)
' dipendenteSelezionato.SetRuoli(lista)
' MessageBox.Show("Dipendente salvato con successo!", "Completato", MessageBoxButtons.OK, MessageBoxIcon.Information)
' ' ✅ RICARICA LA LISTA E AGGIORNA FORM1
' listaDipendenti = Gestionale.gestioneDipendenti.GetDipendenti("")
' Form1.PopolaGrigliaDipendenti()
' GroupAssenza.Enabled = True
' popolaForm()
'End Sub
Private Sub btnSalvaDipendente_Click(sender As Object, e As EventArgs) Handles btnSalvaDipendente.Click
Dim lista = Gestionale.listaID_ChecklistBox(CheckDipRuoli)
If lista.Count = 0 Then
MsgBox("inserire almeno un ruolo")
' ✅ VALIDAZIONE CAMPI OBBLIGATORI
If String.IsNullOrWhiteSpace(TextDipNome.Text) Then
MessageBox.Show("Inserire il nome!", "Campo obbligatorio", MessageBoxButtons.OK, MessageBoxIcon.Warning)
TextDipNome.Focus()
Return
End If
If String.IsNullOrWhiteSpace(TextDipCognome.Text) Then
MessageBox.Show("Inserire il cognome!", "Campo obbligatorio", MessageBoxButtons.OK, MessageBoxIcon.Warning)
TextDipCognome.Focus()
Return
End If
Dim lista = Gestionale.listaID_ChecklistBox(CheckDipRuoli)
If lista.Count = 0 Then
MessageBox.Show("Inserire almeno un ruolo!", "Attenzione", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
' ✅ CREA O AGGIORNA DIPENDENTE
If dipendenteSelezionato Is Nothing Then
' --- NUOVO DIPENDENTE ---
dipendenteSelezionato = New Dipendente(
nome:=TextDipNome.Text,
cognome:=TextDipCognome.Text,
dataNascita:=DateTimeDipNascita.Value.Date, ' ← Già Date, non convertire!
telefono:=TextDipTelefono.Text,
email:=TextDipEmail.Text,
dataAssunzione:=DateTimeAssunzione.Value.Date, ' ← Già Date, non convertire!
attivo:=CheckAttivo.Checked
)
nome:=TextDipNome.Text,
cognome:=TextDipCognome.Text,
dataNascita:=DateTimeDipNascita.Value.Date,
telefono:=TextDipTelefono.Text,
email:=TextDipEmail.Text,
dataAssunzione:=DateTimeAssunzione.Value.Date,
attivo:=CheckAttivo.Checked
)
Debug.WriteLine("[Salva] Creazione nuovo dipendente")
Else
' Se esiste già, aggiorna le proprietà
' --- MODIFICA DIPENDENTE ESISTENTE ---
dipendenteSelezionato.Nome = TextDipNome.Text
dipendenteSelezionato.Cognome = TextDipCognome.Text
dipendenteSelezionato.DataNascita = DateTimeDipNascita.Value.Date
@@ -239,43 +311,56 @@ Public Class FormDipendente
dipendenteSelezionato.Email = TextDipEmail.Text
dipendenteSelezionato.Telefono = TextDipTelefono.Text
dipendenteSelezionato.DataAssunzione = DateTimeAssunzione.Value.Date
Debug.WriteLine($"[Salva] Modifica dipendente ID={dipendenteSelezionato.ID}")
End If
' ✅ SALVA NEL DATABASE
Gestionale.gestioneDipendenti.SalvaDipendente(dipendenteSelezionato)
' Salva Ruoli associati
'Gestionale.gestioneRuoli.SalvaRuoliDipendente(dipendenteSelezionato.ID, lista)
dipendenteSelezionato.SetRuoli(lista)
MessageBox.Show("Dipendente salvato con successo!")
MessageBox.Show("Dipendente salvato con successo!", "Completato", MessageBoxButtons.OK, MessageBoxIcon.Information)
' ✅ RICARICA LA LISTA E AGGIORNA FORM1
listaDipendenti = Gestionale.gestioneDipendenti.GetDipendenti("")
' Trova l'indice del dipendente appena salvato
index = listaDipendenti.FindIndex(Function(d) d.ID = dipendenteSelezionato.ID)
If index < 0 Then index = listaDipendenti.Count - 1 ' Prendi l'ultimo se non trovato
VScrollBar1.Maximum = index
VScrollBar1.Value = index
VScrollBar1.Maximum = listaDipendenti.Count - 1
Form1.PopolaGrigliaDipendenti()
GroupAssenza.Enabled = True
popolaForm()
End Sub
' --- NUOVO RUOLO ---
Private Sub btnNuovoRuolo_Click(sender As Object, e As EventArgs) Handles btnNuovoRuolo.Click
Dim n = InputBox("Nome ruolo", "Nuovo Ruolo")
If String.IsNullOrWhiteSpace(n) Then Return
Dim desc = InputBox("Descrizione", "Nuovo Ruolo")
Dim r As New Ruolo()
r.Nome = n
r.Descrizione = desc
Dim r As New Ruolo With {.Nome = n, .Descrizione = desc}
Gestionale.gestioneRuoli.SalvaRuolo(r)
Gestionale.PopolaCheckedListBox_T(Of Ruolo)(CheckDipRuoli, Gestionale.gestioneRuoli.GetRuoli)
End Sub
' --- ELIMINA RUOLO ---
Private Sub btnEliminaRuolo_Click(sender As Object, e As EventArgs) Handles btnEliminaRuolo.Click
If CheckDipRuoli.SelectedItem IsNot Nothing Then
Dim selectedObj = CheckDipRuoli.SelectedItem
Dim ruolo As Ruolo = DirectCast(CallByName(selectedObj, "Item", CallType.Get), Ruolo)
Dim idRuolo As Integer = ruolo.ID
Gestionale.gestioneRuoli.EliminaRuolo(idRuolo)
Gestionale.PopolaCheckedListBox_T(Of Ruolo)(CheckDipRuoli, Gestionale.gestioneRuoli.GetRuoli)
Dim ruolo As Ruolo = DirectCast(CheckDipRuoli.SelectedItem, Ruolo)
Dim result = MessageBox.Show($"Eliminare ruolo '{ruolo.Nome}'?", "Conferma", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.Yes Then
Gestionale.gestioneRuoli.EliminaRuolo(ruolo.ID)
Gestionale.PopolaCheckedListBox_T(Of Ruolo)(CheckDipRuoli, Gestionale.gestioneRuoli.GetRuoli)
End If
End If
End Sub
' ==========================================
' GESTIONE ASSENZE
' ==========================================
' --- PERIODO ASSENZE ---
Private Sub ImpostaPeriodoDefault()
DtpDal.Value = DateTime.Today
DtpAl.Value = DateTime.Today.AddDays(10)
@@ -284,17 +369,13 @@ Public Class FormDipendente
Private Sub CalcolaGiorniPeriodo()
Dim giorni As Integer = (DtpAl.Value.Date - DtpDal.Value.Date).Days + 1
lblPeriodo.Text = $"Periodo {giorni} giorni"
lblPeriodo.Text = $"Periodo: {giorni} giorni"
End Sub
Private Sub BtnAggiornaAssenze_Click(sender As Object, e As EventArgs) Handles btnAggiornaAssenze.Click
CaricaAssenze()
ConfiguraGriglia()
End Sub
Private Sub DtpDal_ValueChanged(sender As Object, e As EventArgs) Handles DtpDal.ValueChanged
CalcolaGiorniPeriodo()
End Sub
@@ -303,47 +384,46 @@ Public Class FormDipendente
CalcolaGiorniPeriodo()
End Sub
' --- Selezione Riga Griglia ---
' --- SELEZIONE RIGA GRIGLIA ---
Private Sub DataGridAssenze_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridAssenze.SelectionChanged
If DataGridAssenze.CurrentRow Is Nothing Then Return
If DataGridAssenze.CurrentRow.IsNewRow Then Return
_assenzaSelezionata = CType(DataGridAssenze.CurrentRow.DataBoundItem, Assenza)
If _assenzaSelezionata IsNot Nothing Then
' ← TROVA L'OGGETTO TIPO ASSENZA NELLA COMBO
Dim listaTipi = CType(ComboTipoAssenza.DataSource, List(Of TipoAssenza))
Dim tipoAssenza = listaTipi.FirstOrDefault(Function(t) t.ID = _assenzaSelezionata.TipoAssenzaID)
If tipoAssenza IsNot Nothing Then
ComboTipoAssenza.SelectedItem = tipoAssenza ' ← USA SelectedItem!
ComboTipoAssenza.SelectedItem = tipoAssenza
End If
DtpAssenzaDal.Value = _assenzaSelezionata.DataInizio
DtpAssenzaAl.Value = _assenzaSelezionata.DataInizio
DtpAssenzaAl.Value = _assenzaSelezionata.DataFine
TxtMotivazione.Text = _assenzaSelezionata.Motivazione
ChkApprovata.Checked = _assenzaSelezionata.Approvata
' ← CARICA FASCE DAL TIPO ASSENZA
' Carica fasce dal tipo assenza
Dim fasciaIDs = Gestionale.gestioneAssenze.GetFascePerTipoAssenza(_assenzaSelezionata.TipoAssenzaID)
Gestionale.ChecklistBox_Spunta(CheckedListFasce, fasciaIDs)
End If
End Sub
' --- Calcolo Giorni Dettaglio ---
Private Sub DtpDalDettaglio_ValueChanged(sender As Object, e As EventArgs) Handles DtpAssenzaDal.ValueChanged
' --- CALCOLO GIORNI DETTAGLIO ---
Private Sub DtpAssenzaDal_ValueChanged(sender As Object, e As EventArgs) Handles DtpAssenzaDal.ValueChanged
CalcolaGiorniDettaglio()
DtpAssenzaAl.Value = DtpAssenzaDal.Value
End Sub
Private Sub DtpAlDettaglio_ValueChanged(sender As Object, e As EventArgs) Handles DtpAssenzaAl.ValueChanged
Private Sub DtpAssenzaAl_ValueChanged(sender As Object, e As EventArgs) Handles DtpAssenzaAl.ValueChanged
CalcolaGiorniDettaglio()
End Sub
Private Sub CalcolaGiorniDettaglio()
If DtpAssenzaDal.Value <= DtpAssenzaAl.Value Then
Dim giorni As Integer = (DtpAssenzaAl.Value - DtpAssenzaDal.Value).Days + 1
lblGiorniDettaglio.Text = $"Giorni totali {giorni}"
lblGiorniDettaglio.Text = $"Giorni totali: {giorni}"
lblGiorniDettaglio.ForeColor = Color.Green
Else
lblGiorniDettaglio.Text = "⚠️ Data fine precedente!"
@@ -457,63 +537,55 @@ Public Class FormDipendente
End Try
End Sub
Private Sub PulisciCampiAssenze()
' --- PULISCI CAMPI ASSENZA (UNICO METODO) ---
Private Sub PulisciCampiAssenza()
_assenzaSelezionata = Nothing
ComboTipoAssenza.SelectedIndex = 0
DtpAssenzaDal.Value = DateTime.Today
DtpAssenzaAl.Value = DateTime.Today
TxtMotivazione.Text = ""
ChkApprovata.Checked = False
CheckedListFasce.ClearSelected()
CalcolaGiorniDettaglio()
End Sub
' --- ELIMINA ASSENZA ---
Private Sub btnEliminaAssenza_Click(sender As Object, e As EventArgs) Handles btnEliminaAssenza.Click
If _assenzaSelezionata Is Nothing Then
MessageBox.Show("Seleziona un'assenza dalla griglia.")
MessageBox.Show("Seleziona un'assenza dalla griglia.", "Attenzione", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Dim result As DialogResult = MessageBox.Show($"Eliminare assenza del {_assenzaSelezionata.DataInizio:dd/MM/yyyy}?", "Conferma", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
Dim result = MessageBox.Show($"Eliminare assenza del {_assenzaSelezionata.DataInizio:dd/MM/yyyy}?", "Conferma", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.Yes Then
Gestionale.gestioneAssenze.EliminaAssenza(_assenzaSelezionata.ID)
MessageBox.Show("Eliminata.")
MessageBox.Show("Assenza eliminata.", "Completato", MessageBoxButtons.OK, MessageBoxIcon.Information)
PulisciCampiAssenza()
CaricaAssenze()
End If
End Sub
' --- ANNULLA MODIFICHE ASSENZA ---
Private Sub btnAnnullaAssenza_Click(sender As Object, e As EventArgs) Handles btnAnnullaAssenza.Click
PulisciCampiAssenza()
End Sub
Private Sub PulisciCampiAssenza()
_assenzaSelezionata = Nothing
ComboTipoAssenza.SelectedIndex = 0
'ComboFascia.SelectedIndex = 0
DtpAssenzaDal.Value = DateTime.Today
DtpAssenzaAl.Value = DateTime.Today
CalcolaGiorniDettaglio()
End Sub
Private Sub ButtonSalvaDip_Click(sender As Object, e As EventArgs) Handles btnSalvaDipendente.Click
End Sub
' --- ANNULLA MODIFICHE DIPENDENTE ---
Private Sub BtnAnnullla_Click(sender As Object, e As EventArgs) Handles BtnAnnullla.Click
CaricaDatiDipendente()
If dipendenteSelezionato IsNot Nothing Then
CaricaDatiDipendente()
End If
End Sub
' --- MODIFICA ASSENZA ---
Private Sub btnModificaAssenza_Click(sender As Object, e As EventArgs) Handles btnModificaAssenza.Click
If DataGridAssenze.CurrentRow Is Nothing Then Return
If DataGridAssenze.CurrentRow.IsNewRow Then Return
' Recupera l'assenza selezionata
Dim assenza As Assenza = CType(DataGridAssenze.CurrentRow.DataBoundItem, Assenza)
If assenza IsNot Nothing Then
' Riempie i controlli con i dati dell'assenza
DtpAssenzaDal.Value = assenza.DataInizio
DtpAssenzaAl.Value = assenza.DataFine
ComboTipoAssenza.SelectedValue = assenza.TipoAssenzaID
@@ -522,46 +594,111 @@ Public Class FormDipendente
End If
End Sub
Private Sub CheckDipRuoli_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CheckDipRuoli.SelectedIndexChanged
End Sub
' --- CAMBIO TIPO ASSENZA ---
Private Sub ComboTipoAssenza_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboTipoAssenza.SelectedIndexChanged
If ComboTipoAssenza.SelectedItem Is Nothing Then Return
Dim tipoAssenza = CType(ComboTipoAssenza.SelectedItem, TipoAssenza)
Dim tipoID As Integer = tipoAssenza.ID
' ← RECUPERA FASCE CONFIGURATE PER QUESTO TIPO
Dim fasciaIDs As List(Of Integer) = Gestionale.gestioneTipiAssenze.GetFascePerTipoAssenza(tipoID)
' ← CONTROLLA SE È GIORNATA INTERA (ID 1 o 2)
If tipoID = 1 OrElse tipoID = 2 Then
' Giornata intera: deseleziona tutto (FasciaID = NULL)
Gestionale.ChecklistBox_Spunta(CheckedListFasce, New List(Of Integer)())
' ← PRE-SELEZIONA SOLO SE CI SONO FASCE CONFIGURATE
If fasciaIDs.Count > 0 Then
Gestionale.ChecklistBox_Spunta(CheckedListFasce, fasciaIDs)
' Disabilita la selezione (l'utente non può scegliere fasce)
CheckedListFasce.Enabled = False
' Opzionale: mostra messaggio informativo
'lblInfoFasce.Text = "Giornata intera: tutte le fasce saranno incluse automaticamente."
Else
' Altri tipi: abilita la selezione fasce
CheckedListFasce.Enabled = True
' Recupera fasce configurate per questo tipo
Dim fasciaIDs As List(Of Integer) = Gestionale.gestioneTipiAssenze.GetFascePerTipoAssenza(tipoID)
' Pre-seleziona le fasce configurate (se esistono)
If fasciaIDs.Count > 0 Then
Gestionale.ChecklistBox_Spunta(CheckedListFasce, fasciaIDs)
Else
' Nessuna fascia configurata: deseleziona tutto
Gestionale.ChecklistBox_Spunta(CheckedListFasce, Nothing)
End If
'lblInfoFasce.Text = "Seleziona le fasce specifiche per questa assenza."
End If
' ← SE NON CI SONO FASCE CONFIGURATE, NON FARE NULLA!
' L'utente può selezionare manualmente le fasce
End Sub
Private Sub DataGridAssenze_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridAssenze.CellContentClick
End Sub
Private Sub popolaTextTot()
'& vbCrLf &
Dim ind = $"indice = {index}" & vbCrLf
Dim ruo = ""
For Each r In Gestionale.gestioneRuoli.GetRuoli
ruo = ruo & r.Nome & " = " & Gestionale.gestioneDipendenti.CountDipendenti(Nothing, ruoloNome:=r.Nome) & vbCrLf
Next
TextTot.Text = ind & vbCrLf & ruo
End Sub
' --- SCROLLBAR ---
Private Sub VScrollBar1_Scroll(sender As Object, e As ScrollEventArgs) Handles VScrollBar1.Scroll
index = VScrollBar1.Value
dipendenteSelezionato = listaDipendenti(index)
CaricaAssenze()
popolaForm()
End Sub
' --- INFO TOTALI ---
Private Sub popolaTextTot()
Dim ind = $"Indice = {index}" & vbCrLf
Dim ruo = ""
For Each r In Gestionale.gestioneRuoli.GetRuoli
ruo &= $"{r.Nome} = {Gestionale.gestioneDipendenti.CountDipendenti(Nothing, ruoloNome:=r.Nome)}" & vbCrLf
Next
Dim oreA = "ore assenza dipendete: " & Gestionale.gestioneAssenze.GetOreAssenzaDipendente(dipendenteSelezionato.ID)
Dim oreL = "ore lavorate: " & Gestionale.gestioneTurni.GetOreLavorateDaOggiIndietro(dipendenteSelezionato.ID)
Dim oreP = "ore programmate: " & Gestionale.gestioneTurni.GetOreProgrammateDaOggiInAvanti(dipendenteSelezionato.ID)
Dim oreT = "ore Totali Lavorate+Programmate: " & Gestionale.gestioneTurni.OreLavorateProgrammate(dipendenteSelezionato.ID)
TextTot.Text = ind & vbCrLf & ruo & vbCrLf & oreL & vbCrLf & oreA & vbCrLf & oreP & vbCrLf & oreT
End Sub
' --- PULIZIA EVENTI (IMPORTANTE!) ---
Protected Overrides Sub OnFormClosed(e As FormClosedEventArgs)
RemoveHandler DataGridAssenze.CellFormatting, AddressOf DataGridAssenzeAssenze_CellFormatting
MyBase.OnFormClosed(e)
End Sub
Private Sub BtnNuovoDip_Click(sender As Object, e As EventArgs) Handles BtnNuovoDip.Click
' ✅ 1. RESETTA IL DIPENDENTE SELEZIONATO
dipendenteSelezionato = Nothing
' ✅ 2. PULISCI TUTTI I CAMPI
TextDipNome.Text = ""
TextDipCognome.Text = ""
DateTimeDipNascita.Value = DateTime.Today
CheckAttivo.Checked = True
TextDipEmail.Text = ""
TextDipTelefono.Text = ""
DateTimeAssunzione.Value = DateTime.Today
' ✅ 3. DESELEZIONA RUOLI E FASCE
For i As Integer = 0 To CheckDipRuoli.Items.Count - 1
CheckDipRuoli.SetItemChecked(i, False)
Next
For i As Integer = 0 To CheckedListFasce.Items.Count - 1
CheckedListFasce.SetItemChecked(i, False)
Next
' ✅ 4. DISABILITA SEZIONE ASSENZE (non puoi aggiungere assenze a un dipendente non salvato)
GroupAssenza.Enabled = False
' ✅ 5. METTI IL FOCUS SUL PRIMO CAMPO
TextDipNome.Focus()
' ✅ 6. AGGIORNA IL TITOLO
setText()
Debug.WriteLine("[NuovoDip] Form pronto per nuovo dipendente")
End Sub
Private Sub ComboTipoAssenza_TextChanged(sender As Object, e As EventArgs) Handles ComboTipoAssenza.TextChanged
CheckedListFasce.Enabled = True
End Sub
End Class
' Classe di supporto per ComboFascia
' ✅ CLASSE DI SUPPORTO (Sposta in file separato se possibile)
Public Class ComboItem
Public Property ID As Integer
Public Property Nome As String

View File

@@ -19,8 +19,8 @@
Gestionale.PopolaCheckedListBox_T(Of Ruolo)(CheckedListRuoli, ruoli)
'Dim fasce As List(Of Orari_fascia) = Gestionale.gestioneFasce.GetFasce()
'Gestionale.PopolaCheckedListBox_T(Of Orari_fascia)(CheckedListFasce, fasce)
Dim fasce As List(Of Orari_fascia) = Gestionale.gestioneFasce.GetOrari_Fasce()
Gestionale.PopolaCheckedListBox_T(Of Orari_fascia)(CheckedListFasce, fasce)
Dim fasce As List(Of FasciaOraria) = Gestionale.gestioneFasce.GetOrari_Fasce()
Gestionale.PopolaCheckedListBox_T(Of FasciaOraria)(CheckedListFasce, fasce)
'CheckedListFasce.DataSource = Nothing
'CheckedListFasce.DataSource = fasce
'CheckedListFasce.DisplayMember = "NomeTurno" ' proprietà da mostrare
@@ -28,7 +28,7 @@
End Sub
Private Sub PopolaGridFasce()
' 1. Recupero i dati una sola volta
Dim lista As List(Of Orari_fascia) = Gestionale.gestioneFasce.GetOrari_Fasce()
Dim lista As List(Of FasciaOraria) = Gestionale.gestioneFasce.GetOrari_Fasce()
' 2. Popolo la DataGridView
DataGridFasce.DataSource = Nothing
@@ -42,7 +42,7 @@
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim f = New Orari_fascia
Dim f = New FasciaOraria
f.Nome = TextOrarioNome.Text
f.OraInizio = TextOrarioInizio.Text
f.OraFine = TextOrarioFine.Text
@@ -112,7 +112,7 @@
End Sub
Public Function FasciaSelezionata() As Orari_fascia
Public Function FasciaSelezionata() As FasciaOraria
' Controllo se c'è una riga selezionata valida
If DataGridFasce.CurrentRow Is Nothing OrElse DataGridFasce.CurrentRow.Index < 0 Then
Return Nothing
@@ -120,7 +120,7 @@
' Accesso diretto all'oggetto dalla lista originale
' Questo evita problemi di casting su DataBoundItem
Dim lista As List(Of Orari_fascia) = CType(DataGridFasce.DataSource, List(Of Orari_fascia))
Dim lista As List(Of FasciaOraria) = CType(DataGridFasce.DataSource, List(Of FasciaOraria))
Return lista(DataGridFasce.CurrentRow.Index)
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
@@ -159,9 +159,9 @@
'Try
Dim contatore As Integer = 0
For Each ruoloObj In CheckedListRuoli.CheckedItems
' Prendi il valore tramite reflection o CallByName
Dim ruoloID As Integer = CInt(CallByName(ruoloObj, "Value", CallType.Get))
For Each ruoloObj In CheckedListRuoli.CheckedItems
' Prendi il valore tramite reflection o CallByName
Dim ruoloID As Integer = CInt(CallByName(ruoloObj, "Value", CallType.Get))
For Each fasciaObj In CheckedListFasce.CheckedItems
Dim fasciaID As Integer = CInt(CallByName(fasciaObj, "value", CallType.Get))
@@ -172,7 +172,7 @@
Dim requisito As New Fascia With {
.ID = 0,
.Ruolo = New Ruolo With {.ID = ruoloID},
.FasciaOraria = New Orari_fascia With {.ID = fasciaID},
.FasciaOraria = New FasciaOraria With {.ID = fasciaID},
.PersoneNecessarie = personeNecessarie,
.GiornoSettimana = giornoID
}

97
gestionaleTurni/FormTabella.Designer.vb generated Normal file
View File

@@ -0,0 +1,97 @@
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class FormTabella
Inherits System.Windows.Forms.Form
'Form esegue l'override del metodo Dispose per pulire l'elenco dei componenti.
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Richiesto da Progettazione Windows Form
Private components As System.ComponentModel.IContainer
'NOTA: la procedura che segue è richiesta da Progettazione Windows Form
'Può essere modificata in Progettazione Windows Form.
'Non modificarla mediante l'editor del codice.
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.Panel1 = New System.Windows.Forms.Panel()
Me.DateTimeAl = New System.Windows.Forms.DateTimePicker()
Me.DateTimeDal = New System.Windows.Forms.DateTimePicker()
Me.BtnTabelle = New System.Windows.Forms.Button()
Me.BtnSalva = New System.Windows.Forms.Button()
Me.Panel1.SuspendLayout()
Me.SuspendLayout()
'
'Panel1
'
Me.Panel1.AutoSize = True
Me.Panel1.Controls.Add(Me.BtnSalva)
Me.Panel1.Controls.Add(Me.DateTimeAl)
Me.Panel1.Controls.Add(Me.DateTimeDal)
Me.Panel1.Controls.Add(Me.BtnTabelle)
Me.Panel1.Dock = System.Windows.Forms.DockStyle.Top
Me.Panel1.Location = New System.Drawing.Point(0, 0)
Me.Panel1.Name = "Panel1"
Me.Panel1.Size = New System.Drawing.Size(800, 29)
Me.Panel1.TabIndex = 0
'
'DateTimeAl
'
Me.DateTimeAl.Location = New System.Drawing.Point(316, 6)
Me.DateTimeAl.Name = "DateTimeAl"
Me.DateTimeAl.Size = New System.Drawing.Size(200, 20)
Me.DateTimeAl.TabIndex = 2
'
'DateTimeDal
'
Me.DateTimeDal.Location = New System.Drawing.Point(110, 6)
Me.DateTimeDal.Name = "DateTimeDal"
Me.DateTimeDal.Size = New System.Drawing.Size(200, 20)
Me.DateTimeDal.TabIndex = 1
'
'BtnTabelle
'
Me.BtnTabelle.Location = New System.Drawing.Point(3, 3)
Me.BtnTabelle.Name = "BtnTabelle"
Me.BtnTabelle.Size = New System.Drawing.Size(101, 23)
Me.BtnTabelle.TabIndex = 0
Me.BtnTabelle.Text = "Crea Tabelle"
Me.BtnTabelle.UseVisualStyleBackColor = True
'
'BtnSalva
'
Me.BtnSalva.Location = New System.Drawing.Point(522, 3)
Me.BtnSalva.Name = "BtnSalva"
Me.BtnSalva.Size = New System.Drawing.Size(102, 23)
Me.BtnSalva.TabIndex = 3
Me.BtnSalva.Text = "Salva"
Me.BtnSalva.UseVisualStyleBackColor = True
'
'FormTabella
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(800, 450)
Me.Controls.Add(Me.Panel1)
Me.Name = "FormTabella"
Me.Text = "FormTabella"
Me.Panel1.ResumeLayout(False)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Panel1 As Panel
Friend WithEvents BtnTabelle As Button
Friend WithEvents DateTimeAl As DateTimePicker
Friend WithEvents DateTimeDal As DateTimePicker
Friend WithEvents BtnSalva As Button
End Class

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,539 @@
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Collections.Generic
Imports System.Linq
Public Class FormTabella
Inherits Form
Private _container As Panel
Private _tabellePerGiorno As New Dictionary(Of Date, ControlTabella)()
Private _labelPerGiorno As New Dictionary(Of Date, Label)()
Private _staAggiornando As Boolean = False
Private _yPositionCorrente As Integer = 10
' ✅ PARAMETRI PER RICARICARE
Private _ruoloIDs As List(Of Integer)
Private _dataInizio As Date
Private _dataFine As Date
Private _gestioneOrariFasce As Object
Private _gestioneDipendenti As Object
Public Sub New()
InitializeComponent()
InitializeComponenti()
End Sub
Private Sub InitializeComponenti()
Me.Text = "Gestione Turni - Multi Giorni"
Me.Size = New Size(1400, 900)
Me.StartPosition = FormStartPosition.CenterScreen
_container = New Panel With {
.Dock = DockStyle.Fill,
.AutoScroll = True,
.BackColor = Color.White,
.Padding = New Padding(10)
}
Me.Controls.Add(_container)
End Sub
' ✅ CARICA MULTIPLE GIORNATE - ESTRAGGO PARAMETRI AUTOMATICAMENTE
Public Sub CaricaMultipleGiornatex(configurazioni As List(Of TabellaConfig))
Debug.WriteLine($"🔵 FormTabella: CaricaMultipleGiornate - Giorni: {configurazioni.Count}")
' ✅ ESTRAGGO PARAMETRI DA CONFIGURAZIONI
EstraiParametriDaConfigurazioni(configurazioni)
_staAggiornando = True
_container.SuspendLayout()
_container.Controls.Clear()
_tabellePerGiorno.Clear()
Try
Dim yPosition As Integer = 10
Dim configOrdinate = configurazioni.OrderBy(Function(c) c.Data).ToList()
For Each config In configOrdinate
Debug.WriteLine($" - Creo tabella per: {config.Data:dddd dd/MM/yyyy}")
'Dim lblGiorno As New Label With {
' .Text = $"📅 {config.Data:dddd dd MMMM yyyy}",
' .Left = 10,
' .Top = yPosition,
' .Width = 1200,
' .Height = 35,
' .BackColor = Color.FromArgb(50, 50, 50),
' .ForeColor = Color.White,
' .TextAlign = ContentAlignment.MiddleLeft,
' .Font = New Font("Segoe UI", 11, FontStyle.Bold),
' .Padding = New Padding(10, 8, 0, 8)
'}
'_container.Controls.Add(lblGiorno)
yPosition += Panel1.Height
Dim ctrl As New ControlTabella With {
.Left = 10,
.Top = yPosition,
.BackColor = Color.White,
.BorderStyle = BorderStyle.FixedSingle,
.AutoScroll = False
}
AddHandler ctrl.SelezioneModificata, AddressOf HandleSelezioneModificata
AddHandler ctrl.InizializzazioneCompletata, AddressOf HandleInizializzazione
_tabellePerGiorno.Add(config.Data, ctrl)
_container.Controls.Add(ctrl)
ctrl.CreateControl()
ctrl.CaricaDati(config)
Application.DoEvents()
ctrl.Refresh()
ctrl.Update()
yPosition += ctrl.Height + 20
Debug.WriteLine($" - Tabella H={ctrl.Height}, Prossimo Y: {yPosition}")
Next
_container.AutoScrollMinSize = New Size(0, yPosition)
Debug.WriteLine($"✅ FormTabella: Completato - Scroll H={yPosition}")
Catch ex As Exception
Debug.WriteLine($"❌ ERRORE FormTabella: {ex.Message}")
MessageBox.Show($"Errore: {ex.Message}", "Errore FormTabella")
Finally
_container.ResumeLayout()
_staAggiornando = False
End Try
End Sub
Public Sub CaricaMultipleGiornate(configurazioni As List(Of TabellaConfig))
Debug.WriteLine($"🔵 FormTabella: CaricaMultipleGiornate - Giorni: {configurazioni.Count}")
EstraiParametriDaConfigurazioni(configurazioni)
_container.SuspendLayout()
_staAggiornando = True
Try
' ✅ 1. RESETTA LO SCROLL PRIMA DI PULIRE
' Questo elimina immediatamente lo spazio vuoto residuo
_container.AutoScrollMinSize = New Size(0, 0)
_container.VerticalScroll.Value = 0 ' Opzionale: torna in alto
' ✅ 2. PULIZIA PROFONDA (Dispose + Clear)
For Each ctrl As Control In _container.Controls.Cast(Of Control)().ToList()
Dim tabella As ControlTabella = TryCast(ctrl, ControlTabella)
If tabella IsNot Nothing Then
RemoveHandler tabella.SelezioneModificata, AddressOf HandleSelezioneModificata
RemoveHandler tabella.InizializzazioneCompletata, AddressOf HandleInizializzazione
End If
ctrl.Dispose()
Next
_container.Controls.Clear()
_tabellePerGiorno.Clear()
' ✅ 3. CREAZIONE NUOVE TABELLE
Dim yPosition As Integer = Panel1.Height
Dim configOrdinate = configurazioni.OrderBy(Function(c) c.Data).ToList()
For Each config In configOrdinate
Dim ctrl As New ControlTabella With {
.Left = 10,
.Top = yPosition,
.Width = _container.ClientSize.Width - 30,
.BackColor = Color.White,
.BorderStyle = BorderStyle.FixedSingle,
.AutoScroll = False
}
AddHandler ctrl.SelezioneModificata, AddressOf HandleSelezioneModificata
AddHandler ctrl.InizializzazioneCompletata, AddressOf HandleInizializzazione
_tabellePerGiorno.Add(config.Data, ctrl)
_container.Controls.Add(ctrl)
ctrl.CaricaDati(config)
yPosition += ctrl.Height + 20
Next
' ✅ 4. IMPOSTA NUOVO SCROLL (Solo alla fine)
_container.AutoScrollMinSize = New Size(0, yPosition)
Debug.WriteLine($"✅ FormTabella: Completato - Scroll H={yPosition}")
Catch ex As Exception
Debug.WriteLine($"❌ ERRORE FormTabella: {ex.Message}")
MessageBox.Show($"Errore: {ex.Message}", "Errore FormTabella")
Finally
_container.ResumeLayout(True)
_staAggiornando = False
End Try
End Sub
' ✅ ESTRAGGO PARAMETRI DA CONFIGURAZIONI
Private Sub EstraiParametriDaConfigurazioni(configurazioni As List(Of TabellaConfig))
If configurazioni Is Nothing OrElse configurazioni.Count = 0 Then
Debug.WriteLine("⚠️ Nessuna configurazione da cui estrarre parametri")
Return
End If
' ✅ ESTRAGGO DATE (min e max)
_dataInizio = configurazioni.Min(Function(c) c.Data)
_dataFine = configurazioni.Max(Function(c) c.Data)
' ✅ ESTRAGGO RUOLI UNIQUE DA TUTTE LE FASCE
Dim tuttiRuoliID As New List(Of Integer)()
For Each config In configurazioni
If config.Fasce IsNot Nothing Then
For Each fascia In config.Fasce
If fascia.Ruolo IsNot Nothing AndAlso Not tuttiRuoliID.Contains(fascia.Ruolo.ID) Then
tuttiRuoliID.Add(fascia.Ruolo.ID)
End If
Next
End If
Next
_ruoloIDs = tuttiRuoliID
Debug.WriteLine($"📋 Parametri estratti:")
Debug.WriteLine($" - Data Inizio: {_dataInizio:dd/MM/yyyy}")
Debug.WriteLine($" - Data Fine: {_dataFine:dd/MM/yyyy}")
Debug.WriteLine($" - Ruoli: {String.Join(", ", _ruoloIDs)}")
End Sub
' ✅ METODO PUBBLICO PER AGGIORNARE DATE
Public Sub AggiornaDate(nuovaDataInizio As Date, nuovaDataFine As Date)
Debug.WriteLine($"🔵 AggiornaDate: {nuovaDataInizio:dd/MM} - {nuovaDataFine:dd/MM}")
If _ruoloIDs Is Nothing OrElse _ruoloIDs.Count = 0 Then
MessageBox.Show("Nessun ruolo caricato!", "Errore", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Try
' ✅ 1. CREA NUOVE CONFIGURAZIONI
Dim nuoveConfigurazioni As New List(Of TabellaConfig)()
Dim dataCorrente As Date = nuovaDataInizio
While dataCorrente <= nuovaDataFine
Dim Ruoli As New List(Of Ruolo)
For Each id In _ruoloIDs
Ruoli.Add(Gestionale.gestioneRuoli.GetRuolo(id))
Next
Dim fasce = Gestionale.gestioneOrariFasce.GetFasce_Complete(dataCorrente, Ruoli)
nuoveConfigurazioni.Add(New TabellaConfig With {
.Data = dataCorrente,
.Fasce = fasce
})
dataCorrente = dataCorrente.AddDays(1)
End While
' ✅ 2. AGGIORNA PARAMETRI
_dataInizio = nuovaDataInizio
_dataFine = nuovaDataFine
' ✅ 3. RICARICA TABELLE
CaricaMultipleGiornate(nuoveConfigurazioni)
Debug.WriteLine($"✅ AggiornaDate: Completato - {nuoveConfigurazioni.Count} giorni")
Catch ex As Exception
Debug.WriteLine($"❌ ERRORE AggiornaDate: {ex.Message}")
MessageBox.Show($"Errore nell'aggiornamento: {ex.Message}", "Errore", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
' ✅ POSIZIONA TUTTE LE TABELLE CORRETTAMENTE
Private Sub PosizionaTabelle()
Debug.WriteLine("🔵 PosizionaTabelle...")
Dim yPosition As Integer = 10
Dim tabelleOrdinate = _tabellePerGiorno.OrderBy(Function(kvp) kvp.Key).ToList()
For Each kvp In tabelleOrdinate
Dim data = kvp.Key
Dim ctrl = kvp.Value
'Dim lblGiorno = _labelPerGiorno(data)
' ✅ POSIZIONA LABEL
'lblGiorno.Top = yPosition
yPosition += Panel1.Height
' ✅ POSIZIONA TABELLA
ctrl.Top = yPosition
Debug.WriteLine($" - {data:dd/MM/yyyy}: Y={yPosition}, H={ctrl.Height}")
yPosition += ctrl.Height + 20
Next
' ✅ AGGIORNA SCROLL
_container.AutoScrollMinSize = New Size(0, yPosition)
_container.Refresh()
_container.Update()
Debug.WriteLine($"✅ PosizionaTabelle: Completato - Scroll H={yPosition}")
End Sub
' ✅ GESTISCI INIZIALIZZAZIONE COMPLETATA
Private Sub HandleInizializzazione(larghezza As Integer, altezza As Integer)
Debug.WriteLine($"🔵 Inizializzazione: W={larghezza}, H={altezza}")
' ✅ RICALCOLA POSIZIONI QUANDO UNA TABELLA È PRONTA
If Not _staAggiornando Then
PosizionaTabelle()
End If
End Sub
Private Sub HandleSelezioneModificata(selezione As SelezioneTurno)
If _staAggiornando Then Return
Debug.WriteLine($"🔵 Selezione: Data={selezione.Data:dd/MM}, Fascia={selezione.FasciaID}, Dip={selezione.DipendenteID}")
End Sub
'Public Function OttieniTutteLeSelezioni() As List(Of SelezioneTurno)
' Dim tutte As New List(Of SelezioneTurno)()
' For Each kvp In _tabellePerGiorno
' tutte.AddRange(kvp.Value.OttieniSelezioni())
' Next
' Return tutte
'End Function
Private Sub FormTabella_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimeDal.ValueChanged
End Sub
Public Function OttieniTutteLeSelezioni() As List(Of SelezioneTurno)
Dim tutte As New List(Of SelezioneTurno)()
For Each kvp In _tabellePerGiorno
tutte.AddRange(kvp.Value.OttieniSelezioni())
Next
Return tutte
End Function
Private Sub BtnTabelle_Click(sender As Object, e As EventArgs) Handles BtnTabelle.Click
AggiornaDateDaPanel()
End Sub
Public Sub AggiornaDateDaPanelnuovo()
Try
' ✅ 1. LEGGI DATE
Dim dataInizio As Date = DateTimeDal.Value
Dim dataFine As Date = DateTimeAl.Value
Debug.WriteLine($"📅 Aggiornamento: {dataInizio:dd/MM} - {dataFine:dd/MM}")
' ✅ 2. VERIFICA RUOLI
If _ruoloIDs Is Nothing OrElse _ruoloIDs.Count = 0 Then
MessageBox.Show("Nessun ruolo caricato!", "Errore", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
' ✅ 3. PREPARA DATI (Logica invariata)
Dim nuoveConfigurazioni As New List(Of TabellaConfig)()
Dim dataCorrente As Date = dataInizio
While dataCorrente <= dataFine
Dim Ruoli As New List(Of Ruolo)
For Each id In _ruoloIDs
Ruoli.Add(Gestionale.gestioneRuoli.GetRuolo(id))
Next
Dim fasce = Gestionale.gestioneOrariFasce.GetFasce_Complete(dataCorrente, Ruoli)
nuoveConfigurazioni.Add(New TabellaConfig With {
.Data = dataCorrente,
.Fasce = fasce
})
dataCorrente = dataCorrente.AddDays(1)
End While
' ✅ 4. AGGIORNA PARAMETRI INTERNI
_dataInizio = dataInizio
_dataFine = dataFine
' ✅ 5. RICARICA TABELLE (CON PULIZIA PREVENTIVA)
CaricaMultipleGiornate(nuoveConfigurazioni)
Debug.WriteLine($"✅ Aggiornamento completato - {nuoveConfigurazioni.Count} giorni")
Catch ex As Exception
Debug.WriteLine($"❌ ERRORE AggiornaDateDaPanel: {ex.ToString()}")
MessageBox.Show($"Errore: {ex.Message}", "Errore", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
' ✅ METODO PER AGGIORNARE DATE (USA I TUOI DateTimePicker)
Public Sub AggiornaDateDaPanel()
Try
' ✅ 1. LEGGI DATE DAI TUOI CONTROLLI
Dim dataInizio As Date = DateTimeDal.Value
Dim dataFine As Date = DateTimeAl.Value
Debug.WriteLine($"📅 Aggiornamento: {dataInizio:dd/MM} - {dataFine:dd/MM}")
' ✅ 2. VERIFICA DI AVERE I RUOLI
If _ruoloIDs Is Nothing OrElse _ruoloIDs.Count = 0 Then
MessageBox.Show("Nessun ruolo caricato!", "Errore", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
' ✅ 3. CREA NUOVE CONFIGURAZIONI
Dim nuoveConfigurazioni As New List(Of TabellaConfig)()
Dim dataCorrente As Date = dataInizio
While dataCorrente <= dataFine
Dim Ruoli As New List(Of Ruolo)
For Each id In _ruoloIDs
Ruoli.Add(Gestionale.gestioneRuoli.GetRuolo(id))
Next
Dim fasce = Gestionale.gestioneOrariFasce.GetFasce_Complete(dataCorrente, Ruoli)
nuoveConfigurazioni.Add(New TabellaConfig With {
.Data = dataCorrente,
.Fasce = fasce
})
dataCorrente = dataCorrente.AddDays(1)
End While
' ✅ 4. AGGIORNA PARAMETRI INTERNI
_dataInizio = dataInizio
_dataFine = dataFine
' ✅ 5. RICARICA TABELLE
CaricaMultipleGiornate(nuoveConfigurazioni)
Debug.WriteLine($"✅ Aggiornamento completato - {nuoveConfigurazioni.Count} giorni")
Catch ex As Exception
Debug.WriteLine($"❌ ERRORE AggiornaDateDaPanel: {ex.ToString()}")
MessageBox.Show($"Errore: {ex.Message}", "Errore", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub BtnSalva_Click(sender As Object, e As EventArgs) Handles BtnSalva.Click
SalvaTuttiITurni()
End Sub
' ✅ ESTRAGGI TUTTI I TURNI (CONVERTI SelezioneTurno → Turno)
Private Sub SalvaTuttiITurni()
Try
' ✅ 1. RACCOGLI TUTTI I TURNI DA TUTTE LE TABELLE
Dim tuttiITurni As New List(Of Turno)()
For Each kvp In _tabellePerGiorno
Dim pannello = kvp.Value ' ControlTabella
Dim turniTabella = pannello.EstraiTurni()
Debug.WriteLine($"[Salvataggio] Tabella {kvp.Key:dd/MM}: {turniTabella.Count} turni")
tuttiITurni.AddRange(turniTabella)
Next
Debug.WriteLine($"=== SALVATAGGIO TURNI ===")
Debug.WriteLine($"Totale turni da salvare: {tuttiITurni.Count}")
' ✅ 2. CONTROLLA SE CI SONO TURNI DA SALVARE
If tuttiITurni.Count = 0 Then
Dim risultato = MessageBox.Show(
$"⚠️ Nessun turno da salvare!{vbCrLf}{vbCrLf}Vuoi eliminare tutti i turni esistenti nel periodo?",
"Attenzione",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning
)
If risultato = DialogResult.Yes Then
For Each ruoloID In _ruoloIDs
Gestionale.gestioneTurni.EliminaTurniPeriodo(_dataInizio, _dataFine, ruoloID)
Next
MessageBox.Show("✅ Turni eliminati!", "Completato", MessageBoxButtons.OK, MessageBoxIcon.Information)
CaricaDatiPeriodo()
End If
Return
End If
' ✅ 3. RAGGRUPPA PER DATA + RUOLO (NON SOLO PER RUOLO!)
Dim turniPerDataERuolo = tuttiITurni.GroupBy(Function(t) $"{t.Data:yyyy-MM-dd}_{t.RuoloID}")
Dim totaleSalvati As Integer = 0
For Each gruppo In turniPerDataERuolo
Dim parti = gruppo.Key.Split("_"c)
Dim data = Date.Parse(parti(0))
Dim ruoloID = CInt(parti(1))
Dim turniDelGruppo = gruppo.ToList()
Dim ruolo = Gestionale.gestioneRuoli.GetRuolo(ruoloID)
Dim nomeRuolo = If(ruolo IsNot Nothing, ruolo.Nome, $"ID {ruoloID}")
Debug.WriteLine($" 💾 {data:dd/MM} - Ruolo {nomeRuolo}: {turniDelGruppo.Count} turni")
' ✅ SALVA SOLO PER QUEL GIORNO E QUEL RUOLO
Dim salvati = Gestionale.gestioneTurni.SalvaTurniPeriodo(turniDelGruppo, ruoloID, data, data) ' ← data, data (NON _dataInizio, _dataFine!)
totaleSalvati += salvati
Next
MessageBox.Show(
$"✅ {totaleSalvati} turni salvati con successo!",
"Salvataggio Completato",
MessageBoxButtons.OK,
MessageBoxIcon.Information
)
Debug.WriteLine($"=== SALVATAGGIO COMPLETATO ===")
' ✅ 4. RICARICA I DATI AGGIORNATI
CaricaDatiPeriodo()
Catch ex As Exception
MessageBox.Show(
$"❌ Errore durante il salvataggio:{vbCrLf}{ex.Message}",
"Errore",
MessageBoxButtons.OK,
MessageBoxIcon.Error
)
Debug.WriteLine($"[ERRORE] Salvataggio: {ex.Message}")
Debug.WriteLine($"[STACK] {ex.StackTrace}")
End Try
End Sub
' ✅ METODO PER RICARICARE IL PERIODO CORRENTE
Private Sub CaricaDatiPeriodo()
Try
Debug.WriteLine($"🔵 CaricaDatiPeriodo: {_dataInizio:dd/MM} - {_dataFine:dd/MM}")
Dim nuoveConfigurazioni As New List(Of TabellaConfig)()
Dim dataCorrente As Date = _dataInizio
While dataCorrente <= _dataFine
Dim Ruoli As New List(Of Ruolo)
For Each id In _ruoloIDs
Ruoli.Add(Gestionale.gestioneRuoli.GetRuolo(id))
Next
' ✅ CARICA FASCE CON TURNI ESISTENTI
Dim fasce = Gestionale.gestioneOrariFasce.GetFasce_Complete(dataCorrente, Ruoli)
nuoveConfigurazioni.Add(New TabellaConfig With {
.Data = dataCorrente,
.Fasce = fasce
})
dataCorrente = dataCorrente.AddDays(1)
End While
CaricaMultipleGiornate(nuoveConfigurazioni)
Debug.WriteLine($"✅ CaricaDatiPeriodo: Completato")
Catch ex As Exception
Debug.WriteLine($"❌ ERRORE CaricaDatiPeriodo: {ex.Message}")
MessageBox.Show($"Errore: {ex.Message}", "Errore")
End Try
End Sub
End Class

View File

@@ -23,6 +23,7 @@ Partial Class FormTurni
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.Panel1 = New System.Windows.Forms.Panel()
Me.Button1 = New System.Windows.Forms.Button()
Me.btnCarica = New System.Windows.Forms.Button()
Me.Label3 = New System.Windows.Forms.Label()
Me.ComboRuolo = New System.Windows.Forms.ComboBox()
@@ -32,7 +33,6 @@ Partial Class FormTurni
Me.DtpDal = New System.Windows.Forms.DateTimePicker()
Me.PanelGiorni = New System.Windows.Forms.FlowLayoutPanel()
Me.Button2 = New System.Windows.Forms.Button()
Me.Button1 = New System.Windows.Forms.Button()
Me.Panel1.SuspendLayout()
Me.SuspendLayout()
'
@@ -52,6 +52,15 @@ Partial Class FormTurni
Me.Panel1.Size = New System.Drawing.Size(1689, 55)
Me.Panel1.TabIndex = 0
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(769, 7)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(93, 42)
Me.Button1.TabIndex = 14
Me.Button1.Text = "Salva Tabelle"
Me.Button1.UseVisualStyleBackColor = True
'
'btnCarica
'
Me.btnCarica.AutoSize = True
@@ -134,15 +143,6 @@ Partial Class FormTurni
Me.Button2.Text = "Salva tutto"
Me.Button2.UseVisualStyleBackColor = True
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(769, 7)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(93, 42)
Me.Button1.TabIndex = 14
Me.Button1.Text = "Salva Tabelle"
Me.Button1.UseVisualStyleBackColor = True
'
'FormTurni
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
@@ -152,6 +152,7 @@ Partial Class FormTurni
Me.Controls.Add(Me.Panel1)
Me.Name = "FormTurni"
Me.Text = "FormTurni"
Me.WindowState = System.Windows.Forms.FormWindowState.Maximized
Me.Panel1.ResumeLayout(False)
Me.Panel1.PerformLayout()
Me.ResumeLayout(False)

View File

@@ -1,44 +1,30 @@
Public Class FormTurni
'Private _turniCorrenti As List(Of Turno)
'Private _tuttiIDipendenti As List(Of Dipendente)
Private _ruoloSelezionato As Ruolo
Private _dataInizio As Date
Private _dataFine As Date
Private _maxComboPerGiorno As Integer = 0
Private _larghezzaMax As Integer = 0 ' ← TRACK LARGHEZZA
Private _pannelliCreati As Integer = 0 ' ← TRACK PANNELLI
Private _totalePannelli As Integer = 0 ' ← TRACK TOTALE
Private _larghezzaMax As Integer = 0
Private _pannelliCreati As Integer = 0
Private _totalePannelli As Integer = 0
Private _turniSalvati As List(Of Turno) = Nothing
Private Sub FormTurni_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Debug.WriteLine("=== DEBUG VISIBILITÀ ===")
Debug.WriteLine($"PanelGiorni.Visible: {PanelGiorni.Visible}")
Debug.WriteLine($"PanelGiorni.BackColor: {PanelGiorni.BackColor}")
Debug.WriteLine($"PanelGiorni.Dock: {PanelGiorni.Dock}")
Debug.WriteLine($"PanelGiorni.Size: {PanelGiorni.Size}")
Debug.WriteLine($"Form.Size: {Me.Size}")
Debug.WriteLine($"PanelGiorni.Parent: {PanelGiorni.Parent?.GetType().Name}")
Debug.WriteLine("====================")
With PanelGiorni
.Dock = DockStyle.Fill
.AutoScroll = True
.AutoSize = False
.Visible = True ' ⚠️ FORZA VISIBILE
.BringToFront() ' ⚠️ PORTA IN PRIMO PIANO
.Visible = True
.BringToFront()
End With
ImpostaPeriodoDefault()
CaricaComboRuoli()
End Sub
Private Sub OnComboBoxDipendenteCambiato(data As Date, fasciaID As Integer, slot As Integer, dipendenteID As Integer)
Debug.WriteLine($"[Form] Combo: {data:dd/MM} | Fascia={fasciaID} | Slot={slot} | Dip={dipendenteID}")
' Aggiorna visivamente la combo
Dim pannello = PanelGiorni.Controls.OfType(Of FasciaRowControl)() _
.FirstOrDefault(Function(p) p.Data = data)
If pannello IsNot Nothing Then
pannello.AggiornaComboBox(fasciaID, slot, dipendenteID)
End If
End Sub
Private Sub ImpostaPeriodoDefault()
DtpDal.Value = Date.Today
@@ -46,187 +32,226 @@
End Sub
Private Sub CaricaComboRuoli()
Dim listaRuoli = Gestionale.gestioneRuoli.GetRuoli()
ComboRuolo.DataSource = Nothing
ComboRuolo.DisplayMember = "Nome"
ComboRuolo.ValueMember = "ID"
ComboRuolo.DataSource = listaRuoli
End Sub
' ✅ CARICA DATI E PANNELLI
Private Sub btnCarica_Click(sender As Object, e As EventArgs) Handles btnCarica.Click
CaricaDatiPeriodo()
'CreaPannelliPerGiorno()
' Crea pannelli per ogni giorno
_pannelliCreati = 0
_totalePannelli = 0
Dim dataCorrente As Date = _dataInizio
While dataCorrente <= _dataFine
_totalePannelli += 1
'CaricaPannelloTurni(dataCorrente)
creaPannello(dataCorrente)
dataCorrente = dataCorrente.AddDays(1)
End While
'resizeGriglie()
End Sub
Private Sub CaricaDatiPeriodo()
Try
_ruoloSelezionato = Gestionale.gestioneRuoli.GetRuolo(CInt(ComboRuolo.SelectedValue))
If _ruoloSelezionato Is Nothing Then Return
If _ruoloSelezionato Is Nothing Then
MessageBox.Show("Seleziona un ruolo!")
Return
End If
Debug.WriteLine("ID cambiato: " & _ruoloSelezionato.ID)
_dataInizio = DtpDal.Value.Date
_dataFine = DtpAl.Value.Date
' Carica dipendenti
'_tuttiIDipendenti = Gestionale.gestioneDipendenti.GetDipendentiDisponibiliPerRuolo(_ruoloSelezionato.ID, _dataInizio)
' ✅ CARICA I TURNI SALVATI DAL DATABASE
_turniSalvati = Gestionale.gestioneTurni.GetTurniPeriodo(_dataInizio, _dataFine, _ruoloSelezionato.ID)
Debug.WriteLine($"=== TURNI SALVATI TROVATI: {_turniSalvati.Count} ===")
' Carica turni esistenti
'_turniCorrenti = Gestionale.gestioneTurni.GetTurniPeriodo(_dataInizio, _dataFine, _ruoloSelezionato.ID)
' Pulisci il pannello
' ✅ PULISCI IL PANNELLO
PanelGiorni.Controls.Clear()
_larghezzaMax = 0
_pannelliCreati = 0
_totalePannelli = 0
' ✅ CREA PANNELLI PER OGNI GIORNO
Dim dataCorrente As Date = _dataInizio
While dataCorrente <= _dataFine
_totalePannelli += 1
CreaPannello(dataCorrente) ' ← Qui si crea RigheTabella COMPLETA
dataCorrente = dataCorrente.AddDays(1)
End While
' Forza refresh finale
PanelGiorni.PerformLayout()
PanelGiorni.Refresh()
Catch ex As Exception
MessageBox.Show("Errore: " & ex.Message)
Debug.WriteLine($"[ERRORE] CaricaDatiPeriodo: {ex.Message}")
End Try
End Sub
Private Sub creaPannello(data As Date)
Dim R As New RigheTabella
Private Sub CreaPannello(data As Date)
' ✅ 1. CREA RIGHETABELLA
Dim R As New RigheTabella With {
.Data = data,
.RuoloID = _ruoloSelezionato.ID
}
' ✅ 2. CARICA FASCE CON DIPENDENTI DISPONIBILI
Dim fasce = Gestionale.gestioneOrariFasce.GetFasce_PerGiorno_Ruolo(data.DayOfWeek, _ruoloSelezionato.ID)
R.Fasce = fasce
R.Fasce = New List(Of Fascia)()
For Each f As Fascia In fasce
f.DipentiPresenti = Gestionale.gestioneDipendenti.GetDipendentiDisponibiliPerFascia(_ruoloSelezionato.ID, data, f.FasciaOraria.ID)
' Dipendenti disponibili (per le combo)
f.DipentiDisponibili = Gestionale.gestioneDipendenti.GetDipendentiDisponibiliPerFascia(
_ruoloSelezionato.ID, data, f.FasciaOraria.ID)
' ✅ INIZIALIZZA ASSEGNATI VUOTI
f.DipendentiAssegnati = Enumerable.Repeat(Of Dipendente)(Nothing, f.PersoneNecessarie).ToList()
R.Fasce.Add(f)
Next
' ✅ 3. POPOLA DIPENDENTI ASSEGNATI DAI TURNI SALVATI (DAL DB)
Dim turniDelGiorno = _turniSalvati.Where(Function(t) t.Data.Date = data.Date).ToList()
For Each turno In turniDelGiorno
Dim fascia = R.Fasce.FirstOrDefault(Function(f) f.FasciaOraria.ID = turno.FasciaID)
If fascia IsNot Nothing AndAlso turno.DipendenteID.HasValue AndAlso turno.DipendenteID.Value > 0 Then
Dim slot = turno.OrdineVisualizzazione
If slot >= 1 AndAlso slot <= fascia.PersoneNecessarie Then
' ✅ ASSEGNA IL DIPENDENTE ALLO SLOT CORRETTO
fascia.DipendentiAssegnati(slot - 1) = New Dipendente With {
.ID = turno.DipendenteID.Value,
.Nome = turno.DipendenteNome,
.Cognome = turno.DipendenteCognome
}
End If
End If
Next
Debug.WriteLine($"[Form] {data:dd/MM}: {turniDelGiorno.Count} turni assegnati")
' ✅ 4. CREA IL CONTROLLO CON RIGHETABELLA COMPLETA
Dim pannello As New FasciaRowControl(data, R)
'pannello.Dock = DockStyle.Fill
PanelGiorni.Controls.Add(pannello)
Dim dipendentiPerFascia As New Dictionary(Of Integer, List(Of Dipendente))
Dim turniSalvati = Gestionale.gestioneTurni.GetTurniPerGiorno(data, _ruoloSelezionato.ID)
' ✅ AGGIUNGI HANDLER PRIMA DI AGGIUNGERE AL PANEL
pannello.Dock = DockStyle.Top
' ✅ 5. AGGIUNGI HANDLER
AddHandler pannello.InizializzazioneCompletata, AddressOf OnPannelloPronto
AddHandler pannello.ComboBoxDipendenteCambiato, AddressOf OnComboBoxDipendenteCambiato
'pannello.InizializzaTimeline(data, fasce, dipendentiPerFascia, turniSalvati)
PanelGiorni.Controls.Add(pannello)
Debug.WriteLine($"[Form] Pannello creato per: {data:dd/MM/yyyy}")
End Sub
' ✅ GESTISCE CAMBIO COMBOBOX (CON haConflitto)
Private Sub OnComboBoxDipendenteCambiato(data As Date, fasciaID As Integer, slot As Integer,
dipendenteID As Integer, haConflitto As Boolean)
Debug.WriteLine($"[Form] Combo: {data:dd/MM} | Fascia={fasciaID} | Slot={slot} | Dip={dipendenteID}")
dipendenteID As Integer, haConflitto As Boolean,
haConflittoGrave As Boolean)
Debug.WriteLine($"[Form] Fascia={fasciaID} | Slot={slot} | Dip={dipendenteID}")
If haConflitto Then
Debug.WriteLine($"⚠️ ATTENZIONE: Dipendente {dipendenteID} è già assegnato in altre fasce!")
' Puoi mostrare un messaggio o loggare il conflitto
If haConflittoGrave Then
Debug.WriteLine($"🔴 CONFLITTO GRAVE: Dipendente {dipendenteID} ha fasce sovrapposte!")
'MessageBox.Show($"⚠️ ATTENZIONE:{vbCrLf}Il dipendente è già assegnato a una fascia con orario sovrapposto!",
'"Conflitto Grave", MessageBoxButtons.OK, MessageBoxIcon.Warning)
ElseIf haConflitto Then
Debug.WriteLine($"🟡 CONFLITTO: Dipendente {dipendenteID} è in altre fasce (non sovrapposte)")
End If
'If dipendenteID > 0 Then
' SalvaTurno(data, fasciaID, slot, dipendenteID)
'End If
End Sub
' ✅ GESTISCE INIZIALIZZAZIONE PANNELLO + CARICA TURNI SALVATI
Private Sub OnPannelloPronto(larghezza As Integer)
' ✅ TRACK DELLA LARGHEZZA MASSIMA
' Track larghezza
If larghezza > _larghezzaMax Then
_larghezzaMax = larghezza
End If
_pannelliCreati += 1
' ✅ QUANDO TUTTI I PANNELLI HANNO FINITO, RIDIMENSIONA IL FORM
' ✅ TROVA IL PANNELLO DAI CONTROLLI (NON DA SENDER)
' Cerca l'ultimo pannello aggiunto che ha W = larghezza
Dim pannello = PanelGiorni.Controls.OfType(Of FasciaRowControl)().FirstOrDefault(Function(p) p.W = larghezza)
If pannello IsNot Nothing AndAlso _turniSalvati IsNot Nothing Then
' ✅ CARICA I TURNI SALVATI PER QUESTO GIORNO
Dim turniDelGiorno = _turniSalvati.Where(Function(t) t.Data.Date = pannello.Data).ToList()
If turniDelGiorno.Count > 0 Then
Debug.WriteLine($"[Form] Caricamento {turniDelGiorno.Count} turni per {pannello.Data:dd/MM}")
'pannello.CaricaTurniSalvati(turniDelGiorno)
End If
End If
' ✅ RIDIMENSIONA FORM QUANDO TUTTI I PANNELLI SONO PRONTI
If _pannelliCreati = _totalePannelli Then
Me.Width = _larghezzaMax + 50 ' +50 per i bordi del Form
Me.Width = _larghezzaMax + 50
Debug.WriteLine($"=== FORM RIDIMENSIONATO ===")
Debug.WriteLine($"Larghezza Max: {_larghezzaMax}")
Debug.WriteLine($"Form.Width: {Me.Width}")
Debug.WriteLine($"Pannelli: {_pannelliCreati}/{_totalePannelli}")
End If
End Sub
' ✅ SALVA TUTTI I TURNI
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SalvaTuttiITurni()
End Sub
Private Sub SalvaTuttiITurni()
Try
' ✅ 1. RACCOGLI TUTTI I TURNI DA TUTTI I PANNELLI
Dim tuttiITurni As New List(Of Turno)()
For Each ctrl As Control In PanelGiorni.Controls
If TypeOf ctrl Is FasciaRowControl Then
Dim pannello = CType(ctrl, FasciaRowControl)
tuttiITurni.AddRange(pannello.EstraiTurni())
End If
Next
Debug.WriteLine($"=== SALVATAGGIO TURNI ===")
Debug.WriteLine($"Totale turni da salvare: {tuttiITurni.Count}")
'Private Sub SalvaTurni(sender As Object, e As EventArgs)
' ✅ 2. CONTROLLA SE CI SONO TURNI DA SALVARE
If tuttiITurni.Count = 0 Then
Dim risultato = MessageBox.Show("⚠️ Nessun turno da salvare!{vbCrLf}Vuoi eliminare tutti i turni esistenti nel periodo?",
"Attenzione",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning)
' Dim btn = CType(sender, Button)
If risultato = DialogResult.Yes Then
' Elimina tutti i turni nel periodo
Gestionale.gestioneTurni.EliminaTurniPeriodo(_dataInizio, _dataFine, _ruoloSelezionato.ID)
MessageBox.Show("✅ Turni eliminati!", "Completato", MessageBoxButtons.OK, MessageBoxIcon.Information)
CaricaDatiPeriodo()
End If
Return
End If
' Dim tag = btn.Tag
' ✅ 3. SALVA NEL DATABASE
Dim salvati As Integer = Gestionale.gestioneTurni.SalvaTurniPeriodo(tuttiITurni, _ruoloSelezionato.ID, _dataInizio, _dataFine)
' Dim data As Date = tag.Data
' Dim fasciaID As Integer = tag.FasciaID
' Dim comboList As List(Of ComboBox) = tag.Combo
MessageBox.Show($"✅ {salvati} turni salvati con successo!",
"Salvataggio Completato",
MessageBoxButtons.OK,
MessageBoxIcon.Information)
' Dim turniEsistenti = _turniCorrenti.
' Where(Function(t) t.Data.Date = data.Date AndAlso t.FasciaID = fasciaID).
' OrderBy(Function(t) t.ID).
' ToList()
Debug.WriteLine($"=== SALVATAGGIO COMPLETATO ===")
' For i As Integer = 0 To comboList.Count - 1
' Dim dipID = CInt(comboList(i).SelectedValue)
' Dim turnoEsistente As Turno = Nothing
' If i < turniEsistenti.Count Then turnoEsistente = turniEsistenti(i)
' If dipID = 0 Then
' If turnoEsistente IsNot Nothing Then
' Gestionale.gestioneTurni.EliminaTurno(turnoEsistente.ID)
' End If
' Else
' Dim turno As New Turno With {
' .ID = If(turnoEsistente IsNot Nothing, turnoEsistente.ID, 0),
' .DipendenteID = dipID,
' .RuoloID = _ruoloSelezionato.ID,
' .FasciaID = fasciaID,
' .Data = data
' }
' Gestionale.gestioneTurni.SalvaTurno(turno)
' End If
' Next
' MessageBox.Show("Turni salvati")
' CaricaDatiPeriodo()
'End Sub
' ✅ 4. RICARICA I DATI AGGIORNATI
CaricaDatiPeriodo()
Catch ex As Exception
MessageBox.Show($"❌ Errore durante il salvataggio:{vbCrLf}{ex.Message}",
"Errore",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
Debug.WriteLine($"[ERRORE] Salvataggio: {ex.Message}")
Debug.WriteLine($"[STACK] {ex.StackTrace}")
End Try
End Sub
Private Sub ComboRuolo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboRuolo.SelectedIndexChanged
If ComboRuolo.SelectedValue IsNot Nothing Then
_ruoloSelezionato = New Ruolo With {
.ID = CInt(ComboRuolo.SelectedValue),
.Nome = ComboRuolo.Text
}
.ID = CInt(ComboRuolo.SelectedValue),
.Nome = ComboRuolo.Text
}
Debug.WriteLine("ID ruolo selezionato: " & _ruoloSelezionato.ID)
End If
End Sub
Private Sub PanelGiorni_Paint(sender As Object, e As PaintEventArgs) Handles PanelGiorni.Paint
End Sub
Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class
Public Class ComboTag
Public Property Data As Date
Public Property FasciaID As Integer
End Class

View File

@@ -126,27 +126,37 @@
Return ids
End Function
Public Shared Sub ChecklistBox_Spunta(clb As CheckedListBox, dato As List(Of Integer))
' ← 1. DESELEZIONA TUTTI
For i As Integer = 0 To clb.Items.Count - 1
clb.SetItemChecked(i, False)
Next
' ← 1. SE dato IS NOTHING → DESELEZIONA TUTTO (Giornata Intera / NULL)
If dato Is Nothing Then
For i As Integer = 0 To clb.Items.Count - 1
clb.SetItemChecked(i, False)
Next
Return
End If
' ← 2. SELEZIONA QUELLI PRESENTI NELLA LISTA
' ← 2. SE dato È VUOTO → SELEZIONA TUTTO (Tutte le fasce)
If dato.Count = 0 Then
For i As Integer = 0 To clb.Items.Count - 1
clb.SetItemChecked(i, True)
Next
Return
End If
' ← 3. SE dato HA VALORI → SELEZIONA SOLO QUELLI SPECIFICI
For i As Integer = 0 To clb.Items.Count - 1
Dim item = clb.Items(i)
If item Is Nothing Then Continue For
Try
' ← PROVA DIVERSE PROPRIETÀ (funziona con entrambi i tipi)
Dim prop As Reflection.PropertyInfo = Nothing
' Prima prova "ID" (classi come Ruolo, Fascia)
prop = item.GetType().GetProperty("ID")
' Se non esiste, prova "Value" (tipi anonimi da PopolaCheckedListBox_T)
' Se non esiste, prova "Value" (tipi anonimi)
If prop Is Nothing Then prop = item.GetType().GetProperty("Value")
' Se non esiste, prova "Key" (KeyValuePair da PopolaCheckedListBox_da_Database)
' Se non esiste, prova "Key" (KeyValuePair)
If prop Is Nothing Then prop = item.GetType().GetProperty("Key")
' ← LEGGI IL VALORE
@@ -154,9 +164,7 @@
Dim val = prop.GetValue(item)
If val IsNot Nothing AndAlso IsNumeric(val) Then
Dim id = CInt(val)
If dato.Contains(id) Then
clb.SetItemChecked(i, True)
End If
clb.SetItemChecked(i, dato.Contains(id))
End If
End If
Catch ex As Exception
@@ -187,4 +195,51 @@ Public Class emjoi
Public Shared nuovo As String = "📝"
Public Shared aggiorna As String = "🔄"
End Class
' ✅ 5. RISULTATO (Output da ControlTabella)
Public Class SelezioneTurno
Friend RuoloNome As String
Friend FasciaNome As String
Public Property Data As Date
Public Property RuoloID As Integer
Public Property FasciaID As Integer
Public Property Slot As Integer
Public Property DipendenteID As Integer
Public Property HaConflitto As Boolean
End Class
' ✅ CLASSI DI SUPPORTO PER FORMTABELLA
' Informazioni su un conflitto trovato
Public Class InfoConflitto
Public Property HaConflitto As Boolean = False
Public Property HaSovrapposizione As Boolean = False ' True = Grave (stesso orario)
Public Property Messaggio As String = ""
Public Property RuoloConflittoID As Integer = 0
Public Property RuoloConflittoNome As String = ""
Public Property FasciaConflittoID As Integer = 0
End Class
' Risultato del salvataggio
Public Class RisultatoSalvataggio
Public Property Successo As Boolean
Public Property Messaggio As String
Public Property TurniSalvati As Integer = 0
End Class
' ✅ 4. CONFIGURAZIONE TABELLA (Input per ControlTabella)
Public Class TabellaConfig
Public Property Data As Date
' ✅ CAMBIA: Da singolo ruolo a lista di ruoli
Public Property Ruoli As List(Of Ruolo)
Public Property Fasce As List(Of Fascia)
End Class
' ✅ CLASSE PER RISULTATO CONTROLLO CONFLITTI
Public Class ConflittoResult
Public Property HaConflitto As Boolean = False
Public Property HaSovrapposizione As Boolean = False
Public Property Messaggio As String = ""
Public Property RuoloConflitto As String = ""
Public Property OraInizioConflitto As String = ""
Public Property OraFineConflitto As String = ""
End Class

View File

@@ -11,8 +11,7 @@ Public Class GestioneAssenze
Dim assenzaID As Integer = 0
Using conn = db.GetConnection()
' ← 1. TROVA O CREA ASSENZA (SENZA TRANS)
' ← 1. TROVA O CREA ASSENZA
Using cmd As New SqliteCommand("SELECT ID FROM Assenze WHERE DipendenteID=@DipendenteID AND Data=@Data", conn)
cmd.Parameters.AddWithValue("@DipendenteID", a.DipendenteID)
cmd.Parameters.AddWithValue("@Data", a.DataInizio.ToString("yyyy-MM-dd"))
@@ -32,10 +31,13 @@ Public Class GestioneAssenze
cmdUpdate.Parameters.AddWithValue("@Motivazione", If(String.IsNullOrEmpty(a.Motivazione), DBNull.Value, a.Motivazione))
cmdUpdate.Parameters.AddWithValue("@Approvata", If(a.Approvata, 1, 0))
cmdUpdate.Parameters.AddWithValue("@ID", assenzaID)
cmdUpdate.ExecuteNonQuery() ' ← ✅ ESEGUI L'UPDATE!
cmdUpdate.ExecuteNonQuery()
End Using
Else
Using cmdInsert As New SqliteCommand("INSERT INTO Assenze (DipendenteID, Data, TipoAssenzaID, Motivazione, Approvata) VALUES (@DipendenteID, @Data, @TipoAssenzaID, @Motivazione, @Approvata); SELECT last_insert_rowid();", conn)
Using cmdInsert As New SqliteCommand("
INSERT INTO Assenze (DipendenteID, Data, TipoAssenzaID, Motivazione, Approvata)
VALUES (@DipendenteID, @Data, @TipoAssenzaID, @Motivazione, @Approvata);
SELECT last_insert_rowid();", conn)
cmdInsert.Parameters.AddWithValue("@DipendenteID", a.DipendenteID)
cmdInsert.Parameters.AddWithValue("@Data", a.DataInizio.ToString("yyyy-MM-dd"))
cmdInsert.Parameters.AddWithValue("@TipoAssenzaID", a.TipoAssenzaID)
@@ -46,24 +48,19 @@ Public Class GestioneAssenze
End If
End Using
' ← 2. CANCELLA FASCE VECCHIE (SENZA TRANS)
'Using cmd As New SqliteCommand("DELETE FROM AssenzeFasce WHERE AssenzaID = @AssenzaID", conn)
' cmd.Parameters.AddWithValue("@AssenzaID", assenzaID)
' cmd.ExecuteNonQuery()
'End Using
' ← 3. INSERISCI FASCE NUOVE (SENZA TRANS)
' ← 2. INSERISCI FASCE (SOLO SE NON ESISTONO GIÀ)
For Each f In a.Fasce
Using cmd As New SqliteCommand("INSERT INTO AssenzeFasce (TipoAssenzaID, FasciaID) VALUES (@TipoAssenzaID, @FasciaID)", conn)
Using cmd As New SqliteCommand("
INSERT OR IGNORE INTO AssenzeFasce (TipoAssenzaID, FasciaID)
VALUES (@TipoAssenzaID, @FasciaID)", conn)
cmd.Parameters.AddWithValue("@TipoAssenzaID", a.TipoAssenzaID)
cmd.Parameters.AddWithValue("@FasciaID", f.FasciaID)
cmd.ExecuteNonQuery()
End Using
Next
End Using ' ← La connessione si chiude, ma i dati SONO GIÀ SALVATI (auto-commit)
End Using
End Sub
''' <summary>
''' Salva assenza per un intervallo di date
''' </summary>
@@ -72,44 +69,93 @@ Public Class GestioneAssenze
While dataCorrente <= a.DataFine
' ← Passa la data corrente, NON modificare a.DataInizio
a.DataInizio = dataCorrente
SalvaAssenzaSingola(a)
dataCorrente = dataCorrente.AddDays(1)
End While
End Sub
'''' <summary>
'''' Salva assenza per un intervallo di date (chiama SalvaAssenzaSingola per ogni giorno)
'''' </summary>
'Public Sub SalvaAssenza(a As Assenza)
' ' ← CICLO SU TUTTE LE DATE
' Dim dataCorrente As Date = a.DataInizio
Public Function GetOreAssenzaDipendente(dipendenteID As Integer,
Optional dataInizio As Date? = Nothing,
Optional dataFine As Date? = Nothing) As Double
Dim totaleOre As Double = 0.0
' While dataCorrente <= a.DataFine
' ' Salva singolo giorno
' a.DataInizio = dataCorrente
' SalvaAssenzaSingola(a)
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
' Query corretta: prima MIN/MAX per giorno, poi SUM totale
cmd.CommandText = "
SELECT COALESCE(SUM(OreGiornaliere), 0)
FROM (
SELECT
A.Data,
(strftime('%s', '1970-01-01 ' || MAX(F.OraFine)) -
strftime('%s', '1970-01-01 ' || MIN(F.OraInizio))) / 3600.0 as OreGiornaliere
FROM Assenze A
INNER JOIN AssenzeFasce AF ON A.TipoAssenzaID = AF.TipoAssenzaID
INNER JOIN Fasce F ON AF.FasciaID = F.ID
WHERE A.DipendenteID = @dip
AND A.Approvata = 1
AND (@dataInizio IS NULL OR A.Data >= @dataInizio)
AND (@dataFine IS NULL OR A.Data <= @dataFine)
GROUP BY A.Data, A.TipoAssenzaID
)"
' ' Passa al giorno successivo
' dataCorrente = dataCorrente.AddDays(1)
' End While
'End Sub
cmd.Parameters.AddWithValue("@dip", dipendenteID)
If dataInizio.HasValue Then
cmd.Parameters.AddWithValue("@dataInizio", dataInizio.Value.ToString("yyyy-MM-dd"))
Else
cmd.Parameters.AddWithValue("@dataInizio", DBNull.Value)
End If
If dataFine.HasValue Then
cmd.Parameters.AddWithValue("@dataFine", dataFine.Value.ToString("yyyy-MM-dd"))
Else
cmd.Parameters.AddWithValue("@dataFine", DBNull.Value)
End If
Dim result = cmd.ExecuteScalar()
If result IsNot Nothing AndAlso Not DBNull.Value.Equals(result) Then
totaleOre = Convert.ToDouble(result)
End If
End Using
End Using
Return totaleOre
End Function
''' <summary>
''' Ottiene le assenze di un dipendente in un periodo
''' </summary>
Public Function GetAssenzeDipendente(dipendenteID As Integer, dataInizio As Date, dataFine As Date) As List(Of Assenza)
Public Function GetAssenzeDipendente(dipendenteID As Integer,
Optional dataInizio As Date? = Nothing,
Optional dataFine As Date? = Nothing) As List(Of Assenza)
Dim lista As New List(Of Assenza)
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
' Query con filtri data condizionali
cmd.CommandText = "
SELECT a.ID, a.DipendenteID, a.Data, a.TipoAssenzaID, a.Motivazione, a.Approvata
SELECT a.ID, a.DipendenteID, a.Data, a.TipoAssenzaID, t.Nome AS TipoAssenzaNome, a.Motivazione, a.Approvata
FROM Assenze a
INNER JOIN TipiAssenza t ON a.TipoAssenzaID = t.ID
WHERE a.DipendenteID = @dip
AND a.Data >= @inizio AND a.Data <= @fine
AND (@dataInizio IS NULL OR a.Data >= @dataInizio)
AND (@dataFine IS NULL OR a.Data <= @dataFine)
ORDER BY a.Data"
cmd.Parameters.AddWithValue("@dip", dipendenteID)
cmd.Parameters.AddWithValue("@inizio", dataInizio.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@fine", dataFine.ToString("yyyy-MM-dd"))
' Aggiungi parametri data solo se forniti (altrimenti passa NULL)
If dataInizio.HasValue Then
cmd.Parameters.AddWithValue("@dataInizio", dataInizio.Value.ToString("yyyy-MM-dd"))
Else
cmd.Parameters.AddWithValue("@dataInizio", DBNull.Value)
End If
If dataFine.HasValue Then
cmd.Parameters.AddWithValue("@dataFine", dataFine.Value.ToString("yyyy-MM-dd"))
Else
cmd.Parameters.AddWithValue("@dataFine", DBNull.Value)
End If
Using reader = cmd.ExecuteReader()
While reader.Read()
@@ -122,10 +168,14 @@ Public Class GestioneAssenze
a.DataFine = data
a.TipoAssenzaID = reader.GetInt32(reader.GetOrdinal("TipoAssenzaID"))
' ← Leggi il nome del tipo assenza
a.TipoAssenzaNome = If(reader.IsDBNull(reader.GetOrdinal("TipoAssenzaNome")), "", reader.GetString(reader.GetOrdinal("TipoAssenzaNome")))
a.Motivazione = If(reader.IsDBNull(reader.GetOrdinal("Motivazione")), "", reader.GetString(reader.GetOrdinal("Motivazione")))
a.Approvata = reader.GetInt32(reader.GetOrdinal("Approvata")) = 1
' ← CORRETTO: Leggi fasce salvate per QUESTA assenza (da AssenzeFasce)
' ← Leggi fasce salvate per QUESTA assenza
a.Fasce = GetFasceAssenza(a.ID)
lista.Add(a)
@@ -176,32 +226,6 @@ Public Class GestioneAssenze
Return ids
End Function
'Public Function IsAssenteInFascia(dipendenteID As Integer, data As Date, fasciaID As Integer) As Boolean
' Using conn = db.GetConnection()
' Using cmd = conn.CreateCommand()
' cmd.CommandText = "
' SELECT COUNT(*)
' FROM Assenze a
' JOIN TipoAssenzaFasce taf
' ON taf.TipoAssenzaID = a.TipoAssenzaID
' WHERE a.DipendenteID = @dip
' AND a.Data = @data
' AND taf.FasciaID = @fascia
' AND a.Approvata = 1
' "
' cmd.Parameters.AddWithValue("@dip", dipendenteID)
' cmd.Parameters.AddWithValue("@data", data.ToString("yyyy-MM-dd"))
' cmd.Parameters.AddWithValue("@fascia", fasciaID)
' Return CInt(cmd.ExecuteScalar()) > 0
' End Using
' End Using
'End Function
''' <summary>
@@ -225,7 +249,7 @@ Public Class Assenza
Public Property DataInizio As Date
Public Property DataFine As Date
Public Property TipoAssenzaNome As String
Public Property TipoAssenzaID As Integer
Public Property Motivazione As String
@@ -243,6 +267,42 @@ Public Class Assenza
End Function
End Class
'Public Class Assenza
' Public Property ID As Integer
' Public Property DipendenteID As Integer
' ' Per l'UI va bene avere il range
' Public Property DataInizio As Date
' Public Property DataFine As Date
' Public Property TipoAssenzaNome As String
' Public Property TipoAssenzaID As Integer
' Public Property Motivazione As String
' Public Property Approvata As Boolean
' ' ← AGGIUNTO: Gestisce il caso "Giornata Intera" (NULL)
' ' Se ha valore = assenza specifica
' ' Se è Nothing (= NULL) = assenza per tutte le fasce
' Public Property FasciaID As Integer? ' Nullable Integer
' ' Per l'UI: mantieni la lista per le checkbox
' Public Property Fasce As New List(Of AssenzaFascia)
' ' Helper per capire se è giornata intera
' 'Public ReadOnly Property IsGiornataIntera As Boolean
' ' Get
' ' Return (TipoAssenzaID = 1 OrElse TipoAssenzaID = 2) OrElse FasciaID Is Nothing
' ' End Get
' 'End Property
' 'Public Function AssenteInFascia(fasciaID As Integer) As Boolean
' ' If IsGiornataIntera Then Return True
' ' Return Fasce.Any(Function(f) f.FasciaID = fasciaID)
' 'End Function
' Public Overloads Function ToString() As String
' Return $"ID:{ID}, Dip:{DipendenteID}, Tipo:{TipoAssenzaID}, Fascia:{If(FasciaID?.ToString(), "TUTTE")}"
' End Function
'End Class
Public Class AssenzaFascia
Public Property ID As Integer

View File

@@ -7,56 +7,6 @@ Public Class GestioneDipendenti
End Sub
'''' <summary>
'''' Restituisce tutti i dipendenti con filtro opzionale per stato attivo
'''' </summary>
'''' <param name="attivo">True = solo attivi, False = solo disattivati, Nothing = tutti</param>
'''' <returns>Lista di dipendenti filtrata</returns>
'Public Function GetDipendenti(Optional attivo As Boolean? = Nothing) As List(Of Dipendente)
' Dim lista As New List(Of Dipendente)
' ' QUERY BASE
' Dim sql As String = "SELECT ID, Nome, Cognome, DataNascita, Telefono, Email, DataAssunzione, Attivo FROM Dipendenti"
' Dim conditions As New List(Of String)
' ' ⚠️ GESTISCI I 3 CASI (Attivi, Disattivati, Tutti)
' If attivo.HasValue Then
' If attivo.Value = True Then
' conditions.Add("Attivo = 1") ' Solo Attivi
' Else
' conditions.Add("Attivo = 0") ' Solo Disattivati
' End If
' ' Se attivo = Nothing, non aggiungo condizioni → Tutti
' End If
' ' AGGIUNGI WHERE SE CI SONO CONDIZIONI
' If conditions.Count > 0 Then
' sql &= " WHERE " & String.Join(" AND ", conditions)
' End If
' sql &= " ORDER BY Cognome, Nome;"
' Using reader = db.ExecuteReader(sql)
' While reader.Read()
' Dim dip As New Dipendente(
' nome:=reader.GetString(1),
' cognome:=reader.GetString(2),
' dataNascita:=If(reader.IsDBNull(3), New Date(1900, 1, 1), Date.Parse(reader.GetString(3))),
' telefono:=If(reader.IsDBNull(4), "", reader.GetString(4)),
' email:=If(reader.IsDBNull(5), "", reader.GetString(5)),
' dataAssunzione:=If(reader.IsDBNull(6), New Date(1900, 1, 1), Date.Parse(reader.GetString(6))),
' attivo:=(If(reader.IsDBNull(7), 0, reader.GetInt32(7)) = 1)
' )
' ' Imposta l'ID separatamente (è auto-generato dal DB)
' dip.ID = reader.GetInt32(0)
' lista.Add(dip)
' End While
' End Using
' Return lista
'End Function
''' <summary>
''' Restituisce tutti i dipendenti con filtro per stato attivo e ricerca per nome/cognome
''' </summary>
@@ -870,25 +820,56 @@ Public Class GestioneDipendenti
End Function
''' <summary>
''' Controlla se un dipendente ha già un turno assegnato oggi
''' Popola le liste dipendenti (Disponibili e Assegnati) dentro un oggetto Fascia
''' </summary>
Private Function HasTurnoOggi(dipendenteID As Integer, data As Date, ruoloID As Integer) As Boolean
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
cmd.CommandText = "
SELECT COUNT(*)
FROM Turni
WHERE DipendenteID = @dip
AND Data = @data
AND RuoloID = @ruoloID
Public Sub PopolaDipendentiFascia(fascia As Fascia, dataRiferimento As Date)
If fascia Is Nothing Then Return
' 1. Recupera disponibili (esclude assenze e chi non ha il ruolo)
fascia.DipentiDisponibili = GetDipendentiDisponibiliPerFascia(fascia.Ruolo.ID, dataRiferimento, fascia.FasciaOraria.ID)
' 2. Recupera già assegnati (da tabella Turni)
fascia.DipendentiAssegnati = GetDipendentiAssegnatiFascia(fascia.Ruolo.ID, dataRiferimento, fascia.FasciaOraria.ID)
End Sub
''' <summary>
''' Recupera i dipendenti già assegnati a questa fascia in questa data
''' </summary>
''' <param name="ruoloID"></param>
''' <param name="data"></param>
''' <param name="fasciaID"></param>
''' <returns></returns>
Public Function GetDipendentiAssegnatiFascia(ruoloID As Integer, data As Date, fasciaID As Integer) As List(Of Dipendente)
Dim lista As New List(Of Dipendente)
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
cmd.CommandText = "
SELECT d.ID, d.Nome, d.Cognome
FROM Turni t
INNER JOIN Dipendenti d ON t.DipendenteID = d.ID
WHERE t.RuoloID = @ruolo
AND t.FasciaID = @fascia
AND t.Data = @data
"
cmd.Parameters.AddWithValue("@dip", dipendenteID)
cmd.Parameters.AddWithValue("@data", data.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@ruoloID", ruoloID)
Return CInt(cmd.ExecuteScalar()) > 0
cmd.Parameters.AddWithValue("@ruolo", ruoloID)
cmd.Parameters.AddWithValue("@fascia", fasciaID)
cmd.Parameters.AddWithValue("@data", data.ToString("yyyy-MM-dd"))
Using reader = cmd.ExecuteReader()
While reader.Read()
lista.Add(New Dipendente With {
.ID = reader.GetInt32(0),
.Nome = reader.GetString(1),
.Cognome = reader.GetString(2)
})
End While
End Using
End Using
End Function
End Using
Return lista
End Function
End Class
' Classe di supporto
@@ -899,7 +880,7 @@ Public Class Dipendente
Public Property DataNascita As Date
Public Property Telefono As String
Public Property Email As String
Public Property DataAssunzione As String
Public Property DataAssunzione As Date
Public Property Attivo As Boolean
' Costruttore completo
Public Sub New()
@@ -955,6 +936,9 @@ Public Class Dipendente
Public Function GetAssenze(dataInizio As Date, dataFine As Date) As List(Of Assenza)
Return Gestionale.gestioneAssenze.GetAssenzeDipendente(ID, dataInizio, dataFine)
End Function
'Public Function GetAssenze() As Integer
' Return Gestionale.gestioneAssenze.GetAssenzeDipendente(ID)
'End Function
Public Sub SetAssenza(assenza As Assenza)
Gestionale.gestioneAssenze.SalvaAssenza(assenza)

View File

@@ -7,15 +7,15 @@ Public Class GestioneFasceLavoro
db = database
End Sub
Public Function GetOrari_Fasce() As List(Of Orari_fascia)
Dim lista As New List(Of Orari_fascia)
Public Function GetOrari_Fasce() As List(Of FasciaOraria)
Dim lista As New List(Of FasciaOraria)
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
cmd.CommandText = "SELECT ID, Nome, OraInizio, OraFine FROM Fasce ORDER BY ID;"
Using reader = cmd.ExecuteReader()
While reader.Read()
lista.Add(New Orari_fascia With {
lista.Add(New FasciaOraria With {
.ID = reader.GetInt32(0),
.Nome = reader.GetString(1),
.OraInizio = reader.GetString(2),
@@ -28,7 +28,7 @@ Public Class GestioneFasceLavoro
Return lista
End Function
Public Function GetOrario_Fascia(id As Integer) As Orari_fascia
Public Function GetOrario_Fascia(id As Integer) As FasciaOraria
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
@@ -44,7 +44,7 @@ Public Class GestioneFasceLavoro
Using reader = cmd.ExecuteReader()
If reader.Read() Then
Return New Orari_fascia With {
Return New FasciaOraria With {
.ID = reader.GetInt32(0),
.Nome = reader.GetString(1),
.OraInizio = reader.GetString(2),
@@ -59,7 +59,26 @@ Public Class GestioneFasceLavoro
Return Nothing
End Function
' ✅ CONTROLLA SE DUE FASCE SI SOVRAPPONGONO
Public Function FasceSiSovrappongono(fascia1 As Fascia, fascia2 As Fascia) As Boolean
Dim inizio1 As TimeSpan
Dim fine1 As TimeSpan
Dim inizio2 As TimeSpan
Dim fine2 As TimeSpan
If Not TimeSpan.TryParse(fascia1.FasciaOraria.OraInizio, inizio1) Then Return False
If Not TimeSpan.TryParse(fascia1.FasciaOraria.OraFine, fine1) Then Return False
If Not TimeSpan.TryParse(fascia2.FasciaOraria.OraInizio, inizio2) Then Return False
If Not TimeSpan.TryParse(fascia2.FasciaOraria.OraFine, fine2) Then Return False
' Gestione mezzanotte
If fine1 < inizio1 Then fine1 = fine1.Add(New TimeSpan(24, 0, 0))
If fine2 < inizio2 Then fine2 = fine2.Add(New TimeSpan(24, 0, 0))
' ✅ LOGICA SOVRAPPOSIZIONE: due intervalli si sovrappongono se...
' inizio1 < fine2 AND inizio2 < fine1
Return inizio1 < fine2 AndAlso inizio2 < fine1
End Function
Public Function EliminaFascia(fasciaID As Integer) As Boolean
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
@@ -86,7 +105,7 @@ Public Class GestioneFasceLavoro
End Using
End Using
End Function
Public Sub SalvaFascia(f As Orari_fascia)
Public Sub SalvaFascia(f As FasciaOraria)
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
cmd.CommandText = "
@@ -129,7 +148,7 @@ Public Class GestioneFasceLavoro
Dim o As New Fascia With {
.Ruolo = ruolo,
.FasciaOraria = New Orari_fascia With {
.FasciaOraria = New FasciaOraria With {
.ID = reader.GetInt32(0),
.Nome = reader.GetString(1),
.OraInizio = If(reader.IsDBNull(2), "", reader.GetString(2)),
@@ -150,8 +169,34 @@ Public Class GestioneFasceLavoro
Return lista
End Function
Public Function GetFasciaById(fasciaID As Integer) As Fascia
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
cmd.CommandText = "
SELECT ID, Nome, OraInizio, OraFine
FROM Fasce
WHERE ID = @id"
cmd.Parameters.AddWithValue("@id", fasciaID)
Using reader = cmd.ExecuteReader()
If reader.Read() Then
Return New Fascia With {
.ID = reader.GetInt32(0),
.FasciaOraria = New FasciaOraria With {
.ID = reader.GetInt32(0),
.Nome = reader.GetString(1),
.OraInizio = If(reader.IsDBNull(2), "", reader.GetString(2)),
.OraFine = If(reader.IsDBNull(3), "", reader.GetString(3))
}
}
End If
End Using
End Using
End Using
Return Nothing
End Function
End Class
Public Class Orari_fascia
Public Class FasciaOraria
Public Property ID As Integer
Public Property Nome As String
Public Property OraInizio As String
@@ -165,4 +210,12 @@ Public Class Orari_fascia
Public Overloads Function ToString() As String
Return $"{Nome}: {OraInizio} - {OraFine}"
End Function
End Class
' ✅ CLASSE PER RESTITUIRE DETTAGLI CONFLITTO DB
Public Class ConflittoInfo
Public Property HaConflitto As Boolean = False
Public Property HaSovrapposizione As Boolean = False
Public Property TurnoConflitto As Turno
Public Property FasciaConflitto As Fascia
Public Property Messaggio As String
End Class

View File

@@ -36,7 +36,7 @@ Public Class GestioneOrari_FasceLavoro
.ID = reader.GetInt32(1),
.Nome = reader.GetString(2)
},
.FasciaOraria = New Orari_fascia With {
.FasciaOraria = New FasciaOraria With {
.ID = reader.GetInt32(3),
.Nome = reader.GetString(4),
.OraInizio = reader.GetString(5),
@@ -56,49 +56,78 @@ Public Class GestioneOrari_FasceLavoro
Return lista
End Function
''' <summary>
''' Restituisce una Fascia completa dato l'ID
''' </summary>
'Public Function GetFasciaPerID(fasciaID As Integer) As Fascia
' Dim result As Fascia = Nothing
' Using conn = db.GetConnection()
' Using cmd = conn.CreateCommand()
' cmd.CommandText = "
' SELECT rt.ID,
' rt.RuoloID, r.Nome AS RuoloNome,
' rt.FasciaID, f.Nome AS FasciaNome, f.OraInizio, f.OraFine,
' rt.PersoneNecessarie, rt.GiornoSettimana
' FROM OrariFasce rt
' INNER JOIN Ruoli r ON rt.RuoloID = r.ID
' INNER JOIN Fasce f ON rt.FasciaID = f.ID
' WHERE rt.ID = @id
' "
' cmd.Parameters.AddWithValue("@id", fasciaID)
' Using reader = cmd.ExecuteReader()
' If reader.Read() Then
' result = New Fascia With {
' .ID = reader.GetInt32(0),
' .Ruolo = New Ruolo With {
' .ID = reader.GetInt32(1),
' .Nome = reader.GetString(2)
' },
' .FasciaOraria = New FasciaOraria With {
' .ID = reader.GetInt32(3),
' .Nome = reader.GetString(4),
' .OraInizio = reader.GetString(5),
' .OraFine = reader.GetString(6)
' },
' .PersoneNecessarie = reader.GetInt32(7),
' .GiornoSettimana = If(reader.IsDBNull(8), -1, reader.GetInt32(8))
' }
' End If
' End Using
' End Using
' End Using
' Return result
'End Function
Public Function GetFasciaPerID(fasciaID As Integer) As Fascia
Dim result As Fascia = Nothing
Debug.WriteLine($"[GetFasciaPerID] ID={fasciaID}")
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
cmd.CommandText = "
SELECT rt.ID,
rt.RuoloID, r.Nome AS RuoloNome,
rt.FasciaID, f.Nome AS FasciaNome, f.OraInizio, f.OraFine,
rt.PersoneNecessarie, rt.GiornoSettimana
FROM OrariFasce rt
INNER JOIN Ruoli r ON rt.RuoloID = r.ID
INNER JOIN Fasce f ON rt.FasciaID = f.ID
WHERE rt.ID = @id
SELECT f.ID, f.OraInizio, f.OraFine, f.Nome
FROM Fasce f
WHERE f.ID = @id
"
cmd.Parameters.AddWithValue("@id", fasciaID)
Using reader = cmd.ExecuteReader()
If reader.Read() Then
result = New Fascia With {
.ID = reader.GetInt32(0),
.Ruolo = New Ruolo With {
.ID = reader.GetInt32(1),
.Nome = reader.GetString(2)
},
.FasciaOraria = New Orari_fascia With {
.ID = reader.GetInt32(3),
.Nome = reader.GetString(4),
.OraInizio = reader.GetString(5),
.OraFine = reader.GetString(6)
},
.PersoneNecessarie = reader.GetInt32(7),
.GiornoSettimana = If(reader.IsDBNull(8), -1, reader.GetInt32(8))
Dim fascia As New Fascia With {
.FasciaOraria = New FasciaOraria With {
.ID = reader.GetInt32(0),
.OraInizio = reader.GetString(1),
.OraFine = reader.GetString(2),
.Nome = reader.GetString(3)
}
}
Debug.WriteLine($"[GetFasciaPerID] Trovata: {fascia.FasciaOraria.OraInizio}-{fascia.FasciaOraria.OraFine}")
Return fascia
End If
End Using
End Using
End Using
Return result
Debug.WriteLine($"[GetFasciaPerID] NON trovata ID={fasciaID}")
Return Nothing
End Function
''' <summary>
@@ -133,7 +162,7 @@ Public Class GestioneOrari_FasceLavoro
.ID = reader.GetInt32(1),
.Nome = reader.GetString(2)
},
.FasciaOraria = New Orari_fascia With {
.FasciaOraria = New FasciaOraria With {
.ID = reader.GetInt32(3),
.Nome = reader.GetString(4),
.OraInizio = reader.GetString(5),
@@ -187,7 +216,7 @@ Public Class GestioneOrari_FasceLavoro
.ID = reader.GetInt32(1),
.Nome = reader.GetString(2)
},
.FasciaOraria = New Orari_fascia With {
.FasciaOraria = New FasciaOraria With {
.ID = reader.GetInt32(3),
.Nome = reader.GetString(4),
.OraInizio = reader.GetString(5),
@@ -205,6 +234,60 @@ Public Class GestioneOrari_FasceLavoro
Return lista
End Function
Public Function GetFasce_Complete(data As Date) As List(Of Fascia)
' 1. Recupera i requisiti (Fasce)
Dim listaFasce = GetFasce_PerGiorno(data.DayOfWeek)
' 2. Per ogni fascia, carica i dipendenti
For Each fascia In listaFasce
' Chiama il metodo che abbiamo aggiunto a GestioneDipendenti
Gestionale.gestioneDipendenti.PopolaDipendentiFascia(fascia, data)
Next
Return listaFasce
End Function
Public Function GetFasce_Complete(data As Date, ruoli As List(Of Ruolo)) As List(Of Fascia)
Debug.WriteLine($"🔵 GetFasce_Complete: Data={data:dd/MM/yyyy}, Ruoli={ruoli.Count}")
Dim tutteFasce As New List(Of Fascia)()
For Each ruolo In ruoli
' ✅ 1. CARICA LE FASCE DAL DATABASE
Dim fascePerRuolo = GetFasce_PerGiorno_Ruolo(data.DayOfWeek, ruolo.ID)
Debug.WriteLine($" 📋 Ruolo {ruolo.Nome}: {fascePerRuolo.Count} fasce")
For Each fascia In fascePerRuolo
fascia.Ruolo = ruolo
' ✅ 2. POPOLA DIPENDENTI DISPONIBILI
fascia.DipentiDisponibili = Gestionale.gestioneDipendenti.GetDipendentiDisponibiliPerFascia(
ruolo.ID, data, fascia.FasciaOraria.ID)
' ✅ 3. RECUPERA TURNI SALVATI DAL DATABASE (COME IN FASCIAROWCONTROL)
Dim turniSalvati = Gestionale.gestioneTurni.GetTurniPerFascia(data, ruolo.ID, fascia.FasciaOraria.ID)
Debug.WriteLine($" 📍 {fascia.FasciaNome}: {turniSalvati.Count} turni salvati")
' ✅ 4. POPOLA DIPENDENTI ASSEGNATI
fascia.DipendentiAssegnati = New List(Of Dipendente)()
For Each turno In turniSalvati
If turno.DipendenteID.HasValue AndAlso turno.DipendenteID.Value > 0 Then
Dim dip = fascia.DipentiDisponibili.FirstOrDefault(Function(d) d.ID = turno.DipendenteID.Value)
If dip IsNot Nothing Then
fascia.DipendentiAssegnati.Add(dip)
Debug.WriteLine($" 👤 Slot {turno.OrdineVisualizzazione}: {dip.NomeCompleto}")
End If
End If
Next
Debug.WriteLine($" ✓ {fascia.FasciaNome} - Assegnati: {fascia.DipendentiAssegnati.Count}")
Next
tutteFasce.AddRange(fascePerRuolo)
Next
Debug.WriteLine($"✅ GetFasce_Complete: Totale {tutteFasce.Count} fasce")
Return tutteFasce
End Function
''' <summary>
''' Salva o aggiorna il numero di persone necessarie per un ruolo/fascia/giorno
@@ -335,10 +418,11 @@ End Class
Public Class Fascia
Public Property ID As Integer
Public Property Ruolo As Ruolo
Public Property FasciaOraria As Orari_fascia
Public Property FasciaOraria As FasciaOraria
Public Property PersoneNecessarie As Integer
Public Property GiornoSettimana As Integer ' 0=Domenica, 1=Lunedì... 6=Sabato, -1=Tutti i giorni
Public Property DipentiPresenti As List(Of Dipendente)
Public Property DipentiDisponibili As List(Of Dipendente)
Public Property DipendentiAssegnati As List(Of Dipendente)
Public ReadOnly Property RuoloNome As String
Get
Return If(Ruolo IsNot Nothing, Ruolo.Nome, "null")

View File

@@ -225,6 +225,121 @@ Public Class GestioneRuoli
End Using
End Sub
''' <summary>
''' Controlla se il dipendente ha conflitti di ruolo con sovrapposizione oraria
''' </summary>
Public Function ControllaConflittoRuoliConOrario(dipendenteID As Integer,
ruoloEsclusoID As Integer,
fasciaCorrente As Fascia,
data As Date,
Optional fasceRuoliDaEscludere As List(Of FasciaRuoloKey) = Nothing) As ConflittoResult
Dim result As New ConflittoResult()
Try
Dim dipendente = Gestionale.gestioneDipendenti.GetDipendente_ID(dipendenteID)
Dim nomeDipendente As String = If(dipendente IsNot Nothing, dipendente.NomeCompleto, $"ID {dipendenteID}")
' ✅ 1. SE HA 1 SOLO RUOLO, NON PUÒ AVERE CONFLITTI CON ALTRI RUOLI
Dim ruoliDipendente = Gestionale.gestioneRuoli.GetRuoliDipendente(dipendenteID)
If ruoliDipendente.Count <= 1 Then
Return result
End If
' ✅ 2. RECUPERA TURNI ESISTENTI
Dim turniEsistenti = Gestionale.gestioneTurni.GetTurniDipendente(dipendenteID, data, data)
If turniEsistenti.Count = 0 Then Return result
If fasciaCorrente Is Nothing OrElse fasciaCorrente.FasciaOraria Is Nothing Then Return result
Debug.WriteLine($"[ConflittoRuoli] {nomeDipendente} ha {ruoliDipendente.Count} ruoli")
Debug.WriteLine($"[ConflittoRuoli] Turni trovati: {turniEsistenti.Count}")
If fasceRuoliDaEscludere IsNot Nothing Then
Debug.WriteLine($"[ConflittoRuoli] Da escludere (UI): {String.Join(",", fasceRuoliDaEscludere.Select(Function(x) $"F{x.FasciaID}+R{x.RuoloID}"))}")
End If
' ✅ 3. ANALIZZA OGNI TURNO
For Each turno In turniEsistenti
' ✅ SALTA SE FASCIA+RUOLO È NELLA TABELLA CORRENTE (GESTITO DA UI)
If fasceRuoliDaEscludere IsNot Nothing AndAlso
fasceRuoliDaEscludere.Any(Function(x) x.FasciaID = turno.FasciaID AndAlso x.RuoloID = turno.RuoloID) Then
Debug.WriteLine($"[ConflittoRuoli] ✅ SKIP: Fascia {turno.FasciaID} + Ruolo {turno.RuoloID} è nella tabella (gestito da UI)")
Continue For
End If
' ✅ STESSA FASCIA + STESSO RUOLO → SKIP (multi-slot consentito)
If turno.FasciaID = fasciaCorrente.FasciaOraria.ID AndAlso turno.RuoloID = ruoloEsclusoID Then
Debug.WriteLine($"[ConflittoRuoli] ✅ SKIP: Stessa fascia + stesso ruolo (multi-slot)")
Continue For
End If
' ✅ STESSA FASCIA + RUOLO DIVERSO → CONFLITTO ROSSO
If turno.FasciaID = fasciaCorrente.FasciaOraria.ID AndAlso turno.RuoloID <> ruoloEsclusoID Then
Dim fasciaTurno = Gestionale.gestioneFasce.GetFasciaById(turno.FasciaID)
Dim ruolo = Gestionale.gestioneRuoli.GetRuolo(turno.RuoloID)
Dim ruoloNome = If(ruolo IsNot Nothing, ruolo.Nome, $"ID {turno.RuoloID}")
result.HaConflitto = True
result.HaSovrapposizione = True
result.Messaggio = $"⛔ {nomeDipendente} è già assegnato in:{vbCrLf}{vbCrLf}" &
$"🏢 Ruolo: {ruoloNome}{vbCrLf}" &
$"⏰ Orario: {fasciaTurno.FasciaOraria.OraInizio} - {fasciaTurno.FasciaOraria.OraFine}{vbCrLf}{vbCrLf}" &
$"Stessa fascia oraria ma ruolo diverso."
Return result
End If
' ✅ FASCIA DIVERSA + RUOLO DIVERSO → CONTROLLA SOVRAPPOSIZIONE
If turno.RuoloID <> ruoloEsclusoID Then
Dim fasciaTurno = Gestionale.gestioneFasce.GetFasciaById(turno.FasciaID)
If fasciaTurno IsNot Nothing AndAlso fasciaTurno.FasciaOraria IsNot Nothing Then
Dim ruolo = Gestionale.gestioneRuoli.GetRuolo(turno.RuoloID)
Dim ruoloNome = If(ruolo IsNot Nothing, ruolo.Nome, $"ID {turno.RuoloID}")
Dim sovrapposto As Boolean = Gestionale.gestioneFasce.FasceSiSovrappongono(fasciaCorrente, fasciaTurno)
If sovrapposto Then
result.HaConflitto = True
result.HaSovrapposizione = True
result.Messaggio = $"⛔ {nomeDipendente} è già assegnato in:{vbCrLf}{vbCrLf}" &
$"🏢 Ruolo: {ruoloNome}{vbCrLf}" &
$"⏰ Orario: {fasciaTurno.FasciaOraria.OraInizio} - {fasciaTurno.FasciaOraria.OraFine}{vbCrLf}{vbCrLf}" &
$"Le fasce orarie si sovrappongono."
Return result
Else
result.HaConflitto = True
result.HaSovrapposizione = False
result.Messaggio = $"⚠️ {nomeDipendente} ha già un turno in:{vbCrLf}" &
$"🏢 Ruolo: {ruoloNome}{vbCrLf}" &
$"⏰ Orario: {fasciaTurno.FasciaOraria.OraInizio} - {fasciaTurno.FasciaOraria.OraFine}{vbCrLf}{vbCrLf}" &
$"Non c'è sovrapposizione oraria."
End If
End If
End If
Next
Catch ex As Exception
Debug.WriteLine($"[ERRORE] ControllaConflittoRuoliConOrario: {ex.Message}")
End Try
Return result
End Function
''' <summary>
''' Calcola le ore di una fascia
''' </summary>
Private Function CalcolaOreFascia(fascia As Fascia) As Double
Dim inizio As TimeSpan
Dim fine As TimeSpan
If Not TimeSpan.TryParse(fascia.FasciaOraria.OraInizio, inizio) Then Return 0.0
If Not TimeSpan.TryParse(fascia.FasciaOraria.OraFine, fine) Then Return 0.0
Dim ore As Double = (fine - inizio).TotalHours
If ore < 0 Then ore += 24 ' Gestione mezzanotte
Return ore
End Function
End Class
' Classe di supporto per rappresentare un ruolo
@@ -232,7 +347,23 @@ Public Class Ruolo
Public Property ID As Integer
Public Property Nome As String
Public Property Descrizione As String
Public Property Colore As Color
Public Overloads Function ToString() As String
Return $"ID:{ID} nome:{Nome}"
End Function
End Class
' ✅ NUOVA CLASSE PER IDENTIFICARE UNIVOCAMENTE UNA FASCIA+RUOLO
Public Class FasciaRuoloKey
Public Property FasciaID As Integer
Public Property RuoloID As Integer
Public Overrides Function GetHashCode() As Integer
Return FasciaID * 1000 + RuoloID
End Function
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Nothing Then Return False
Dim other = CType(obj, FasciaRuoloKey)
Return Me.FasciaID = other.FasciaID AndAlso Me.RuoloID = other.RuoloID
End Function
End Class

View File

@@ -10,6 +10,7 @@ Public Class GestioneTurni
' ⚠️ SALVA UN SINGOLO TURNO (INSERT O UPDATE)
Public Sub SalvaTurno(turno As Turno)
Using conn = db.GetConnection()
conn.Open()
Using cmd = conn.CreateCommand()
If turno.ID > 0 Then
' UPDATE
@@ -52,37 +53,372 @@ Public Class GestioneTurni
End Using
End Sub
' ✅ NUOVO: SALVA TUTTI I TURNI DI UN PERIODO (DELETE + INSERT)
Public Function SalvaTurniPeriodo(turni As List(Of TurnoDaSalvare),
ruoloID As Integer,
dataInizio As Date,
dataFine As Date) As Integer
Dim salvati As Integer = 0
Using conn = db.GetConnection()
conn.Open()
Using trans = conn.BeginTransaction()
Try
' 1. ELIMINA TUTTI I TURNI ESISTENTI NEL PERIODO
Using cmd As New SqliteCommand("
DELETE FROM Turni
WHERE Data >= @dataInizio
AND Data <= @dataFine
AND RuoloID = @ruoloID
", conn, trans)
cmd.Parameters.AddWithValue("@dataInizio", dataInizio.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@dataFine", dataFine.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@ruoloID", ruoloID)
cmd.ExecuteNonQuery()
End Using
' 2. INSERISCI I NUOVI TURNI
For Each turno In turni
Using cmd As New SqliteCommand("
INSERT INTO Turni
(DipendenteID, RuoloID, FasciaID, Data, Stato, OrdineVisualizzazione, UtenteInserimento, DataInserimento)
VALUES
(@dip, @ruolo, @fascia, @data, @stato, @ordine, @utente, CURRENT_TIMESTAMP)
", conn, trans)
cmd.Parameters.AddWithValue("@dip", turno.DipendenteID)
cmd.Parameters.AddWithValue("@ruolo", ruoloID)
cmd.Parameters.AddWithValue("@fascia", turno.FasciaID)
cmd.Parameters.AddWithValue("@data", turno.Data.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@stato", "Assegnato")
cmd.Parameters.AddWithValue("@ordine", turno.Slot)
cmd.Parameters.AddWithValue("@utente", Environment.UserName)
cmd.ExecuteNonQuery()
salvati += 1
End Using
Next
trans.Commit()
Catch ex As Exception
trans.Rollback()
Throw New Exception($"Errore salvataggio turni: {ex.Message}", ex)
End Try
End Using
End Using
Return salvati
End Function
' ⚠️ SALVA TUTTI I TURNI DI UNA GIORNATA (DELETE + INSERT)
Public Sub SalvaTurniGiornata(data As Date, ruoloID As Integer, turni As List(Of Turno))
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
' 1. ELIMINA TURNI ESISTENTI PER QUELLA DATA/RUOLO
cmd.CommandText = "DELETE FROM Turni WHERE Data = @data AND RuoloID = @ruolo"
cmd.Parameters.AddWithValue("@data", data.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@ruolo", ruoloID)
conn.Open()
Using trans = conn.BeginTransaction()
Try
' 1. ELIMINA TURNI ESISTENTI PER QUELLA DATA/RUOLO
Using cmd As New SqliteCommand("
DELETE FROM Turni
WHERE Data = @data AND RuoloID = @ruolo
", conn, trans)
cmd.Parameters.AddWithValue("@data", data.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@ruolo", ruoloID)
cmd.ExecuteNonQuery()
End Using
' 2. INSERISCI NUOVI TURNI
For Each turno In turni
Using cmd As New SqliteCommand("
INSERT INTO Turni
(DipendenteID, RuoloID, FasciaID, Data, Stato, OrdineVisualizzazione, Note, UtenteInserimento, DataInserimento)
VALUES
(@dip, @ruolo, @fascia, @data, @stato, @ordine, @note, @utente, CURRENT_TIMESTAMP)
", conn, trans)
cmd.Parameters.AddWithValue("@dip", If(turno.DipendenteID.HasValue, turno.DipendenteID.Value, DBNull.Value))
cmd.Parameters.AddWithValue("@ruolo", turno.RuoloID)
cmd.Parameters.AddWithValue("@fascia", turno.FasciaID)
cmd.Parameters.AddWithValue("@data", turno.Data.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@stato", If(String.IsNullOrEmpty(turno.Stato), "Assegnato", turno.Stato))
cmd.Parameters.AddWithValue("@ordine", turno.OrdineVisualizzazione)
cmd.Parameters.AddWithValue("@note", If(String.IsNullOrEmpty(turno.Note), DBNull.Value, turno.Note))
cmd.Parameters.AddWithValue("@utente", Environment.UserName)
cmd.ExecuteNonQuery()
End Using
Next
trans.Commit()
Catch ex As Exception
trans.Rollback()
Throw
End Try
End Using
End Using
End Sub
' ✅ NEL TUO GESTIONALETURNI.VB
Public Function UpdateTurniPeriodo(turni As List(Of Turno),
ruoloID As Integer,
dataInizio As Date,
dataFine As Date) As Integer
Dim salvati As Integer = 0
Using conn = db.GetConnection()
conn.Open()
Using trans = conn.BeginTransaction()
Try
' 1. ELIMINA TUTTI I TURNI ESISTENTI NEL PERIODO
Using cmd As New SqliteCommand("
DELETE FROM Turni
WHERE Data >= @dataInizio
AND Data <= @dataFine
AND RuoloID = @ruoloID
", conn, trans)
cmd.Parameters.AddWithValue("@dataInizio", dataInizio.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@dataFine", dataFine.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@ruoloID", ruoloID)
cmd.ExecuteNonQuery()
End Using
' 2. INSERISCI I NUOVI TURNI
For Each turno In turni
Using cmd As New SqliteCommand("
INSERT INTO Turni
(DipendenteID, RuoloID, FasciaID, Data, Stato, OrdineVisualizzazione, UtenteInserimento, DataInserimento)
VALUES
(@dip, @ruolo, @fascia, @data, @stato, @ordine, @utente, CURRENT_TIMESTAMP)
", conn, trans)
cmd.Parameters.AddWithValue("@dip", turno.DipendenteID)
cmd.Parameters.AddWithValue("@ruolo", turno.RuoloID)
cmd.Parameters.AddWithValue("@fascia", turno.FasciaID)
cmd.Parameters.AddWithValue("@data", turno.Data.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@stato", "Assegnato")
cmd.Parameters.AddWithValue("@ordine", turno.OrdineVisualizzazione)
cmd.Parameters.AddWithValue("@utente", Environment.UserName)
cmd.ExecuteNonQuery()
salvati += 1
End Using
Next
trans.Commit()
Catch ex As Exception
trans.Rollback()
Throw New Exception($"Errore salvataggio turni: {ex.Message}", ex)
End Try
End Using
End Using
Return salvati
End Function
Public Function SalvaTurniPeriodox(turni As List(Of Turno),
ruoloID As Integer,
dataInizio As Date,
dataFine As Date) As Integer
Dim salvati As Integer = 0
Dim aggiornati As Integer = 0
Using conn = db.GetConnection()
conn.Open()
Using trans = conn.BeginTransaction()
Try
' ✅ 1. ELIMINA SOLO I TURNI NON PRESENTI NELLA NUOVA LISTA
' (quelli che sono stati rimossi dall'utente)
Using cmd As New SqliteCommand("
DELETE FROM Turni
WHERE Data >= @dataInizio
AND Data <= @dataFine
AND RuoloID = @ruoloID
AND (DipendenteID, FasciaID, Data) NOT IN (
SELECT @dip, @fascia, @data
)
", conn, trans)
' ← Questo è complesso, meglio la versione semplice sotto
End Using
' ✅ VERSIONE SEMPLICE: Per ogni turno, UPDATE o INSERT
For Each turno In turni
If turno.DipendenteID > 0 Then
' ✅ CONTROLLA SE ESISTE GIÀ
Using cmdCheck As New SqliteCommand("
SELECT ID FROM Turni
WHERE DipendenteID = @dip
AND FasciaID = @fascia
AND Data = @data
AND RuoloID = @ruolo
", conn, trans)
cmdCheck.Parameters.AddWithValue("@dip", turno.DipendenteID)
cmdCheck.Parameters.AddWithValue("@fascia", turno.FasciaID)
cmdCheck.Parameters.AddWithValue("@data", turno.Data.ToString("yyyy-MM-dd"))
cmdCheck.Parameters.AddWithValue("@ruolo", turno.RuoloID)
Dim existingID = cmdCheck.ExecuteScalar()
If existingID IsNot Nothing Then
' ✅ UPDATE
Using cmd As New SqliteCommand("
UPDATE Turni
SET Stato = @stato,
OrdineVisualizzazione = @ordine,
UtenteModifica = @utente,
DataModifica = CURRENT_TIMESTAMP
WHERE ID = @id
", conn, trans)
cmd.Parameters.AddWithValue("@stato", "Assegnato")
cmd.Parameters.AddWithValue("@ordine", turno.OrdineVisualizzazione)
cmd.Parameters.AddWithValue("@utente", Environment.UserName)
cmd.Parameters.AddWithValue("@id", existingID)
cmd.ExecuteNonQuery()
End Using
aggiornati += 1
Else
' ✅ INSERT
Using cmd As New SqliteCommand("
INSERT INTO Turni
(DipendenteID, RuoloID, FasciaID, Data, Stato, OrdineVisualizzazione, UtenteInserimento, DataInserimento)
VALUES
(@dip, @ruolo, @fascia, @data, @stato, @ordine, @utente, CURRENT_TIMESTAMP)
", conn, trans)
cmd.Parameters.AddWithValue("@dip", turno.DipendenteID)
cmd.Parameters.AddWithValue("@ruolo", turno.RuoloID)
cmd.Parameters.AddWithValue("@fascia", turno.FasciaID)
cmd.Parameters.AddWithValue("@data", turno.Data.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@stato", "Assegnato")
cmd.Parameters.AddWithValue("@ordine", turno.OrdineVisualizzazione)
cmd.Parameters.AddWithValue("@utente", Environment.UserName)
cmd.ExecuteNonQuery()
End Using
salvati += 1
End If
End Using
End If
Next
' ✅ 2. ELIMINA I TURNI NON PRESENTI NELLA NUOVA LISTA
Using cmd As New SqliteCommand("
DELETE FROM Turni
WHERE Data >= @dataInizio
AND Data <= @dataFine
AND RuoloID = @ruoloID
AND DipendenteID > 0
", conn, trans)
cmd.Parameters.AddWithValue("@dataInizio", dataInizio.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@dataFine", dataFine.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@ruoloID", ruoloID)
cmd.ExecuteNonQuery()
End Using
trans.Commit()
Debug.WriteLine($"[Salvataggio] ✅ {salvati} nuovi, {aggiornati} aggiornati")
Catch ex As Exception
trans.Rollback()
Debug.WriteLine($"[Salvataggio] ❌ Errore: {ex.Message}")
Throw New Exception($"Errore salvataggio turni: {ex.Message}", ex)
End Try
End Using
End Using
Return salvati + aggiornati
End Function
Public Function SalvaTurniPeriodo(turni As List(Of Turno),
ruoloID As Integer,
dataInizio As Date,
dataFine As Date) As Integer
Dim salvati As Integer = 0
Debug.WriteLine($"========================================")
Debug.WriteLine($"[SalvaTurniPeriodo] INIZIO")
Debug.WriteLine($"[SalvaTurniPeriodo] ruoloID: {ruoloID}")
Debug.WriteLine($"[SalvaTurniPeriodo] dataInizio: {dataInizio:dd/MM/yyyy}")
Debug.WriteLine($"[SalvaTurniPeriodo] dataFine: {dataFine:dd/MM/yyyy}")
Debug.WriteLine($"[SalvaTurniPeriodo] turni.Count: {turni.Count}")
Debug.WriteLine($"========================================")
Using conn = db.GetConnection()
conn.Open()
Using trans = conn.BeginTransaction()
Try
' ✅ 1. CONTROLLA QUANTI TURNI ESISTONO PRIMA DEL DELETE
Using cmdCheck As New SqliteCommand("SELECT COUNT(*) FROM Turni WHERE Data >= @dataInizio AND Data <= @dataFine AND RuoloID = @ruoloID", conn, trans)
cmdCheck.Parameters.AddWithValue("@dataInizio", dataInizio.ToString("yyyy-MM-dd"))
cmdCheck.Parameters.AddWithValue("@dataFine", dataFine.ToString("yyyy-MM-dd"))
cmdCheck.Parameters.AddWithValue("@ruoloID", ruoloID)
Dim countPrima = cmdCheck.ExecuteScalar()
Debug.WriteLine($"[SalvaTurniPeriodo] Turni esistenti PRIMA del DELETE: {countPrima}")
End Using
' ✅ 2. ELIMINA TUTTI I TURNI ESISTENTI NEL PERIODO
Using cmd As New SqliteCommand("
DELETE FROM Turni
WHERE Data >= @dataInizio
AND Data <= @dataFine
AND RuoloID = @ruoloID
", conn, trans)
cmd.Parameters.AddWithValue("@dataInizio", dataInizio.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@dataFine", dataFine.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@ruoloID", ruoloID)
Dim deleted = cmd.ExecuteNonQuery()
Debug.WriteLine($"[SalvaTurniPeriodo] Turni CANCELLATI: {deleted}")
End Using
' ✅ 3. INSERISCI I NUOVI TURNI
For Each turno In turni
If turno.DipendenteID > 0 Then
Using cmd As New SqliteCommand("
INSERT INTO Turni
(DipendenteID, RuoloID, FasciaID, Data, Stato, OrdineVisualizzazione, UtenteInserimento, DataInserimento)
VALUES
(@dip, @ruolo, @fascia, @data, @stato, @ordine, @utente, CURRENT_TIMESTAMP)
", conn, trans)
cmd.Parameters.AddWithValue("@dip", turno.DipendenteID)
cmd.Parameters.AddWithValue("@ruolo", turno.RuoloID)
cmd.Parameters.AddWithValue("@fascia", turno.FasciaID)
cmd.Parameters.AddWithValue("@data", turno.Data.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@stato", "Assegnato")
cmd.Parameters.AddWithValue("@ordine", turno.OrdineVisualizzazione)
cmd.Parameters.AddWithValue("@utente", Environment.UserName)
cmd.ExecuteNonQuery()
salvati += 1
End Using
End If
Next
Debug.WriteLine($"[SalvaTurniPeriodo] Turni INSERITI: {salvati}")
trans.Commit()
Catch ex As Exception
trans.Rollback()
Debug.WriteLine($"[SalvaTurniPeriodo] ❌ ERRORE: {ex.Message}")
Throw New Exception($"Errore salvataggio turni: {ex.Message}", ex)
End Try
End Using
End Using
Debug.WriteLine($"[SalvaTurniPeriodo] FINE - Totale salvati: {salvati}")
Debug.WriteLine($"========================================")
Return salvati
End Function
' ✅ METODO PER ELIMINARE TURNI NEL PERIODO
Public Sub EliminaTurniPeriodo(dataInizio As Date, dataFine As Date, ruoloID As Integer)
Using conn = db.GetConnection()
Using cmd As New SqliteCommand("
DELETE FROM Turni
WHERE Data >= @dataInizio
AND Data <= @dataFine
AND RuoloID = @ruoloID
", conn)
cmd.Parameters.AddWithValue("@dataInizio", dataInizio.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@dataFine", dataFine.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@ruoloID", ruoloID)
cmd.ExecuteNonQuery()
' 2. INSERISCI NUOVI TURNI
cmd.Parameters.Clear()
cmd.CommandText = "
INSERT INTO Turni
(DipendenteID, RuoloID, FasciaID, Data, Stato, OrdineVisualizzazione, Note, UtenteInserimento, DataInserimento)
VALUES
(@dip, @ruolo, @fascia, @data, @stato, @ordine, @note, @utente, CURRENT_TIMESTAMP)
"
For Each turno In turni
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("@dip", If(turno.DipendenteID.HasValue, turno.DipendenteID.Value, DBNull.Value))
cmd.Parameters.AddWithValue("@ruolo", turno.RuoloID)
cmd.Parameters.AddWithValue("@fascia", turno.FasciaID)
cmd.Parameters.AddWithValue("@data", turno.Data.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@stato", If(String.IsNullOrEmpty(turno.Stato), "Assegnato", turno.Stato))
cmd.Parameters.AddWithValue("@ordine", turno.OrdineVisualizzazione)
cmd.Parameters.AddWithValue("@note", If(String.IsNullOrEmpty(turno.Note), DBNull.Value, turno.Note))
cmd.Parameters.AddWithValue("@utente", Environment.UserName)
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub
@@ -93,7 +429,6 @@ Public Class GestioneTurni
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
' ⚠️ LEFT JOIN SU DIPENDENTI (PERMETTE SLOT VUOTI)
Dim sql As String = "
SELECT
t.ID,
@@ -135,7 +470,7 @@ Public Class GestioneTurni
.DipendenteID = If(reader.IsDBNull(1), Nothing, reader.GetInt32(1)),
.DipendenteCognome = If(reader.IsDBNull(2), "", reader.GetString(2)),
.DipendenteNome = If(reader.IsDBNull(3), "", reader.GetString(3)),
.ruoloID = reader.GetInt32(4),
.RuoloID = reader.GetInt32(4),
.RuoloNome = reader.GetString(5),
.FasciaID = reader.GetInt32(6),
.FasciaNome = reader.GetString(7),
@@ -160,9 +495,15 @@ Public Class GestioneTurni
End Function
' ⚠️ RECUPERA TURNI PER FASCIA SPECIFICA (PER POPOLARE COMBOBOX)
' ✅ RECUPERA TURNI PER FASCIA SPECIFICA (PER POPOLARE COMBOBOX)
Public Function GetTurniPerFascia(data As Date, ruoloID As Integer, fasciaID As Integer) As List(Of Turno)
Debug.WriteLine($"🔵 GetTurniPerFascia: Data={data:dd/MM}, Ruolo={ruoloID}, Fascia={fasciaID}")
Dim tutti = GetTurniPerGiorno(data, ruoloID)
Return tutti.Where(Function(t) t.FasciaID = fasciaID).OrderBy(Function(t) t.OrdineVisualizzazione).ToList()
Dim filtrati = tutti.Where(Function(t) t.FasciaID = fasciaID).OrderBy(Function(t) t.OrdineVisualizzazione).ToList()
Debug.WriteLine($" ✓ Trovati {filtrati.Count} turni")
Return filtrati
End Function
' ⚠️ CONTROLLA SE DIPENDENTE È GIÀ ASSEGNATO A QUELLA FASCIA
@@ -229,9 +570,398 @@ Public Class GestioneTurni
End Using
End Using
End Function
Public Function GetOreLavorateDaOggiIndietro(dipendenteID As Integer,
Optional dataRiferimento As Date? = Nothing) As Double
Dim totaleOre As Double = 0.0
' ✅ Se non specificata, usa oggi come data di taglio
If Not dataRiferimento.HasValue Then
dataRiferimento = Date.Today
End If
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
cmd.CommandText = "
SELECT COALESCE(SUM(
(strftime('%s', '1970-01-01 ' || F.OraFine) - strftime('%s', '1970-01-01 ' || F.OraInizio)) / 3600.0
), 0)
FROM Turni T
INNER JOIN Fasce F ON T.FasciaID = F.ID
WHERE T.DipendenteID = @dip
AND T.Data <= @dataTaglio -- ✅ Solo passato/oggi
AND T.Stato != 'Cancellato' -- ✅ Esclude annullati
AND T.Stato != 'Programmato' -- ✅ Esclude futuri non ancora lavorati
AND (strftime('%s', F.OraFine) - strftime('%s', F.OraInizio)) > 0"
cmd.Parameters.AddWithValue("@dip", dipendenteID)
cmd.Parameters.AddWithValue("@dataTaglio", dataRiferimento.Value.ToString("yyyy-MM-dd"))
Dim result = cmd.ExecuteScalar()
If result IsNot Nothing AndAlso Not DBNull.Value.Equals(result) Then
totaleOre = Convert.ToDouble(result)
End If
End Using
End Using
Return Math.Round(totaleOre, 2)
End Function
Public Function GetOreProgrammateDaOggiInAvanti(dipendenteID As Integer,
Optional dataRiferimento As Date? = Nothing) As Double
Dim totaleOre As Double = 0.0
' ✅ Se non specificata, usa oggi come data di taglio
If Not dataRiferimento.HasValue Then
dataRiferimento = Date.Today
End If
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
cmd.CommandText = "
SELECT COALESCE(SUM(
(strftime('%s', '1970-01-01 ' || F.OraFine) - strftime('%s', '1970-01-01 ' || F.OraInizio)) / 3600.0
), 0)
FROM Turni T
INNER JOIN Fasce F ON T.FasciaID = F.ID
WHERE T.DipendenteID = @dip
AND T.Data >= @dataTaglio -- ✅ Solo futuro/oggi
AND T.Stato != 'Cancellato' -- ✅ Esclude annullati
AND (strftime('%s', F.OraFine) - strftime('%s', F.OraInizio)) > 0"
cmd.Parameters.AddWithValue("@dip", dipendenteID)
cmd.Parameters.AddWithValue("@dataTaglio", dataRiferimento.Value.ToString("yyyy-MM-dd"))
Dim result = cmd.ExecuteScalar()
If result IsNot Nothing AndAlso Not DBNull.Value.Equals(result) Then
totaleOre = Convert.ToDouble(result)
End If
End Using
End Using
Return Math.Round(totaleOre, 2)
End Function
Public Function OreLavorateProgrammate(dipendenteID As Integer,
Optional dataRiferimento As Date? = Nothing) As Double
Return Gestionale.gestioneTurni.GetOreLavorateDaOggiIndietro(dipendenteID) + Gestionale.gestioneTurni.GetOreProgrammateDaOggiInAvanti(dipendenteID)
End Function
Public Class DettaglioTurno
Public Property Data As Date
Public Property Ruolo As String
Public Property Fascia As String
Public Property Ore As Double
End Class
Public Function GetDettaglioTurniDipendente(dipendenteID As Integer,
Optional dataInizio As Date? = Nothing,
Optional dataFine As Date? = Nothing) As List(Of DettaglioTurno)
Dim lista As New List(Of DettaglioTurno)
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
cmd.CommandText = "
SELECT
T.Data,
R.Nome as Ruolo,
F.Nome as Fascia,
(strftime('%s', '1970-01-01 ' || F.OraFine) - strftime('%s', '1970-01-01 ' || F.OraInizio)) / 3600.0 as Ore
FROM Turni T
INNER JOIN Fasce F ON T.FasciaID = F.ID
INNER JOIN Ruoli R ON T.RuoloID = R.ID
WHERE T.DipendenteID = @dip
AND T.Stato != 'Cancellato'
AND (@dataInizio IS NULL OR T.Data >= @dataInizio)
AND (@dataFine IS NULL OR T.Data <= @dataFine)
ORDER BY T.Data, F.OraInizio"
cmd.Parameters.AddWithValue("@dip", dipendenteID)
If dataInizio.HasValue Then
cmd.Parameters.AddWithValue("@dataInizio", dataInizio.Value.ToString("yyyy-MM-dd"))
Else
cmd.Parameters.AddWithValue("@dataInizio", DBNull.Value)
End If
If dataFine.HasValue Then
cmd.Parameters.AddWithValue("@dataFine", dataFine.Value.ToString("yyyy-MM-dd"))
Else
cmd.Parameters.AddWithValue("@dataFine", DBNull.Value)
End If
Using reader = cmd.ExecuteReader()
While reader.Read()
lista.Add(New DettaglioTurno With {
.Data = Date.Parse(reader.GetString("Data")),
.Ruolo = reader.GetString("Ruolo"),
.Fascia = reader.GetString("Fascia"),
.Ore = reader.GetDouble("Ore")
})
End While
End Using
End Using
End Using
Return lista
End Function
Public Function ControllaConflittiDipendente(dipendenteID As Integer,
data As Date,
fasciaOrariaID As Integer,
ruoloCorrenteID As Integer) As ConflittoInfo
Dim info As New ConflittoInfo()
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
' ✅ RECUPERA ORARI FASCIA CORRENTE
Dim fasciaCorrenteInizio As TimeSpan
Dim fasciaCorrenteFine As TimeSpan
Using cmdFascia As New SqliteCommand("SELECT OraInizio, OraFine FROM Fasce WHERE ID = @id", conn)
cmdFascia.Parameters.AddWithValue("@id", fasciaOrariaID)
Using reader = cmdFascia.ExecuteReader()
If reader.Read() Then
TimeSpan.TryParse(reader.GetString(0), fasciaCorrenteInizio)
TimeSpan.TryParse(reader.GetString(1), fasciaCorrenteFine)
End If
End Using
End Using
Debug.WriteLine($"🔍 Fascia corrente ID={fasciaOrariaID}: {fasciaCorrenteInizio:hh\:mm}-{fasciaCorrenteFine:hh\:mm}, RuoloID={ruoloCorrenteID}")
' ✅ RECUPERA TUTTI I TURNI DEL DIPENDENTE IN QUEL GIORNO
cmd.CommandText = "
SELECT T.FasciaID, T.RuoloID, R.Nome AS RuoloNome, F.OraInizio, F.OraFine
FROM Turni T
INNER JOIN Ruoli R ON T.RuoloID = R.ID
INNER JOIN Fasce F ON T.FasciaID = F.ID
WHERE T.DipendenteID = @dip AND T.Data = @data
ORDER BY F.OraInizio
"
cmd.Parameters.AddWithValue("@dip", dipendenteID)
cmd.Parameters.AddWithValue("@data", data.ToString("yyyy-MM-dd"))
Using reader = cmd.ExecuteReader()
While reader.Read()
Dim turnoFasciaID = reader.GetInt32(0)
Dim turnoRuoloID = reader.GetInt32(1) ' ✅ NUOVO: Recupera RuoloID
Dim oraInizioStr = reader.GetString(3)
Dim oraFineStr = reader.GetString(4)
Dim ruoloNome = reader.GetString(2)
' ✅ PARSE ORARI TURNO ESISTENTE
Dim turnoInizio As TimeSpan
Dim turnoFine As TimeSpan
If Not TimeSpan.TryParse(oraInizioStr, turnoInizio) Then Continue While
If Not TimeSpan.TryParse(oraFineStr, turnoFine) Then Continue While
Debug.WriteLine($" 🔍 Confronto: {ruoloNome} (RuoloID={turnoRuoloID}) {turnoInizio:hh\:mm}-{turnoFine:hh\:mm} vs Corrente RuoloID={ruoloCorrenteID} {fasciaCorrenteInizio:hh\:mm}-{fasciaCorrenteFine:hh\:mm}")
' ✅ CONTROLLO 1: STESSO RUOLO + STESSA FASCIA → SKIP (PUÒ AVERE PIÙ SLOT)
If turnoRuoloID = ruoloCorrenteID AndAlso turnoFasciaID = fasciaOrariaID Then
Debug.WriteLine($" ✅ SKIP: Stesso ruolo + stessa fascia (multi-slot consentito)")
Continue While
End If
' ✅ CONTROLLA SOVRAPPOSIZIONE ORARIA
Dim sovrapposto As Boolean = (fasciaCorrenteInizio < turnoFine) AndAlso (turnoInizio < fasciaCorrenteFine)
If sovrapposto Then
' ❌ STESSA FASCIA ORARIA (QUALUNQUE RUOLO) → ROSSO + MSGBOX
info.HaConflitto = True
info.HaSovrapposizione = True
info.Messaggio = $"🏢 Ruolo: {ruoloNome}{vbCrLf}" &
$"⏰ Orario: {oraInizioStr} - {oraFineStr}{vbCrLf}{vbCrLf}" &
$"Le fasce orarie si sovrappongono."
info.RuoloConflitto = ruoloNome
info.FasciaConflittoID = turnoFasciaID
Debug.WriteLine($" ❌ SOVRAPPOSIZIONE TROVATA (ROSSO)!")
Return info ' ✅ ESCI SUBITO
Else
' ⚠️ STESSO GIORNO, FASCIA DIVERSA → GIALLO + TOOLTIP
info.HaConflitto = True
info.HaSovrapposizione = False
info.Messaggio = $"⚠️ Il dipendente ha già un turno in:{vbCrLf}" &
$"🏢 Ruolo: {ruoloNome}{vbCrLf}" &
$"⏰ Orario: {oraInizioStr} - {oraFineStr}{vbCrLf}{vbCrLf}" &
$"Non c'è sovrapposizione oraria."
Debug.WriteLine($" ⚠️ CONFLITTO GIALLO (NO SOVRAPPOSIZIONE)")
' ✅ NON ESCIRE, CONTINUA A CONTROLLARE ALTRI TURNI
End If
End While
End Using
End Using
End Using
Return info
End Function
' ✅ CLASSE PER INFORMAZIONI CONFLITTO
Public Class ConflittoInfo
Friend FasciaConflittoID As Integer
Public Property HaConflitto As Boolean = False
Public Property HaSovrapposizione As Boolean = False
Public Property Messaggio As String = ""
Public Property RuoloConflitto As String
Public Property OraInizioConflitto As String
Public Property OraFineConflitto As String
End Class
' ✅ METODO PER CONTROLLARE SOVRAPPOSIZIONE FASCE
Private Function FasceSiSovrappongono(fascia1 As Fascia, fascia2 As Fascia) As Boolean
Dim inizio1, fine1, inizio2, fine2 As TimeSpan
If Not TimeSpan.TryParse(fascia1.FasciaOraria.OraInizio, inizio1) Then Return False
If Not TimeSpan.TryParse(fascia1.FasciaOraria.OraFine, fine1) Then Return False
If Not TimeSpan.TryParse(fascia2.FasciaOraria.OraInizio, inizio2) Then Return False
If Not TimeSpan.TryParse(fascia2.FasciaOraria.OraFine, fine2) Then Return False
If fine1 < inizio1 Then fine1 = fine1.Add(New TimeSpan(24, 0, 0))
If fine2 < inizio2 Then fine2 = fine2.Add(New TimeSpan(24, 0, 0))
Return inizio1 < fine2 AndAlso inizio2 < fine1
End Function
Public Function GetTurniDipendente(dipendenteID As Integer, dataInizio As Date, dataFine As Date) As List(Of Turno)
Dim lista As New List(Of Turno)()
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
cmd.CommandText = "
SELECT ID, DipendenteID, RuoloID, FasciaID, Data, Stato
FROM Turni
WHERE DipendenteID = @dip
AND Data >= @inizio AND Data <= @fine
AND Stato != 'Cancellato'"
cmd.Parameters.AddWithValue("@dip", dipendenteID)
cmd.Parameters.AddWithValue("@inizio", dataInizio.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@fine", dataFine.ToString("yyyy-MM-dd"))
Using reader = cmd.ExecuteReader()
While reader.Read()
lista.Add(New Turno With {
.ID = reader.GetInt32(0),
.DipendenteID = reader.GetInt32(1),
.RuoloID = reader.GetInt32(2),
.FasciaID = reader.GetInt32(3),
.Data = Date.Parse(reader.GetString(4)),
.Stato = reader.GetString(5)
})
End While
End Using
End Using
End Using
Debug.WriteLine($"[GetTurniDipendente] Dip={dipendenteID}, Data={dataInizio:dd/MM}, Trovati={lista.Count}")
Return lista
End Function
' ✅ SALVA SELEZIONI DALLA UI (SelezioneTurno → Turno)
Public Sub SalvaSelezioni(selezioni As List(Of SelezioneTurno))
If selezioni Is Nothing OrElse selezioni.Count = 0 Then
Debug.WriteLine("⚠️ Nessuna selezione da salvare")
Return
End If
Debug.WriteLine($"💾 Salvataggio {selezioni.Count} turni dalla UI...")
Using conn = db.GetConnection()
conn.Open()
Using trans = conn.BeginTransaction()
Try
Dim turniPerDataRuolo = selezioni.GroupBy(Function(s) New With {s.Data, s.RuoloID})
For Each gruppo In turniPerDataRuolo
Dim data = gruppo.Key.Data
Dim ruoloID = gruppo.Key.RuoloID
Debug.WriteLine($" 📅 Data: {data:dd/MM}, Ruolo: {ruoloID}")
' ✅ ELIMINA TURNI ESISTENTI
Using cmd As New SqliteCommand("
DELETE FROM Turni
WHERE Data = @data AND RuoloID = @ruolo
", conn, trans)
cmd.Parameters.AddWithValue("@data", data.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@ruolo", ruoloID)
cmd.ExecuteNonQuery()
End Using
' ✅ INSERISCI NUOVI TURNI
For Each sel In gruppo
If sel.DipendenteID > 0 Then
Debug.WriteLine($" 💾 FasciaID={sel.FasciaID}, Dip={sel.DipendenteID}, Slot={sel.Slot}")
Using cmd As New SqliteCommand("
INSERT INTO Turni
(DipendenteID, RuoloID, FasciaID, Data, Stato, OrdineVisualizzazione, UtenteInserimento, DataInserimento)
VALUES
(@dip, @ruolo, @fascia, @data, @stato, @ordine, @utente, CURRENT_TIMESTAMP)
", conn, trans)
cmd.Parameters.AddWithValue("@dip", sel.DipendenteID)
cmd.Parameters.AddWithValue("@ruolo", sel.RuoloID)
cmd.Parameters.AddWithValue("@fascia", sel.FasciaID) ' ✅ DEVE ESSERE Fasce.ID
cmd.Parameters.AddWithValue("@data", sel.Data.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@stato", "Assegnato")
cmd.Parameters.AddWithValue("@ordine", sel.Slot)
cmd.Parameters.AddWithValue("@utente", Environment.UserName)
cmd.ExecuteNonQuery()
End Using
End If
Next
Next
trans.Commit()
Debug.WriteLine($"✅ Salvataggio completato: {selezioni.Count} turni")
Catch ex As Exception
trans.Rollback()
Debug.WriteLine($"❌ ERRORE salvataggio: {ex.Message}")
Debug.WriteLine($" Stack: {ex.StackTrace}")
Throw New Exception($"Errore salvataggio turni: {ex.Message}", ex)
End Try
End Using
End Using
End Sub
' ✅ RECUPERA TURNI PER DATA E RUOLO (PER PRE-COMPILARE COMBOBOX)
' ✅ RECUPERA TURNI PER DATA E RUOLO (PER PRE-COMPILARE COMBOBOX)
Public Function GetTurniPerDataERuolo(data As Date, ruoloID As Integer) As List(Of Turno)
Dim turni As New List(Of Turno)()
Using conn = db.GetConnection()
Using cmd = conn.CreateCommand()
cmd.CommandText = "
SELECT DipendenteID, FasciaID, OrdineVisualizzazione
FROM Turni
WHERE Data = @data AND RuoloID = @ruolo
ORDER BY FasciaID, OrdineVisualizzazione
"
cmd.Parameters.AddWithValue("@data", data.ToString("yyyy-MM-dd"))
cmd.Parameters.AddWithValue("@ruolo", ruoloID)
Using reader = cmd.ExecuteReader()
While reader.Read()
turni.Add(New Turno With {
.Data = data,
.RuoloID = ruoloID,
.FasciaID = reader.GetInt32(1),
.OrdineVisualizzazione = reader.GetInt32(2),
.DipendenteID = If(reader.IsDBNull(0), Nothing, reader.GetInt32(0))
})
End While
End Using
End Using
End Using
Return turni
End Function
End Class
' ✅ CLASSE PER TRASPORTARE I DATI DEL TURNO (DAL CONTROLLO AL DATABASE)
Public Class TurnoDaSalvare
Public Property Data As Date
Public Property FasciaID As Integer
Public Property Slot As Integer
Public Property DipendenteID As Integer
End Class
' ✅ CLASSE TURNO (PER LETTURA DAL DATABASE)
Public Class Turno
' ⚠️ PROPRIETÀ DAL DATABASE (TABELLA TURNI)
Public Property ID As Integer

View File

@@ -125,6 +125,9 @@
<Import Include="System.Threading.Tasks" />
</ItemGroup>
<ItemGroup>
<Compile Include="ControlTabella.vb">
<SubType>Component</SubType>
</Compile>
<Compile Include="FasciaRowControl.Designer.vb">
<DependentUpon>FasciaRowControl.vb</DependentUpon>
</Compile>
@@ -149,6 +152,12 @@
<Compile Include="FormSettaggi.vb">
<SubType>Form</SubType>
</Compile>
<Compile Include="FormTabella.Designer.vb">
<DependentUpon>FormTabella.vb</DependentUpon>
</Compile>
<Compile Include="FormTabella.vb">
<SubType>Form</SubType>
</Compile>
<Compile Include="FormTurni.Designer.vb">
<DependentUpon>FormTurni.vb</DependentUpon>
</Compile>
@@ -206,6 +215,9 @@
<EmbeddedResource Include="FormSettaggi.resx">
<DependentUpon>FormSettaggi.vb</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FormTabella.resx">
<DependentUpon>FormTabella.vb</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FormTurni.resx">
<DependentUpon>FormTurni.vb</DependentUpon>
</EmbeddedResource>