Files
2025-06-21 11:53:07 +02:00

544 lines
18 KiB
C#

using EgwCoreLib.Razor;
using GPW.CORE.Data.DbModels;
using GPW.CORE.Data.Services;
using GPW.CORE.Data;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using NLog;
using EgwCoreLib.Utils;
using System.Diagnostics;
using static GPW.CORE.ADM.Components.Compo.GiustList;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace GPW.CORE.ADM.Components.Compo
{
public partial class ReviewTimbMan : IDisposable
{
#region Public Methods
public void Dispose()
{
AppMServ.EA_SearchUpdated -= AppMServ_EA_SearchUpdated;
}
#endregion Public Methods
#region Protected Fields
protected List<int> PageSizeListSpec = new List<int>() { 5, 10, 15, 20, 25, 50 };
#endregion Protected Fields
#region Protected Properties
[Inject]
protected MessageService AppMServ { get; set; } = null!;
[Inject]
protected IConfiguration config { get; set; } = null!;
[Inject]
protected GpwDataService GDataServ { get; set; } = null!;
protected int IdxDipSel { get; set; } = 0;
[Inject]
protected IJSRuntime JSRuntime { get; set; } = null!;
#endregion Protected Properties
#region Protected Methods
protected string CheckSel(TeRaExplModel? SelItem)
{
string answ = "";
if (SelRecord != null)
{
answ = SelRecord.UID == SelItem.UID ? "table-info" : "";
}
return answ;
}
protected async Task DoSelect(TeRaExplModel selItem)
{
// seleziono record x mostrare update
SelRecord = selItem;
await ReloadDayDetail();
await Task.Delay(1);
}
protected async Task ForceReload()
{
currPage = 1;
SelRecord = null;
await ReloadData();
await ReloadDayDetail();
}
protected async Task GiustAddNew(string CodGiust)
{
if (SelRecord != null)
{
await GDataServ.GiustificativiInsByDate(SelRecord.IdxDipendente, SelRecord.DataLav, CodGiust);
await ReloadData();
await ReloadDayDetail();
}
}
protected async Task GiustCancel()
{
await ReloadData();
await ReloadDayDetail();
}
protected async Task GiustDelete(GiustificativiModel selItem)
{
if (!await JSRuntime.InvokeAsync<bool>("confirm", "Sicuro di voler eliminare il record Giustificativo?"))
return;
await GDataServ.GiustificativiDelete(selItem);
await ReloadData();
await ReloadDayDetail();
}
protected async Task GiustUpdate(GiustSet newSet)
{
await GDataServ.GiustificativiUpdate(newSet.OldRec, newSet.NewRec);
await ReloadData();
await ReloadDayDetail();
}
protected override async Task OnInitializedAsync()
{
CurrPeriodo.Fine = DateTime.Today.AddDays(1);
CurrSearch = "";
AppMServ.SearchVal = "";
AppMServ.EA_SearchUpdated += AppMServ_EA_SearchUpdated;
numRecord = await AppMServ.NumRowGridGet(gridKey);
ListGiust = await GDataServ.AnagGiust();
// imposto path...
exportPath = config.GetValue<string>("ServerConf:BasePathExport") ?? config.GetValue<string>("OptConf:BasePathExport") ?? $"{Directory.GetCurrentDirectory()}\\temp\\";
// svuoto temp folder dopo 1 min
await clearDir(1);
// carico conf specifica...
var rCodTimbra = await GDataServ.ConfigGetKeyAsync("ExpOreCodTimbra");
if (rCodTimbra != null)
{
TimbExp = rCodTimbra.valore;
}
}
protected override async Task OnParametersSetAsync()
{
await ReloadData();
}
protected async Task SetNumRec(int newNum)
{
numRecord = newNum;
currPage = 1;
await AppMServ.NumRowGridSet(gridKey, newNum);
await InvokeAsync(ReloadData);
}
protected async Task SetPage(int newNum)
{
currPage = newNum;
await InvokeAsync(ReloadData);
}
protected async Task SortRequested(Sorter.SortCallBack e)
{
sortField = e.ParamName;
sortAsc = e.IsAscending;
await ReloadData();
}
protected async Task TimbDelete(TimbratureModel selItem)
{
if (!await JSRuntime.InvokeAsync<bool>("confirm", "Sicuro di voler eliminare il record Timbratura?"))
return;
await GDataServ.TimbratureDelete(selItem);
await ReloadData();
await ReloadDayDetail();
//SelRecord = null;
//await InvokeAsync(StateHasChanged);
}
protected async Task TimbUpdate(TimbratureModel UpdRec)
{
await GDataServ.TimbratureUpdate(UpdRec);
await ReloadData();
await ReloadDayDetail();
}
#endregion Protected Methods
#region Private Fields
private static Logger Log = LogManager.GetCurrentClassLogger();
private string gridKey = "RevTimbMan";
private int sendDataMaxVal = 100;
private int sendDataNextVal = 0;
private int sendDataVal = 0;
private bool sortAsc = true;
private string sortField = "";
#endregion Private Fields
#region Private Properties
private int currPage { get; set; } = 1;
private DtUtils.Periodo CurrPeriodo { get; set; } = new DtUtils.Periodo(DtUtils.PeriodSet.ThisMonth);
private string CurrSearch { get; set; } = "";
private string exportPath { get; set; } = "";
private bool filtDip { get; set; } = false;
private string fnExpComm
{
get => $"ExportCommesse_{DateTime.Now:yyyyMMdd}_{DateTime.Now:HHmmss}.csv";
}
private string fnTimb
{
get => $"Timbrature_{DateTime.Now:yyyyMMdd}_{DateTime.Now:HHmmss}.csv";
}
private bool isLoading { get; set; } = false;
private bool isSendingData { get; set; } = false;
private List<DipendentiModel> ListDipendenti { get; set; } = new List<DipendentiModel>();
private List<AnagGiustModel>? ListGiust { get; set; } = null;
private List<GiustificativiModel>? ListGiustDay { get; set; } = null;
private List<RegAttivitaModel>? ListRA { get; set; } = null;
private List<TeRaExplModel>? ListRecords { get; set; } = null;
private List<TimbratureModel>? ListTimbDay { get; set; } = null;
private int MaxErrMin { get; set; } = -30;
private int MaxErrPlus { get; set; } = 30;
private int numRecord { get; set; } = 10;
private List<TeRaExplModel>? SearchRecords { get; set; } = null;
private TeRaExplModel? SelRecord { get; set; } = null;
private bool ShowInatt { get; set; } = false;
private bool ShowWE { get; set; } = true;
private string TimbExp { get; set; } = "000";
private int totalCount { get; set; } = 0;
#endregion Private Properties
#region Private Methods
private async void AppMServ_EA_SearchUpdated()
{
CurrSearch = AppMServ.SearchVal;
await ReloadData();
await InvokeAsync(StateHasChanged);
}
private async Task clearDir(int maxAgeMinutes)
{
string dirPath = Path.Combine(exportPath);
DirectoryInfo dInfo = new DirectoryInfo(dirPath);
await Task.Run(() =>
{
var fileList = dInfo.GetFiles();
// elimino file + vecchi de minuti ricevuti...
foreach (var file in fileList)
{
if (file.CreationTime < DateTime.Now.AddMinutes(-maxAgeMinutes))
{
file.Delete();
}
}
});
}
private bool ClearFile(string fileName)
{
bool fatto = false;
string filePath = Path.Combine(exportPath, fileName);
if (File.Exists(filePath))
{
File.Delete(exportPath);
fatto = true;
}
return fatto;
}
/// <summary>
/// ricalcola giornate periodo visualizzato per i dipendenti selezionati
/// </summary>
private async Task DoFullRecalc()
{
if (!await JSRuntime.InvokeAsync<bool>("confirm", "Sicuro di voler ricalcolare il periodo selezionato? L'operazione richiederà tempo..."))
return;
Stopwatch sw = new Stopwatch();
sw.Start();
Log.Trace($"DoFullRecalc | Starting");
isSendingData = true;
await Task.Delay(1);
sendDataVal = 0;
sendDataNextVal = 50;
await InvokeAsync(StateHasChanged);
// step 1: ricalcola timb esplose x utenti e periodo...
var updTask = Task.Run(async () =>
await GDataServ.TimbExplRicalcola(IdxDipSel, CurrPeriodo.Inizio, CurrPeriodo.Fine)
);
await updTask;
sw.Stop();
Log.Info($"DoFullRecalc | STEP 01 | {sw.ElapsedMilliseconds:N0} ms");
sw.Restart();
sendDataVal = 50;
sendDataNextVal = 90;
await InvokeAsync(StateHasChanged);
// verifico dip con giust da inserire...
var list2fix = await GDataServ.TimbExplGetAnomalie(IdxDipSel, CurrPeriodo.Inizio, CurrPeriodo.Fine, false, false, true);
if (list2fix != null && list2fix.Count > 0)
{
var updTask2 = Task.Run(async () =>
{
foreach (var item in list2fix)
{
// escludo date da dtRif in poi...
if (item.DataLav < DateTime.Today)
{
GiustificativiModel rec2del = new GiustificativiModel()
{
IdxDipendente = item.IdxDipendente,
DataLav = item.DataLav,
CodGiust = "PERM"
};
try
{
// elimino eventuali vecchi permessi
await GDataServ.GiustificativiDelete(rec2del);
// inserisco permessi...
await GDataServ.GiustificativiInsByDate(item.IdxDipendente, item.DataLav, "PERM");
}
catch (Exception exc)
{
Log.Error($"Eccezione in ricalcolo:{Environment.NewLine}{exc}");
}
}
}
sw.Stop();
Log.Info($"DoFullRecalc | STEP 02 | {sw.ElapsedMilliseconds:N0} ms");
sw.Restart();
// ricalcolo!
await GDataServ.TimbExplRicalcola(IdxDipSel, CurrPeriodo.Inizio, CurrPeriodo.Fine);
sw.Stop();
Log.Info($"DoFullRecalc | STEP 03 | {sw.ElapsedMilliseconds:N0} ms");
sw.Restart();
});
sw.Stop();
await updTask2;
Log.Info($"DoFullRecalc | STEP 04 | {sw.ElapsedMilliseconds:N0} ms");
sw.Restart();
}
sendDataVal = 90;
sendDataNextVal = 100;
await InvokeAsync(StateHasChanged);
// ricalcolo RegAttExpl
var updTask3 = Task.Run(async () =>
{
await GDataServ.RegAttRicalcola(IdxDipSel, CurrPeriodo.Inizio, CurrPeriodo.Fine);
});
await updTask3;
sw.Stop();
Log.Info($"DoFullRecalc | STEP 05 | {sw.ElapsedMilliseconds:N0} ms");
// aggiorno
SelRecord = null;
sendDataVal = 100;
sendDataNextVal = 100;
isLoading = true;
await Task.Delay(1);
await InvokeAsync(StateHasChanged);
await ReloadData();
}
private async Task ExportCsv<T>(string fileName, List<T> RecList)
{
isLoading = true;
if (RecList != null)
{
string filePath = Path.Combine(exportPath, fileName);
// salvo davvero!
await Utils.SaveToCsv(RecList, filePath, ';');
}
isLoading = false;
}
private async Task ExportTxt(string fileName, List<string> RecList)
{
isLoading = true;
if (RecList != null)
{
string filePath = Path.Combine(exportPath, fileName);
await File.WriteAllLinesAsync(filePath, RecList);
}
isLoading = false;
}
private async Task ReloadData()
{
isLoading = true;
ListRecords = null;
var rawList = await GDataServ.DipendentiGetAll();
if (ShowInatt)
{
ListDipendenti = rawList;
}
else
{
ListDipendenti = rawList.Where(x => (x.Attivo ?? false)).ToList();
}
try
{
SearchRecords = await GDataServ.TeRaExplGetFilt(IdxDipSel, CurrPeriodo.Inizio, CurrPeriodo.Fine, ShowInatt, ShowWE, MaxErrMin, MaxErrPlus);
// verifico filtro per IdxDip
if (IdxDipSel > 0)
{
SearchRecords = SearchRecords.Where(x => x.IdxDipendente == IdxDipSel).ToList();
}
}
catch (Exception ex)
{
Log.Error($"Eccezione in recupero dati{Environment.NewLine}{ex}");
}
totalCount = SearchRecords.Count;
SortTable();
isLoading = false;
// tolgo eventuale send data...
isSendingData = false;
}
private async Task ReloadDayDetail()
{
if (SelRecord != null)
{
// salvo dettaglio giornaliero
ListTimbDay = await GDataServ.TimbratureDay(SelRecord.DataLav, SelRecord.IdxDipendente);
ListGiustDay = await GDataServ.GiustificativiFilt(SelRecord.IdxDipendente, SelRecord.DataLav, SelRecord.DataLav.AddDays(1).AddMinutes(-1));
ListRA = await GDataServ.RegAttDipDate(SelRecord.IdxDipendente, SelRecord.DataLav);
}
}
private async Task SaveExpCom()
{
// svuoto
ClearFile(fnExpComm);
// recupero nuovo elenco dati...
var list2save = await GDataServ.ExportCommessa(IdxDipSel, CurrPeriodo.Inizio, CurrPeriodo.Fine);
if (list2save != null)
{
// bonifica descrizione: elimino gli a capo...
foreach (var item in list2save)
{
if (item.Descrizione.Contains(Environment.NewLine) || item.Descrizione.Contains("\n") || item.Descrizione.Contains("\r"))
{
item.Descrizione = item.Descrizione.Replace(Environment.NewLine, " ").Replace("\n", " ").Replace("\r", " ");
}
}
// export
await ExportCsv(fnExpComm, list2save);
// chiamo apri pagina x download
await JSRuntime.InvokeVoidAsync("open", $"export/{fnExpComm}", "_blank");
}
}
private async Task SaveExpOre()
{
// svuoto
ClearFile(fnTimb);
// recupero nuovo elenco dati elenco zucchetti
var rawData = await GDataServ.ExportZucchetti(IdxDipSel, CurrPeriodo.Inizio, CurrPeriodo.Fine, TimbExp);
var list2save = rawData.Select(x => x.CampoExport).ToList();
if (list2save != null)
{
// export
await ExportTxt(fnTimb, list2save);
// chiamo apri pagina x download
await JSRuntime.InvokeVoidAsync("open", $"export/{fnTimb}", "_blank");
}
}
private async Task SavePeriodo(DtUtils.Periodo newPeiodo)
{
CurrPeriodo = newPeiodo;
await ReloadData();
}
private void SortTable()
{
if (SearchRecords != null)
{
// se ho ordinamento riordino...
if (!string.IsNullOrEmpty(sortField))
{
switch (sortField)
{
case "Dipendente":
if (sortAsc)
{
SearchRecords = SearchRecords.OrderBy(x => x.CognomeNome).ToList();
}
else
{
SearchRecords = SearchRecords.OrderByDescending(x => x.CognomeNome).ToList();
}
break;
case "DataLav":
if (sortAsc)
{
SearchRecords = SearchRecords.OrderBy(x => x.DataLav).ToList();
}
else
{
SearchRecords = SearchRecords.OrderByDescending(x => x.DataLav).ToList();
}
break;
default:
break;
}
}
// filtro x display
ListRecords = SearchRecords
.Skip(numRecord * (currPage - 1))
.Take(numRecord)
.ToList();
}
else
{
ListRecords = new List<TeRaExplModel>();
}
}
#endregion Private Methods
}
}