Files
Gestionale-Turni/gestionaleTurni/FormDipendente.vb
luca.mustacchio@outlook.it c8978b3795 Backup prima del merge
2026-03-25 17:56:28 +01:00

571 lines
22 KiB
VB.net
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Imports System.Drawing
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)
Public Property dipendenteSelezionato As Dipendente
Get
Return _dipendenteSelezionato
End Get
Set(value As Dipendente)
_dipendenteSelezionato = value
RaiseEvent DipendenteSelezionatoChanged(value)
popolaForm()
End Set
End Property
' --- MODIFICA DIPENDENTE (Da Form Esterno) ---
Public Sub ModificaDipendente(dip As Dipendente)
dipendenteSelezionato = dip
If dip IsNot Nothing Then
CaricaDatiDipendente()
End If
GroupAssenza.Enabled = True
Me.Show()
End Sub
Private Sub setText()
Me.Text = $"👤 {If(dipendenteSelezionato IsNot Nothing, dipendenteSelezionato.NomeCompleto, "Nuovo Dipendente")}"
End Sub
' --- CARICAMENTO FORM ---
Private Sub FormDipendente_Load(sender As Object, e As EventArgs) Handles MyBase.Load
VScrollBar1.BackColor = Color.LightGray
VScrollBar1.ForeColor = Color.DarkBlue
' ⚠️ CARICA PRIMA LA LISTA
listaDipendenti = Gestionale.gestioneDipendenti.GetDipendenti("")
If listaDipendenti.Count = 0 Then Return
VScrollBar1.Maximum = listaDipendenti.Count - 1
If dipendenteSelezionato Is Nothing Then
' Primo dipendente della lista
index = 0
dipendenteSelezionato = listaDipendenti(index)
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
End If
VScrollBar1.Value = index
popolaForm()
End Sub
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()
InizializzaControlliDipendente()
InizializzaControlliAssenze()
ConfiguraGriglia()
setText()
popolaTextTot()
End Sub
Private Sub InizializzaControlliDipendente()
If dipendenteSelezionato IsNot Nothing Then
CaricaDatiDipendente()
End If
End Sub
Private Sub CaricaDatiDipendente()
TextDipNome.Text = dipendenteSelezionato.Nome
TextDipCognome.Text = dipendenteSelezionato.Cognome
DateTimeDipNascita.Value = If(String.IsNullOrEmpty(dipendenteSelezionato.DataNascita), DateTime.Today, DateTime.Parse(dipendenteSelezionato.DataNascita))
CheckAttivo.Checked = dipendenteSelezionato.Attivo
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)
End Sub
Private Sub InizializzaControlliAssenze()
Try
' 1. Controlla che la lista dei tipi assenza non sia Nothing
Dim lista = Gestionale.gestioneTipiAssenze.GetTipiAssenza()
If lista Is Nothing Then
lista = New List(Of TipoAssenza)() ' lista vuota
End If
' 2. Assicurati che la Combo esista
If ComboTipoAssenza IsNot Nothing Then
ComboTipoAssenza.DataSource = lista
ComboTipoAssenza.DisplayMember = "Nome"
ComboTipoAssenza.ValueMember = "ID"
End If
' 3. Date Assenze (Dettaglio)
If DtpAssenzaDal IsNot Nothing Then
DtpAssenzaDal.Format = DateTimePickerFormat.Short
DtpAssenzaAl.Format = DateTimePickerFormat.Short
DtpAssenzaDal.Value = DateTime.Today
DtpAssenzaAl.Value = DateTime.Today
End If
' 4. Date Assenze (Filtro)
If DtpDal IsNot Nothing AndAlso DtpAl IsNot Nothing Then
DtpDal.Format = DateTimePickerFormat.Long
DtpAl.Format = DateTimePickerFormat.Long
DtpAl.Value = DtpDal.Value.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
CaricaAssenze()
End Sub
Private Sub CaricaAssenze()
If dipendenteSelezionato IsNot Nothing Then
' ← LEGGI DIRETTAMENTE DAL DATABASE
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"
System.Diagnostics.Debug.WriteLine($"CaricaAssenze: {assenzeCorrenti.Count} assenze trovate")
End If
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
AddHandler DataGridAssenze.CellFormatting, AddressOf DataGridAssenzeAssenze_CellFormatting
End Sub
Private Sub DataGridAssenzeAssenze_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs)
If DataGridAssenze.Rows(e.RowIndex).DataBoundItem Is Nothing Then Return
Dim assenza As Assenza = CType(DataGridAssenze.Rows(e.RowIndex).DataBoundItem, Assenza)
' Colonna Stato
If e.ColumnIndex = DataGridAssenze.Columns("Approvata").Index Then
e.Value = assenza.Approvata ' If(assenza.Approvata, "✅ Approvata", "⏳ In attesa")
e.CellStyle.BackColor = If(assenza.Approvata, Color.LightGreen, Color.Orange)
e.CellStyle.ForeColor = Color.Black
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)
ComboTipoAssenza.SelectedIndex = 0
' 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)
' ==========================================
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")
Return
End If
If dipendenteSelezionato Is Nothing Then
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
)
Else
' Se esiste già, aggiorna le proprietà
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
Gestionale.gestioneDipendenti.SalvaDipendente(dipendenteSelezionato)
' Salva Ruoli associati
'Gestionale.gestioneRuoli.SalvaRuoliDipendente(dipendenteSelezionato.ID, lista)
dipendenteSelezionato.SetRuoli(lista)
MessageBox.Show("Dipendente salvato con successo!")
Form1.PopolaGrigliaDipendenti()
GroupAssenza.Enabled = True
popolaForm()
End Sub
Private Sub btnNuovoRuolo_Click(sender As Object, e As EventArgs) Handles btnNuovoRuolo.Click
Dim n = InputBox("Nome ruolo", "Nuovo Ruolo")
Dim desc = InputBox("Descrizione", "Nuovo Ruolo")
Dim r As New Ruolo()
r.Nome = n
r.Descrizione = desc
Gestionale.gestioneRuoli.SalvaRuolo(r)
Gestionale.PopolaCheckedListBox_T(Of Ruolo)(CheckDipRuoli, Gestionale.gestioneRuoli.GetRuoli)
End Sub
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)
End If
End Sub
' ==========================================
' GESTIONE ASSENZE
' ==========================================
Private Sub ImpostaPeriodoDefault()
DtpDal.Value = DateTime.Today
DtpAl.Value = DateTime.Today.AddDays(10)
CalcolaGiorniPeriodo()
End Sub
Private Sub CalcolaGiorniPeriodo()
Dim giorni As Integer = (DtpAl.Value.Date - DtpDal.Value.Date).Days + 1
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
Private Sub DtpAl_ValueChanged(sender As Object, e As EventArgs) Handles DtpAl.ValueChanged
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
_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!
End If
DtpAssenzaDal.Value = _assenzaSelezionata.DataInizio
DtpAssenzaAl.Value = _assenzaSelezionata.DataInizio
TxtMotivazione.Text = _assenzaSelezionata.Motivazione
ChkApprovata.Checked = _assenzaSelezionata.Approvata
' ← 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
CalcolaGiorniDettaglio()
DtpAssenzaAl.Value = DtpAssenzaDal.Value
End Sub
Private Sub DtpAlDettaglio_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.ForeColor = Color.Green
Else
lblGiorniDettaglio.Text = "⚠️ Data fine precedente!"
lblGiorniDettaglio.ForeColor = Color.Red
End If
End Sub
' --- SALVA ASSENZA (Intervallo Dal/Al) ---
Private Sub btnSalvaAssenza_Click(sender As Object, e As EventArgs) Handles btnSalvaAssenza.Click
Try
' ← 1. LEGGI LE FASCE PRIMA DI QUALSIASI OPERAZIONE (IMPORTANTE!)
Dim listaFasce = Gestionale.listaID_ChecklistBox(CheckedListFasce)
' -------------------
' Controllo tipo assenza
' -------------------
Dim tipoID As Integer = 0
If ComboTipoAssenza.SelectedValue Is Nothing Then
Dim r = MsgBox($"Tipo di assenza '{ComboTipoAssenza.Text}' non esistente. Aggiungere?",
MsgBoxStyle.YesNo + MsgBoxStyle.Question)
If r = MsgBoxResult.Yes Then
Dim ta As New TipoAssenza
ta.Nome = ComboTipoAssenza.Text.Trim()
ta.Descrizione = InputBox($"Aggiungi una descrizione per il tipo di assenza: {ComboTipoAssenza.Text}")
Dim ret = MsgBox("È retribuita?", MsgBoxStyle.YesNo + MsgBoxStyle.Question)
ta.Retribuita = (ret = MsgBoxResult.Yes)
' ← SALVA E RECUPERA L'ID GENERATO
Gestionale.gestioneTipiAssenze.SalvaTipoAssenza(ta)
tipoID = ta.ID
' ← CORRETTO: Ricarica SOLO la ComboBox, NON tutti i controlli!
Dim listaTipi = Gestionale.gestioneTipiAssenze.GetTipiAssenza()
ComboTipoAssenza.DataSource = Nothing
ComboTipoAssenza.DataSource = listaTipi
ComboTipoAssenza.DisplayMember = "Nome"
ComboTipoAssenza.ValueMember = "ID"
ComboTipoAssenza.SelectedValue = tipoID
' ← NON chiamare InizializzaControlliAssenze() qui!
' ← Le fasce sono già state lette sopra, non si perdono
Else
MessageBox.Show("Operazione annullata.")
ComboTipoAssenza.Focus()
Return
End If
Else
tipoID = CInt(ComboTipoAssenza.SelectedValue)
End If
If tipoID <= 0 Then
MessageBox.Show("Tipo assenza non valido.")
Return
End If
' -------------------
' Controllo dipendente
' -------------------
If dipendenteSelezionato Is Nothing Then
MessageBox.Show("Seleziona un dipendente.")
Return
End If
' -------------------
' Controllo date
' -------------------
If DtpAssenzaDal.Value.Date > DtpAssenzaAl.Value.Date Then
MessageBox.Show("Le date non sono valide.")
Return
End If
' ← 2. CONTROLLA LE FASCE (già lette all'inizio)
If listaFasce.Count = 0 Then
MessageBox.Show("Selezionare almeno una fascia.")
Return
End If
' -------------------
' Creazione oggetto assenza
' -------------------
Dim a As New Assenza With {
.DipendenteID = dipendenteSelezionato.ID,
.DataInizio = DtpAssenzaDal.Value.Date,
.DataFine = DtpAssenzaAl.Value.Date,
.TipoAssenzaID = tipoID,
.Motivazione = TxtMotivazione.Text,
.Approvata = ChkApprovata.Checked
}
' ← Aggiunta fasce
For Each id In listaFasce
a.Fasce.Add(New AssenzaFascia With {.FasciaID = id})
Next
' -------------------
' Salvataggio DB
' -------------------
Gestionale.gestioneAssenze.SalvaAssenza(a)
' -------------------
' Aggiornamento UI
' -------------------
CaricaAssenze()
ConfiguraGriglia()
Catch ex As Exception
MessageBox.Show($"Errore: {ex.Message}" & vbCrLf & ex.StackTrace)
Console.WriteLine(ex.Message & vbCrLf & ex.StackTrace)
End Try
End Sub
Private Sub PulisciCampiAssenze()
_assenzaSelezionata = Nothing
ComboTipoAssenza.SelectedIndex = 0
DtpAssenzaDal.Value = DateTime.Today
DtpAssenzaAl.Value = DateTime.Today
TxtMotivazione.Text = ""
ChkApprovata.Checked = False
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.")
Return
End If
Dim result As DialogResult = 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.")
PulisciCampiAssenza()
CaricaAssenze()
End If
End Sub
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
Private Sub BtnAnnullla_Click(sender As Object, e As EventArgs) Handles BtnAnnullla.Click
CaricaDatiDipendente()
End Sub
Private Sub btnModificaAssenza_Click(sender As Object, e As EventArgs) Handles btnModificaAssenza.Click
If DataGridAssenze.CurrentRow Is Nothing 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
ChkApprovata.Checked = assenza.Approvata
TxtMotivazione.Text = assenza.Motivazione
End If
End Sub
Private Sub CheckDipRuoli_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CheckDipRuoli.SelectedIndexChanged
End Sub
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)
' ← PRE-SELEZIONA SOLO SE CI SONO FASCE CONFIGURATE
If fasciaIDs.Count > 0 Then
Gestionale.ChecklistBox_Spunta(CheckedListFasce, fasciaIDs)
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
Private Sub VScrollBar1_Scroll(sender As Object, e As ScrollEventArgs) Handles VScrollBar1.Scroll
index = VScrollBar1.Value
dipendenteSelezionato = listaDipendenti(index)
End Sub
End Class
' Classe di supporto per ComboFascia
Public Class ComboItem
Public Property ID As Integer
Public Property Nome As String
Public Overrides Function ToString() As String
Return Nome
End Function
End Class