Files
gpw_next/GPW.CORE.SMART/Data/CoreSmartDataService.cs
T
2023-01-16 14:30:38 +01:00

723 lines
26 KiB
C#

using GPW.CORE.Comp;
using GPW.CORE.Data.DbModels;
using GPW.CORE.Data.DTO;
using Microsoft.AspNetCore.Identity.UI.Services;
using Newtonsoft.Json;
using NLog;
using StackExchange.Redis;
using System.Diagnostics;
namespace GPW.CORE.Smart.Data
{
public class CoreSmartDataService : IDisposable
{
#region Public Fields
public static CORE.Data.Controllers.GPWController dbController = null!;
public bool VetoInsert = false;
#endregion Public Fields
#region Public Constructors
public CoreSmartDataService(IConfiguration configuration, ILogger<CoreSmartDataService> logger, IConnectionMultiplexer redisConnMult, IEmailSender emailSender)
{
_logger = logger;
_configuration = configuration;
_emailSender = emailSender;
// Conf cache
redisConn = redisConnMult;// ConnectionMultiplexer.Connect(_configuration.GetConnectionString("Redis"));
//redisConn = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("Redis"));
redisDb = this.redisConn.GetDatabase();
// json serializer... FIX errore loop circolare https://www.ryadel.com/en/jsonserializationexception-self-referencing-loop-detected-error-fix-entity-framework-asp-net-core/
JSSettings = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
// cod app
CodApp = _configuration["CodApp"];
var strVeto = _configuration["VetoIns"];
_ = bool.TryParse(strVeto, out VetoInsert);
// Conf DB
string connStr = _configuration.GetConnectionString("GPW.DB");
if (string.IsNullOrEmpty(connStr))
{
_logger.LogError("ConnString empty!");
}
else
{
dbController = new CORE.Data.Controllers.GPWController(configuration);
}
_logger.LogInformation("Avviata classe CoreSmartDataService");
}
#endregion Public Constructors
#region Public Properties
public string CodApp { get; set; } = "";
#endregion Public Properties
#region Public Methods
/// <summary>
/// Recupera l'elenco dei controlli VC19 nel periodo indicato x dipendente
/// </summary>
/// <param name="idxDipendente">Dipendente interessato</param>
/// <param name="dtInizio">Data di riferimento (ultima/corrente)</param>
/// <param name="dtFine">NUm settimane precedenti da recuperare</param>
/// <returns></returns>
public async Task<List<CheckVc19Model>> CheckVC19List(int idxDipendente, DateTime dtInizio, DateTime dtFine)
{
string source = "DB";
List<CheckVc19Model>? dbResult = new List<CheckVc19Model>();
string currKey = $"{rKeyVC19}:{dtInizio:yyyyMMdd}:{dtFine:yyyMMdd}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<CheckVc19Model>>(rawData);
if (tempResult == null)
{
dbResult = new List<CheckVc19Model>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.CheckVC19List(idxDipendente, dtInizio, dtFine);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, FastCache);
}
if (dbResult == null)
{
dbResult = new List<CheckVc19Model>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"CheckVC19List | {source} in: {ts.TotalMilliseconds} ms");
return dbResult;
}
/// <summary>
/// Lista configurazione
/// </summary>
/// <param name="dtStart"></param>
/// <param name="dtEnd"></param>
/// <returns></returns>
public async Task<List<ConfigModel>> ConfigGetAll()
{
string source = "DB";
List<ConfigModel>? dbResult = new List<ConfigModel>();
string currKey = $"{rKeyConfig}:Table";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<ConfigModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<ConfigModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.ConfigGetAll();
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<ConfigModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ConfigGetAll | {source} in: {ts.TotalMilliseconds} ms");
return dbResult;
}
/// <summary>
/// Recupera una singola chaive di config da cache/DB
/// </summary>
/// <param name="chiave"></param>
/// <returns></returns>
public async Task<ConfigModel?> ConfigGetKey(string chiave)
{
string source = "DB";
// cerco in cache direttamente la chiave... altrimenti da redis/db
ConfigModel? keyResult = null;
string currKey = $"{rKeyConfig}:Dict:{chiave}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<ConfigModel>(rawData);
if (tempResult == null)
{
keyResult = new ConfigModel();
}
else
{
keyResult = tempResult;
}
keyResult = JsonConvert.DeserializeObject<ConfigModel>(rawData);
}
else
{
var listConfig = await ConfigGetAll();
keyResult = listConfig.FirstOrDefault(x => x.chiave == chiave);
rawData = JsonConvert.SerializeObject(keyResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ConfigGetKey | {chiave} | {source} in: {ts.TotalMilliseconds} ms");
return await Task.FromResult(keyResult);
}
/// <summary>
/// Recupera l'elenco dei dettagli giornalieri attività di un dipendente, dato periodo riferimento
/// </summary>
/// <param name="idxDipendente">Dipendente interessato</param>
/// <param name="dtInizio">Data di riferimento (ultima/corrente)</param>
/// <param name="dtFine">NUm settimane precedenti da recuperare</param>
/// <returns></returns>
public async Task<List<DailyDataDTO>> DailyDetails(int idxDipendente, DateTime dtInizio, DateTime dtFine)
{
string source = "DB";
List<DailyDataDTO>? dbResult = new List<DailyDataDTO>();
string currKey = $"{rKeyDailyData}:{idxDipendente}:{dtInizio.ToString("yyyy-MM-dd")}:{dtFine.ToString("yyyy-MM-dd")}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<DailyDataDTO>>(rawData);
if (tempResult == null)
{
dbResult = new List<DailyDataDTO>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.DailyDetails(idxDipendente, dtInizio, dtFine);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, FastCache);
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DailyDetails | {source} in: {ts.TotalMilliseconds} ms");
return dbResult;
}
public string DeriptData(string encData)
{
return SteamCrypto.DecryptString(encData, passPhrase);
}
public async Task<AnagDeviceModel?> DeviceBySecret(string devSecret)
{
string source = "DB";
AnagDeviceModel? dbResult = new AnagDeviceModel();
List<AnagDeviceModel>? cachedResult = new List<AnagDeviceModel>();
string currKey = $"{rKeyUserSecrets}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<AnagDeviceModel>>(rawData);
if (tempResult == null)
{
cachedResult = new List<AnagDeviceModel>();
}
else
{
cachedResult = tempResult;
}
}
// controllo se c'è in cache...
dbResult = cachedResult.FirstOrDefault(x => x.DeviceSecret == devSecret);
if (dbResult == null)
{
source = "REDIS + DB";
//altrimenti cerco nel DB ed aggiungo
dbResult = dbController.AnagDeviceByKey(devSecret);
if (dbResult != null)
{
cachedResult.Add(dbResult);
rawData = JsonConvert.SerializeObject(cachedResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, LongCache);
}
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DeviceBySecret | {source} in: {ts.TotalMilliseconds} ms");
return dbResult;
}
/// <summary>
/// Crea un record device
/// </summary>
/// <param name="newRecord"></param>
/// <returns></returns>
public async Task<bool> DeviceInsert(AnagDeviceModel newRecord)
{
string source = "DB";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
bool fatto = dbController.AnagDeviceInsert(newRecord);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DeviceInsert | {source} in: {ts.TotalMilliseconds} ms");
await Task.Delay(1);
return fatto;
}
public async Task<List<DipendentiModel>> DipendentiGetAll()
{
string source = "DB";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<DipendentiModel>? dbResult = new List<DipendentiModel>();
string? rawData = await redisDb.StringGetAsync(rKeyDipendenti);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<DipendentiModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<DipendentiModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.DipendentiGetAll();
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(rKeyDipendenti, rawData, FastCache);
}
if (dbResult == null)
{
dbResult = new List<DipendentiModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DipendentiGetAll | {source} in: {ts.TotalMilliseconds} ms");
return dbResult;
}
public async Task<List<Dipendenti2RuoliModel>> Dip2RuoliGetAll()
{
string source = "DB";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<Dipendenti2RuoliModel>? dbResult = new List<Dipendenti2RuoliModel>();
string? rawData = await redisDb.StringGetAsync(rKeyDip2Ruoli);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<Dipendenti2RuoliModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<Dipendenti2RuoliModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.Dipendenti2RuoliGetAll();
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(rKeyDip2Ruoli, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<Dipendenti2RuoliModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"Dip2RuoliGetAll | {source} in: {ts.TotalMilliseconds} ms");
return dbResult;
}
/// <summary>
/// Update record dipendenti
/// </summary>
/// <param name="currItem"></param>
/// <returns></returns>
public async Task<bool> DipendentiUpdate(DipendentiModel currItem)
{
bool answ = false;
try
{
answ = dbController.DipendentiUpdate(currItem);
// invalido la cache...
await FlushRedisCache();
}
catch
{ }
return answ;
}
public void Dispose()
{
// Clear database controller
dbController.Dispose();
}
public string EncriptData(string rawData)
{
return SteamCrypto.EncryptString(rawData, passPhrase);
}
public async Task<bool> FlushRedisCache()
{
await Task.Delay(1);
RedisValue pattern = new RedisValue($"{redisBaseAddr}:*");
bool answ = await ExecFlushRedisPattern(pattern);
return answ;
}
/// <summary>
/// Recupera l'elenco dei Rilievi temperatura nel periodo indicato x dipendente
/// </summary>
/// <param name="idxDipendente">Dipendente interessato</param>
/// <param name="dtInizio">Data di riferimento (ultima/corrente)</param>
/// <param name="dtFine">NUm settimane precedenti da recuperare</param>
/// <returns></returns>
public async Task<List<RilievoTempModel>> RilTempList(int idxDipendente, DateTime dtInizio, DateTime dtFine)
{
string source = "DB";
List<RilievoTempModel>? dbResult = new List<RilievoTempModel>();
string currKey = $"{rKeyRilTemp}:{dtInizio:yyyyMMdd}:{dtFine:yyyMMdd}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<RilievoTempModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<RilievoTempModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.RilTempList(idxDipendente, dtInizio, dtFine);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, FastCache);
}
if (dbResult == null)
{
dbResult = new List<RilievoTempModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"RilTempList | {source} in: {ts.TotalMilliseconds} ms");
return dbResult;
}
/// <summary>
/// Registra update valore temp rilevata
/// </summary>
/// <param name="currItem"></param>
/// <returns></returns>
public async Task<bool> RilTempUpdate(RilievoTempModel currItem)
{
bool answ = false;
try
{
dbController.RilTempUpdate(currItem);
// invalido la cache...
await ExecFlushRedisPattern($"{rKeyRilTemp}:*");
await ExecFlushRedisPattern($"{rKeyDailyData}:*");
answ = true;
}
catch
{ }
return answ;
}
public void rollBackEdit(object item)
{
dbController.rollBackEntity(item);
}
/// <summary>
/// Invio email tramite libreria
/// </summary>
/// <param name="destList">Elenco destinatari separati da virgola</param>
/// <param name="subject">Oggetto email</param>
/// <param name="message">Corpo Email (HTML)</param>
/// <returns></returns>
public async Task<bool> sendEmailAsync(string destList, string subject, string message)
{
bool fatto = false;
List<string> emailDestList = destList.Split(",").ToList();
foreach (var dest in emailDestList)
{
try
{
await _emailSender.SendEmailAsync(dest, subject, message);
fatto = true;
}
catch (Exception exc)
{
Log.Error($"Eccezione durante invio email:{Environment.NewLine}dest: {dest} | subject {subject}{Environment.NewLine}{exc}");
}
}
return fatto;
}
/// <summary>
/// Elenco timbrature di un giorno
/// </summary>
/// <param name="dateRif"></param>
/// <param name="IdxDip"></param>
/// <returns></returns>
public async Task<List<TimbratureModel>> TimbratureDay(DateTime dateRif, int IdxDip)
{
await Task.Delay(1);
List<TimbratureModel>? dbResult = new List<TimbratureModel>();
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = dbController.TimbratureDay(dateRif, IdxDip);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Trace($"Effettuata lettura da DB + caching per TimbratureDay: {ts.TotalMilliseconds} ms");
return dbResult;
}
public async Task<bool> TimbratureDelete(TimbratureModel currItem)
{
bool answ = false;
try
{
dbController.TimbratureDelete(currItem);
// invalido la cache...
await FlushRedisCache();
answ = true;
}
catch
{ }
return answ;
}
/// <summary>
/// Inserimento richeista mancata timbratura
/// </summary>
/// <param name="currItem"></param>
/// <returns></returns>
public async Task<bool> TimbratureInsRichiesta(TimbratureModel currItem)
{
bool answ = false;
try
{
// aggiorna i campi x mancata timbratura (hard coded)
currItem.CodTipoTimb = "NoTim";
currItem.Approv = false;
// upsert!
dbController.TimbratureUpdate(currItem);
Log.Info($"Registrata richiesta Mancata TImbratura | idxDip {currItem.IdxDipendente} | data-ora: {currItem.DataOra} | isEntrata: {currItem.Entrata}");
// invalido la cache...
await FlushRedisCache();
answ = true;
}
catch
{ }
return answ;
}
public async Task<bool> TimbratureUpdate(TimbratureModel currItem)
{
bool answ = false;
try
{
dbController.TimbratureUpdate(currItem);
// invalido la cache...
await FlushRedisCache();
answ = true;
}
catch
{ }
return answ;
}
#endregion Public Methods
#region Protected Fields
protected const string passPhrase = "EB6BD8BE-638F-481E-85E4-F89012DA95BB";
protected const string redisBaseAddr = "GPW:Smart";
protected const string rKeyAKV = $"{redisBaseAddr}:Cache:AKV";
protected const string rKeyAnOrDip = $"{redisBaseAddr}:Cache:AnOrariDip";
protected const string rKeyCalcOreFase = $"{redisBaseAddr}:Cache:CalcOreFase";
protected const string rKeyCalcOreProj = $"{redisBaseAddr}:Cache:CalcOreProj";
protected const string rKeyCalendari = $"{redisBaseAddr}:Cache:Calendari";
protected const string rKeyCliAll = $"{redisBaseAddr}:Cache:CliAll";
protected const string rKeyConfig = $"{redisBaseAddr}:Cache:Config";
protected const string rKeyDailyData = $"{redisBaseAddr}:Cache:DailyData";
protected const string rKeyDip2Ruoli = $"{redisBaseAddr}:Cache:Dip2Ruoli";
protected const string rKeyDipendenti = $"{redisBaseAddr}:Cache:Dipendenti";
protected const string rKeyFasiAll = $"{redisBaseAddr}:Cache:FasiAll";
protected const string rKeyFasiByProj = $"{redisBaseAddr}:Cache:FasiByProj";
protected const string rKeyFasiSearch = $"{redisBaseAddr}:Cache:FasiSearch";
protected const string rKeyGiust = $"{redisBaseAddr}:Cache:Giustif";
protected const string rKeyGrpAll = $"{redisBaseAddr}:Cache:GrpAll";
protected const string rKeyGrpUser = $"{redisBaseAddr}:Cache:GrpUser";
protected const string rKeyParetoRegAtt = $"{redisBaseAddr}:Cache:ParetoRegAtt";
protected const string rKeyProjAll = $"{redisBaseAddr}:Cache:ProjAll";
protected const string rKeyRilTemp = $"{redisBaseAddr}:Cache:RilTemp";
protected const string rKeyUserSecrets = $"{redisBaseAddr}:Cache:DevSecrets";
protected const string rKeyVC19 = $"{redisBaseAddr}:Cache:VC19";
protected const string rKeyVetoIns = $"{redisBaseAddr}:Cache:VetoInsert";
protected const string rKeyWeekStats = $"{redisBaseAddr}:Cache:WeekStats";
protected static string connStringBBM = "";
protected Random rnd = new Random();
#endregion Protected Fields
#region Private Fields
private static IConfiguration _configuration = null!;
private static ILogger<CoreSmartDataService> _logger = null!;
private static JsonSerializerSettings? JSSettings;
private static NLog.Logger Log = LogManager.GetCurrentClassLogger();
private readonly IEmailSender _emailSender;
private List<string> cachedDataList = new List<string>();
/// <summary>
/// Durata cache lunga IN SECONDI
/// </summary>
private int cacheTtlLong = 60 * 5;
/// <summary>
/// Durata cache breve IN SECONDI
/// </summary>
private int cacheTtlShort = 60 * 1;
/// <summary>
/// Oggetto per connessione a REDIS
/// </summary>
private IConnectionMultiplexer redisConn;
//ISubscriber sub = redis.GetSubscriber();
/// <summary>
/// Oggetto DB redis da impiegare x chiamate R/W
/// </summary>
private IDatabase redisDb = null!;
#endregion Private Fields
#region Private Properties
/// <summary>
/// Durata cache lunga (+ perturbazione percentuale +/-10%)
/// </summary>
private TimeSpan FastCache
{
get => TimeSpan.FromSeconds(cacheTtlShort * rnd.Next(900, 1100) / 1000);
}
/// <summary>
/// Durata cache lunga (+ perturbazione percentuale +/-10%)
/// </summary>
private TimeSpan LongCache
{
get => TimeSpan.FromSeconds(cacheTtlLong * rnd.Next(900, 1100) / 1000);
}
/// <summary>
/// Durata cache lunga (+ perturbazione percentuale +/-10%)
/// </summary>
private TimeSpan UltraLongCache
{
get => TimeSpan.FromSeconds(cacheTtlLong * 10 * rnd.Next(900, 1100) / 1000);
}
#endregion Private Properties
#region Private Methods
/// <summary>
/// Esegue flush memoria redis dato pattern
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
private async Task<bool> ExecFlushRedisPattern(RedisValue pattern)
{
bool answ = false;
var listEndpoints = redisConn.GetEndPoints();
foreach (var endPoint in listEndpoints)
{
//var server = redisConnAdmin.GetServer(listEndpoints[0]);
var server = redisConn.GetServer(endPoint);
if (server != null)
{
var keyList = server.Keys(redisDb.Database, pattern);
foreach (var item in keyList)
{
await redisDb.KeyDeleteAsync(item);
}
answ = true;
}
}
return answ;
}
#endregion Private Methods
}
}