1894 lines
78 KiB
C#
1894 lines
78 KiB
C#
using GWMS.Data;
|
|
using GWMS.Data.DatabaseModels;
|
|
using GWMS.Data.DTO;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.AspNetCore.Identity.UI.Services;
|
|
using Microsoft.Extensions.Caching.Distributed;
|
|
using Microsoft.Extensions.Caching.Memory;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Logging;
|
|
using Newtonsoft.Json;
|
|
using NLog;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.Globalization;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using static GWMS.Data.IobObjects;
|
|
|
|
namespace GWMS.UI.Data
|
|
{
|
|
public class GWMSDataService : IDisposable
|
|
{
|
|
#region Public Fields
|
|
|
|
public static GWMS.Data.Controllers.GWMSController dbController;
|
|
|
|
#endregion Public Fields
|
|
|
|
#region Public Constructors
|
|
|
|
public GWMSDataService(IConfiguration configuration, ILogger<GWMSDataService> logger, IMemoryCache memoryCache, IDistributedCache distributedCache, IEmailSender emailSender, UserManager<IdentityUser> userManager)
|
|
{
|
|
_logger = logger;
|
|
_configuration = configuration;
|
|
_emailSender = emailSender;
|
|
_userManager = userManager;
|
|
// conf cache
|
|
this.memoryCache = memoryCache;
|
|
this.distributedCache = distributedCache;
|
|
// conf DB
|
|
string connStr = _configuration.GetConnectionString("GWMS.Data");
|
|
if (string.IsNullOrEmpty(connStr))
|
|
{
|
|
_logger.LogError("ConnString empty!");
|
|
}
|
|
else
|
|
{
|
|
dbController = new GWMS.Data.Controllers.GWMSController(configuration);
|
|
}
|
|
}
|
|
|
|
#endregion Public Constructors
|
|
|
|
#region Public Methods
|
|
|
|
/// <summary>
|
|
/// Hash dati MemoryMap x la macchina specificata
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <returns></returns>
|
|
public static string currMamMapHash(string idxMacchina)
|
|
{
|
|
return mHash(string.Format("MemMap:{0}", idxMacchina));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Hash dati CurrentParameters x la macchina specificata
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <returns></returns>
|
|
public static string currParametersHash(string idxMacchina)
|
|
{
|
|
return mHash(string.Format("CurrentParameters:{0}", idxMacchina));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Hash Redis contenente i dati MP di una specifico TYPE (es StatusMacchina,
|
|
/// StateMachineIngressi, ...)
|
|
/// </summary>
|
|
/// <param name="dataType"></param>
|
|
/// <returns></returns>
|
|
public static string mHash(string dataType)
|
|
{
|
|
return $"DATA:{dataType}";
|
|
}
|
|
|
|
/// <summary>
|
|
/// Hash dati OPT PARAMETERS x la macchina specificata
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <returns></returns>
|
|
public static string optParHash(string idxMacchina)
|
|
{
|
|
return mHash(string.Format("OptPar:{0}", idxMacchina));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Hash dati SAVED (EXE) TASK x la macchina specificata x poter ripristinare in caso di
|
|
/// perdita valore WRITE
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <returns></returns>
|
|
public static string savedTaskHash(string idxMacchina)
|
|
{
|
|
return mHash(string.Format("SavedTask:{0}", idxMacchina));
|
|
}
|
|
|
|
/// <summary>
|
|
/// verifica se sia da reinviare un task alla macchina dall'elenco di quelli salvati (in
|
|
/// modalità upsert) se non scaduti
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <param name="taskKey"></param>
|
|
/// <param name="taskVal"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> addCheckTask4Machine(string idxMacchina, taskType taskKey, string taskVal)
|
|
{
|
|
bool answ = false;
|
|
string currHash = exeTaskHash(idxMacchina);
|
|
Log.Info($"addCheckTask4Machine idxMacchina: {idxMacchina} | taskKey: {taskKey} | taskVal: {taskVal}");
|
|
try
|
|
{
|
|
Dictionary<string, string> savedTask = await mSavedTaskMacchina(idxMacchina);
|
|
// cerco valore saved
|
|
string savedVal = savedTask[taskKey.ToString()];
|
|
// se ho un valore != "" --> rimetto in coda di invio...
|
|
if (!string.IsNullOrEmpty(savedVal) && (savedVal != taskVal))
|
|
{
|
|
// leggo task attuali...
|
|
Dictionary<string, string> currTasks = await mTaskMacchina(idxMacchina);
|
|
// rimetto in task da eseguire...
|
|
currTasks[taskKey.ToString()] = savedVal;
|
|
// salvo in redis!
|
|
string rawData = JsonConvert.SerializeObject(currTasks);
|
|
await distributedCache.SetAsync(currHash, Encoding.UTF8.GetBytes(rawData));
|
|
Log.Info($"Re-issued task4machine | idxMacchina: {idxMacchina} | taskKey: {taskKey} | savedVal: {savedVal}");
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Errore in addCheckTask4Machine | idxMacchina: {idxMacchina} | taskKey: {taskKey} | taskVal: {taskVal}{Environment.NewLine}{exc}");
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Aggiunge un task all'elenco di quelli salvati (in modalità upsert)
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <param name="taskKey"></param>
|
|
/// <param name="taskVal"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> addTask4Machine(string idxMacchina, taskType taskKey, string taskVal)
|
|
{
|
|
bool answ = false;
|
|
string rawData = "";
|
|
string currHash = exeTaskHash(idxMacchina);
|
|
string currSavedParHash = savedTaskHash(idxMacchina);
|
|
Dictionary<string, string> currTasks = new Dictionary<string, string>();
|
|
Dictionary<string, string> savedTask = new Dictionary<string, string>();
|
|
try
|
|
{
|
|
Log.Info($"Request: idxMacchina: {idxMacchina} | taskKey: {taskKey} | taskVal: {taskVal}");
|
|
// leggo task attuali...
|
|
currTasks = await mTaskMacchina(idxMacchina);
|
|
if (currTasks.ContainsKey($"{taskKey}"))
|
|
{
|
|
currTasks[$"{taskKey}"] = taskVal;
|
|
}
|
|
else
|
|
{
|
|
currTasks.Add($"{taskKey}", taskVal);
|
|
}
|
|
// salvo in redis!
|
|
rawData = JsonConvert.SerializeObject(currTasks);
|
|
await distributedCache.SetAsync(currHash, Encoding.UTF8.GetBytes(rawData));
|
|
Log.Info($"Task ADD | idxMacchina: {idxMacchina} | taskKey: {taskKey} | taskVal: {taskVal}");
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Errore in remTask4Machine | idxMacchina: {idxMacchina} | taskKey: {taskKey} | taskVal: {taskVal}{Environment.NewLine}{exc}");
|
|
}
|
|
// verifico in base al tipo di task se fare backup...
|
|
switch (taskKey)
|
|
{
|
|
case taskType.setArt:
|
|
case taskType.setComm:
|
|
case taskType.setPzComm:
|
|
case taskType.setProg:
|
|
// leggo task SALVATI attuali...
|
|
savedTask = await mSavedTaskMacchina(idxMacchina);
|
|
savedTask[$"{taskKey}"] = taskVal;
|
|
// salvo in redis!
|
|
rawData = JsonConvert.SerializeObject(savedTask);
|
|
await distributedCache.SetAsync(currSavedParHash, Encoding.UTF8.GetBytes(rawData));
|
|
break;
|
|
|
|
case taskType.endProd:
|
|
// salvo un DICT vuoto x resettare
|
|
savedTask = new Dictionary<string, string>();
|
|
// salvo in redis!
|
|
rawData = JsonConvert.SerializeObject(savedTask);
|
|
await distributedCache.SetAsync(currSavedParHash, Encoding.UTF8.GetBytes(rawData));
|
|
break;
|
|
|
|
default:
|
|
break;
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
public async Task<List<AlarmLogModel>> AlarmLogGetFilt(int PlantId, int skipRec, int numRec)
|
|
{
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
var dbResult = dbController.AlarmLogGetFilt(PlantId, skipRec, numRec);
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB AlarmLogGetFilt: {ts.TotalMilliseconds} ms");
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
public async Task<bool> AlarmLogInsert(AlarmLogModel newItem)
|
|
{
|
|
bool fatto = await dbController.AlarmLogInsert(newItem);
|
|
DateTime adesso = DateTime.Now;
|
|
// se registrato --> invio email
|
|
if (fatto)
|
|
{
|
|
// Gestori!
|
|
string emailDest = "";
|
|
string emailSubj = "";
|
|
string emailBody = "";
|
|
StringBuilder sb = new StringBuilder();
|
|
|
|
List<PlantDTO> allPlants = await PlantDtoGetAll();
|
|
var currPlant = allPlants.Where(x => x.PlantId == newItem.PlantId).FirstOrDefault();
|
|
|
|
// inizio a comporre email
|
|
emailSubj = $"GWMS: warning/allarme registrato per impianto {currPlant.PlantDesc}";
|
|
sb.AppendLine($"Impianto interessato: <b>{currPlant.PlantDesc}</b>");
|
|
sb.AppendLine("");
|
|
if (newItem.Status > 0)
|
|
{
|
|
sb.AppendLine($"Allarme rilevato in area {newItem.MemAddress}/{newItem.Index} alle {adesso:yyyy.MM.dd HH:mm:ss}");
|
|
sb.AppendLine($"{newItem.ValDecoded}");
|
|
}
|
|
else
|
|
{
|
|
sb.AppendLine($"Allarme cessato per {newItem.MemAddress}/{newItem.Index} alle {adesso:yyyy.MM.dd HH:mm:ss}");
|
|
}
|
|
emailBody = sb.ToString().Replace(Environment.NewLine, "<br/>");
|
|
|
|
System.Security.Claims.Claim suppClaim = new System.Security.Claims.Claim("PlantId", $"{newItem.PlantId}");
|
|
|
|
// recupero elenco users associati al PLANT....
|
|
var rawUserList = UserDataGetFilt("").Result;
|
|
var plantUserList = rawUserList
|
|
.Where(x => x.Roles.Contains("User"))
|
|
.ToList();
|
|
//var plantList = await PlantDtoGetAll();
|
|
var userListSupp = plantUserList
|
|
.Where(x => x.Claims.Where(c => c.Type == "PlantId" && c.Value == $"{newItem.PlantId}").Count() > 0)
|
|
.ToList();
|
|
|
|
foreach (var user in userListSupp)
|
|
{
|
|
// invio email di notifica nuovi ordini inseriti
|
|
emailDest = user.Identity.Email;
|
|
#if RELEASE
|
|
// invio!
|
|
await _emailSender.SendEmailAsync(emailDest, emailSubj, emailBody);
|
|
#endif
|
|
_logger.LogInformation($"Email sento to PLANT USER {emailDest}!");
|
|
}
|
|
}
|
|
|
|
return fatto;
|
|
}
|
|
|
|
/// <summary>
|
|
/// effettua verifica x tutti i plant, se livello > livello riordino e NON ci sono ordini
|
|
/// APERTI in arrivo --> lancia ordine
|
|
/// </summary>
|
|
public async Task<bool> checkLevels()
|
|
{
|
|
bool fatto = false;
|
|
// effettuo verifica veto ricalcolo ordini da cache...
|
|
DateTime adesso = DateTime.Now;
|
|
DateTime vetoCheck = adesso.AddMinutes(1);
|
|
string cacheKey = "DATA:CHECKLEVEL";
|
|
string rawData;
|
|
try
|
|
{
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
// se non ho veto --> controllo
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
vetoCheck = JsonConvert.DeserializeObject<DateTime>(rawData);
|
|
}
|
|
else
|
|
{
|
|
vetoCheck = adesso.AddMinutes(-1);
|
|
}
|
|
if (adesso > vetoCheck)
|
|
{
|
|
fatto = await checkCreateOrders();
|
|
// imposto nuovo veto a 5 min...
|
|
vetoCheck = adesso.AddMinutes(5);
|
|
rawData = JsonConvert.SerializeObject(vetoCheck);
|
|
redisDataList = Encoding.UTF8.GetBytes(rawData);
|
|
await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(false));
|
|
}
|
|
}
|
|
catch
|
|
{ }
|
|
return fatto;
|
|
}
|
|
|
|
public async Task<List<GWMS.Data.DatabaseModels.ConfigModel>> ConfigGetAll()
|
|
{
|
|
//return Task.FromResult(dbController.ActionsGetAll());
|
|
List<GWMS.Data.DatabaseModels.ConfigModel> dbResult = new List<GWMS.Data.DatabaseModels.ConfigModel>();
|
|
string cacheKey = "DATA:CONFIG";
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
dbResult = JsonConvert.DeserializeObject<List<GWMS.Data.DatabaseModels.ConfigModel>>(rawData);
|
|
}
|
|
else
|
|
{
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetConfig();
|
|
rawData = JsonConvert.SerializeObject(dbResult);
|
|
redisDataList = Encoding.UTF8.GetBytes(rawData);
|
|
await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(false));
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB + caching per ConfigGetAll: {ts.TotalMilliseconds} ms");
|
|
}
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
public PlantLogModel convertFluxToPL(int plantId, flogData origData)
|
|
{
|
|
// cerco di ottenere un val in cifre
|
|
TimeSpan delta = origData.dtCurr.Subtract(origData.dtEve);
|
|
PlantLogModel answ = new PlantLogModel()
|
|
{
|
|
FluxType = origData.flux,
|
|
ValNumber = convStr2Double(origData.valore),
|
|
ValString = origData.valore,
|
|
PlantId = plantId,
|
|
DtEvent = DateTime.Now.Subtract(delta)
|
|
};
|
|
|
|
return answ;
|
|
}
|
|
|
|
public double convStr2Double(string origData)
|
|
{
|
|
double valDbl = 0;
|
|
NumberStyles style = NumberStyles.Number;
|
|
CultureInfo culture = CultureInfo.CreateSpecificCulture("it-IT");
|
|
string valString = origData;
|
|
// verifico SE contiene o meno la ","...
|
|
if (valString.IndexOf(',') > 0 && valString.IndexOf('.') > 0)
|
|
{
|
|
valString = origData.Replace(".", "");
|
|
}
|
|
else if (valString.IndexOf(',') < 0)
|
|
{
|
|
valString = origData.Replace(".", ",");
|
|
}
|
|
double.TryParse(valString, style, culture, out valDbl);
|
|
return valDbl;
|
|
}
|
|
|
|
public async Task<bool> DbForceMigrate()
|
|
{
|
|
return await Task.FromResult(dbController.DbForceMigrate());
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
// Clear database controller
|
|
dbController.Dispose();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Restitusice elenco PARAMETRI (da passare a IOB-WIN) per l'impianto indicato
|
|
/// </summary>
|
|
/// <param name="idxMacchina">Impianto richiesto</param>
|
|
/// <returns></returns>
|
|
public async Task<List<objItem>> getCurrObjItems(string idxMacchina)
|
|
{
|
|
List<objItem> answ = new List<objItem>();
|
|
List<objItem> outList = new List<objItem>();
|
|
// ORA recupero da memoria redis...
|
|
try
|
|
{
|
|
string cacheKey = currParametersHash(idxMacchina);
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
answ = JsonConvert.DeserializeObject<List<objItem>>(rawData);
|
|
// ordino!
|
|
outList = answ
|
|
.OrderByDescending(x => x.writable)
|
|
.ThenBy(x => x.name)
|
|
.ToList();
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Info($"Errore in recupero ParametriMacchinaGet | idxMacchina {idxMacchina}{Environment.NewLine}{exc}");
|
|
}
|
|
return outList;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Restitusice elenco PARAMETRI che richiedono una WRITE x IOB
|
|
/// </summary>
|
|
/// <param name="idxMacchina">Impianto richiesto</param>
|
|
/// <returns></returns>
|
|
public async Task<List<objItem>> getCurrObjItemsPendigWrite(string idxMacchina)
|
|
{
|
|
List<objItem> actValues = new List<objItem>();
|
|
List<objItem> writeValues = new List<objItem>();
|
|
// ORA recupero da memoria redis...
|
|
try
|
|
{
|
|
string cacheKey = currParametersHash(idxMacchina);
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
actValues = JsonConvert.DeserializeObject<List<objItem>>(rawData);
|
|
// cerco e rimuovo parametri sola lettura o SENZA richieste scrittura
|
|
foreach (var item in actValues)
|
|
{
|
|
if (item.writable && !string.IsNullOrEmpty(item.reqValue))
|
|
{
|
|
writeValues.Add(item);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Info($"Errore in recupero ParametriMacchinaWriteGet | idxMacchina {idxMacchina}{Environment.NewLine}{exc}");
|
|
}
|
|
return writeValues;
|
|
}
|
|
|
|
public async Task<bool> HasPlantLog()
|
|
{
|
|
return await Task.FromResult(dbController.HasPlantLog());
|
|
}
|
|
|
|
/// <summary>
|
|
/// invalida tutta la cache in caso di update
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public async Task InvalidateAllCache()
|
|
{
|
|
await distributedCache.RemoveAsync("DATA:CONFIG");
|
|
await distributedCache.RemoveAsync("DATA:CHECKLEVEL");
|
|
await distributedCache.RemoveAsync("DATA:PLANTS:ListDTO");
|
|
await distributedCache.RemoveAsync("DATA:PLANTS:VetoReadDto");
|
|
await distributedCache.RemoveAsync("DATA:SUPPL:List");
|
|
await distributedCache.RemoveAsync("DATA:TRANSP:List");
|
|
await distributedCache.RemoveAsync("DATA:WEEKPLAN:List");
|
|
await distributedCache.RemoveAsync("ParamSend:List");
|
|
}
|
|
|
|
public async Task<List<GWMS.Data.DatabaseModels.ItemModel>> ItemsGetAll()
|
|
{
|
|
//return Task.FromResult(dbController.ActionsGetAll());
|
|
List<GWMS.Data.DatabaseModels.ItemModel> dbResult = new List<GWMS.Data.DatabaseModels.ItemModel>();
|
|
string cacheKey = "DATA:ITEMS";
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
dbResult = JsonConvert.DeserializeObject<List<GWMS.Data.DatabaseModels.ItemModel>>(rawData);
|
|
}
|
|
else
|
|
{
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetItems();
|
|
rawData = JsonConvert.SerializeObject(dbResult);
|
|
redisDataList = Encoding.UTF8.GetBytes(rawData);
|
|
await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(false));
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB + caching per ItemsGetAll: {ts.TotalMilliseconds} ms");
|
|
}
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Restitusice elenco KVP dei TASK (da passare a IOB-WIN) per l'impianto indicato
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <returns></returns>
|
|
public async Task<Dictionary<string, string>> mOptParMacchina(string idxMacchina)
|
|
{
|
|
// hard coded dimensione vettore DatiMacchine
|
|
Dictionary<string, string> answ = new Dictionary<string, string>();
|
|
// ORA recupero da memoria redis...
|
|
try
|
|
{
|
|
string currHash = optParHash(idxMacchina);
|
|
var redisDataList = await distributedCache.GetAsync(currHash);
|
|
if (redisDataList != null)
|
|
{
|
|
string rawData = Encoding.UTF8.GetString(redisDataList);
|
|
answ = JsonConvert.DeserializeObject<Dictionary<string, string>>(rawData);
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Errore in compilazione dati OPT PARAM mOptParMacchina | idxMacchina {idxMacchina}{Environment.NewLine}{exc}");
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Restitusice elenco KVP dei TASK SALVATI (da passare a IOB-WIN) per l'impianto indicato
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <returns></returns>
|
|
public async Task<Dictionary<string, string>> mSavedTaskMacchina(string idxMacchina)
|
|
{
|
|
// hard coded dimensione vettore DatiMacchine
|
|
Dictionary<string, string> answ = new Dictionary<string, string>();
|
|
// ORA recupero da memoria redis...
|
|
try
|
|
{
|
|
string cacheKey = savedTaskHash(idxMacchina);
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
answ = JsonConvert.DeserializeObject<Dictionary<string, string>>(rawData);
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Errore in recupero dati SAVED TASK x Redis mSavedTaskMacchina | idxMacchina {idxMacchina}{Environment.NewLine}{exc}");
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Restitusice elenco KVP dei TASK (da passare a IOB-WIN) per l'impianto indicato
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <returns></returns>
|
|
public async Task<Dictionary<string, string>> mTaskMacchina(string idxMacchina)
|
|
{
|
|
// hard coded dimensione vettore DatiMacchine
|
|
Dictionary<string, string> answ = new Dictionary<string, string>();
|
|
// ORA recupero da memoria redis...
|
|
try
|
|
{
|
|
string cacheKey = exeTaskHash(idxMacchina);
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
string rawData = Encoding.UTF8.GetString(redisDataList);
|
|
answ = JsonConvert.DeserializeObject<Dictionary<string, string>>(rawData);
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Errore in recupero dati EXE TASK x Redis mTaskMacchina | idxMacchina: {idxMacchina}{Environment.NewLine}{exc}");
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Cancellazione Ordine consegna GAS
|
|
/// </summary>
|
|
/// <param name="currItem"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> OrderDelete(OrderModel currItem)
|
|
{
|
|
bool done = false;
|
|
try
|
|
{
|
|
done = dbController.OrderDelete(currItem);
|
|
await InvalidateAllCache();
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Eccezione in OrderDelete:{Environment.NewLine}{exc}");
|
|
}
|
|
return await Task.FromResult(done);
|
|
}
|
|
|
|
public async Task<OrderModel> OrderGetByCode(string OrderCode)
|
|
{
|
|
OrderModel dbResult = new OrderModel();
|
|
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetOrderByCode(OrderCode);
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB per OrderGetByCode: {ts.TotalMilliseconds} ms");
|
|
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
public async Task<OrderModel> OrderGetById(int OrderId)
|
|
{
|
|
OrderModel dbResult = new OrderModel();
|
|
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetOrderById(OrderId);
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB per OrderGetById: {ts.TotalMilliseconds} ms");
|
|
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
public async Task<List<OrderModel>> OrdersGetFilt(SelectOrderData CurrFilter)
|
|
{
|
|
List<OrderModel> dbResult = new List<OrderModel>();
|
|
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetOrdersFilt(CurrFilter.PlantId, CurrFilter.SupplierId, CurrFilter.TransporterId, CurrFilter.DateStart, CurrFilter.DateEnd, CurrFilter.ShowClosed);
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB per OrdersGetFilt: {ts.TotalMilliseconds} ms");
|
|
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Elenco degli ordini ancora aperti x il Plant
|
|
/// </summary>
|
|
/// <param name="CurrFilter"></param>
|
|
/// <returns></returns>
|
|
public async Task<List<OrderModel>> OrdersGetOpen(int PlantId)
|
|
{
|
|
List<OrderModel> dbResult = new List<OrderModel>();
|
|
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetOrdersOpen(PlantId);
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB per OrdersGetOpen | PlantId: {PlantId} | {ts.TotalMilliseconds} ms");
|
|
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Aggiornamento ordine
|
|
/// </summary>
|
|
/// <param name="currItem"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> OrderUpdate(OrderModel currItem)
|
|
{
|
|
bool done = false;
|
|
try
|
|
{
|
|
done = dbController.OrderUpdate(currItem);
|
|
await InvalidateAllCache();
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Eccezione in OrderUpdate:{Environment.NewLine}{exc}");
|
|
}
|
|
return await Task.FromResult(done);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Elenco di TUTTI i parametri send gestiti
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public async Task<ParamSendModel> ParamSendGet(int PlantId, string ParamUid)
|
|
{
|
|
ParamSendModel currRecord = dbController.ParamSendGet(PlantId, ParamUid);
|
|
return await Task.FromResult(currRecord);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Elenco di TUTTI i parametri send gestiti
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public async Task<List<ParamSendModel>> ParamSendGetAll()
|
|
{
|
|
List<ParamSendModel> dbResult = new List<ParamSendModel>();
|
|
string cacheKey = "ParamSend:List";
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
dbResult = JsonConvert.DeserializeObject<List<ParamSendModel>>(rawData);
|
|
}
|
|
else
|
|
{
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.ParamSendGetAll();
|
|
rawData = JsonConvert.SerializeObject(dbResult);
|
|
redisDataList = Encoding.UTF8.GetBytes(rawData);
|
|
await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(false));
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB + caching per ParamSendGetAll: {ts.TotalMilliseconds} ms");
|
|
}
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Aggiornamento ParamSend record
|
|
/// </summary>
|
|
/// <param name="currItem"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> ParamSendUpdate(ParamSendModel currItem)
|
|
{
|
|
bool done = false;
|
|
try
|
|
{
|
|
done = dbController.ParamSendUpdate(currItem);
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Eccezione in ParamSendUpdate:{Environment.NewLine}{exc}");
|
|
}
|
|
return await Task.FromResult(done);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ottiene il valore calcolato x il parametro richiesto al momento della richiesta
|
|
/// </summary>
|
|
/// <param name="PlantId"></param>
|
|
/// <param name="ParamUid"></param>
|
|
/// <returns></returns>
|
|
public async Task<decimal> ParamSetCalcVal(int PlantId, string ParamUid)
|
|
{
|
|
decimal answ = 0;
|
|
List<ParamSetModel> ListRecords = await ParamSetGetFilt(PlantId, ParamUid);
|
|
if (ListRecords != null && ListRecords.Count > 1)
|
|
{
|
|
// prendo i 2 valori precedente e successivo
|
|
DateTime oggi = DateTime.Today;
|
|
var prevPar = ListRecords.Where(x => x.Scadenza <= oggi).OrderByDescending(x => x.Scadenza).FirstOrDefault();
|
|
var nextPar = ListRecords.Where(x => x.Scadenza >= oggi).OrderBy(x => x.Scadenza).FirstOrDefault();
|
|
// se ho valori
|
|
if (prevPar != null && nextPar != null)
|
|
{
|
|
double num = oggi.Subtract(prevPar.Scadenza).TotalDays;
|
|
double den = nextPar.Scadenza.Subtract(prevPar.Scadenza).TotalDays;
|
|
den = den != 0 ? den : 1;
|
|
answ = prevPar.TargetVal + (nextPar.TargetVal - prevPar.TargetVal) * (decimal)(num / den);
|
|
// 2023.09.05 controllo valore ammissibile (compreso tra min/max)
|
|
decimal minVal = Math.Min(prevPar.TargetVal, nextPar.TargetVal);
|
|
decimal maxVal = Math.Max(prevPar.TargetVal, nextPar.TargetVal);
|
|
answ = Math.Min(maxVal, answ);
|
|
answ = Math.Max(minVal, answ);
|
|
}
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Cancellazione ParamSet
|
|
/// </summary>
|
|
/// <param name="currItem"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> ParamSetDelete(ParamSetModel currItem)
|
|
{
|
|
bool done = false;
|
|
try
|
|
{
|
|
done = dbController.ParamSetDelete(currItem);
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Eccezione in ParamSetDelete:{Environment.NewLine}{exc}");
|
|
}
|
|
return await Task.FromResult(done);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Recupera ParamSet dato plant e UID parametro
|
|
/// </summary>
|
|
/// <param name="PlantId"></param>
|
|
/// <returns></returns>
|
|
public async Task<List<ParamSetModel>> ParamSetGetFilt(int PlantId, string ParamUid)
|
|
{
|
|
List<ParamSetModel> dbResult = new List<ParamSetModel>();
|
|
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.ParamSetGet(PlantId, ParamUid);
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB per ParamSetGetByPlant: {ts.TotalMilliseconds} ms");
|
|
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Aggiornamento ParamSet
|
|
/// </summary>
|
|
/// <param name="currItem"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> ParamSetUpdate(ParamSetModel currItem)
|
|
{
|
|
bool done = false;
|
|
if (currItem != null)
|
|
{
|
|
try
|
|
{
|
|
done = dbController.ParamSetUpdate(currItem);
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Eccezione in ParamSetUpdate:{Environment.NewLine}{exc}");
|
|
}
|
|
}
|
|
return await Task.FromResult(done);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua verifica parametri da inviare ed eventualmente invia
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public async Task<bool> ParamsSendCheck()
|
|
{
|
|
bool answ = false;
|
|
// prima di tutto invalido cache dei parametri...
|
|
await distributedCache.RemoveAsync("ParamSend:List");
|
|
DateTime adesso = DateTime.Now;
|
|
var currParams = await ParamSendGetAll();
|
|
// ciclo x tutti dove siano attivi e NON ci fosse veto
|
|
var activeParams = currParams
|
|
.Where(x => x.enabled && x.VetoSend <= adesso)
|
|
.ToList();
|
|
if (activeParams != null && activeParams.Count > 0)
|
|
{
|
|
foreach (var item in activeParams)
|
|
{
|
|
await ParamsSetCheck(item.PlantId, item.ParamUid);
|
|
// recupero valore...
|
|
var newVal = await ParamSetCalcVal(item.PlantId, item.ParamUid);
|
|
// registro richiesta
|
|
bool fatto = await updateMachineParameter(item.PlantId, item.ParamUid, $"{newVal:N3}");
|
|
// registro nuovo veto
|
|
if (fatto)
|
|
{
|
|
// rand attesa...
|
|
Random rnd = new Random();
|
|
DateTime vetoSend = DateTime.Today.AddDays(1).AddHours(item.windStart + rnd.NextDouble() * (item.windEnd - item.windStart));
|
|
// salvo!
|
|
item.LastSend = adesso;
|
|
item.VetoSend = vetoSend;
|
|
await ParamSendUpdate(item);
|
|
}
|
|
}
|
|
}
|
|
|
|
// alla fine di nuovo invalido cache dei parametri...
|
|
await distributedCache.RemoveAsync("ParamSend:List");
|
|
return await Task.FromResult(answ);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua verifica parametri SET ed eventualmente aggiorna (deve esserci 1 record futuro
|
|
/// ed 1 passato x interpolare)
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public async Task<bool> ParamsSetCheck(int PlantId, string ParamUid)
|
|
{
|
|
bool answ = false;
|
|
// elenco parametri set...
|
|
List<ParamSetModel> ListRecords = await ParamSetGetFilt(PlantId, ParamUid);
|
|
// per invecchiare DEVONO essere almeno 2
|
|
if (ListRecords != null && ListRecords.Count > 1)
|
|
{
|
|
// cerco se ci sia 1 valore successivo...
|
|
DateTime oggi = DateTime.Today;
|
|
var nextPar = ListRecords.Where(x => x.Scadenza >= oggi).OrderBy(x => x.Scadenza).FirstOrDefault();
|
|
if (nextPar == null)
|
|
{
|
|
// prendo il valore + vecchio e lo sposto avanti 1 anno...
|
|
var oldestPar = ListRecords.Where(x => x.Scadenza <= oggi).OrderBy(x => x.Scadenza).FirstOrDefault();
|
|
oldestPar.Scadenza = oldestPar.Scadenza.AddYears(1);
|
|
// salvo!
|
|
await ParamSetUpdate(oldestPar);
|
|
}
|
|
answ = true;
|
|
}
|
|
return await Task.FromResult(answ);
|
|
}
|
|
|
|
public async Task<List<PlantDTO>> PlantDtoGetAll()
|
|
{
|
|
List<PlantDTO> dbResult = new List<PlantDTO>();
|
|
string cacheVetoKey = "DATA:PLANTS:VetoReadDto";
|
|
string rawData;
|
|
var rand = new Random();
|
|
// controllo se ci sia semaforo lettura
|
|
var redVeto = await distributedCache.GetAsync(cacheVetoKey);
|
|
// attendo sino a che non ho scadenza blocco richiesta...
|
|
while (redVeto != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redVeto);
|
|
var vetoDt = JsonConvert.DeserializeObject<DateTime>(rawData);
|
|
if (vetoDt < DateTime.Now)
|
|
{
|
|
await distributedCache.RemoveAsync("DATA:PLANTS:VetoReadDto");
|
|
Log.Info("Fine veto attesa");
|
|
redVeto = null;
|
|
}
|
|
else
|
|
{
|
|
Log.Trace($"Veto attivo per PlantDtoGetAll: salto!");
|
|
// controllo se ci sia semaforo lettura
|
|
redVeto = await distributedCache.GetAsync(cacheVetoKey);
|
|
// se scaduto da oltre 10 sec --> tolgo
|
|
//attendo
|
|
await Task.Delay(1000 * rand.Next(1, 5));
|
|
}
|
|
}
|
|
|
|
// inserisco veto x bloccare!
|
|
var vetoData = JsonConvert.SerializeObject(DateTime.Now.AddSeconds(5));
|
|
var serVetoData = Encoding.UTF8.GetBytes(vetoData);
|
|
await distributedCache.SetAsync(cacheVetoKey, serVetoData, cacheOptFast(true));
|
|
// proseguo con la vera lettura e serializzazione
|
|
string cacheKey = "DATA:PLANTS:ListDTO";
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
dbResult = JsonConvert.DeserializeObject<List<PlantDTO>>(rawData);
|
|
Log.Trace($"PlantDtoGetAll: lettura da cache REDIS");
|
|
}
|
|
else
|
|
{
|
|
// metto semaforo lettura x 30 sec...
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
int maxRec = 100;
|
|
int.TryParse(_configuration["MaxLogRecord"], out maxRec);
|
|
dbResult = dbController.GetPlantsDTO(maxRec);
|
|
rawData = JsonConvert.SerializeObject(dbResult);
|
|
redisDataList = Encoding.UTF8.GetBytes(rawData);
|
|
await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true));
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Info($"Effettuata lettura da DB + caching per PlantDtoGetAll: {ts.TotalMilliseconds} ms");
|
|
}
|
|
// elimino veto!
|
|
await distributedCache.RemoveAsync("DATA:PLANTS:VetoReadDto");
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
public async Task<PlantDTO> PlantDtoGetByCode(string PlantCode)
|
|
{
|
|
PlantDTO answ = new PlantDTO();
|
|
var ListRecords = await PlantDtoGetAll();
|
|
var found = ListRecords.Where(x => x.PlantCode == PlantCode).FirstOrDefault();
|
|
if (found != null)
|
|
{
|
|
answ = found;
|
|
}
|
|
return await Task.FromResult(answ);
|
|
}
|
|
|
|
public async Task<List<PlantLogModel>> PlantLogGetFilt(int PlantId, DateTime DtMaxDate, int numRec)
|
|
{
|
|
List<PlantLogModel> dbResult = new List<PlantLogModel>();
|
|
string cacheKey = $"DATA:PLANTS:LOGS:{PlantId}:{DtMaxDate:yyyyMMddHHmm}:{numRec}";
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
dbResult = JsonConvert.DeserializeObject<List<PlantLogModel>>(rawData);
|
|
}
|
|
else
|
|
{
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetPlantLog(PlantId, DtMaxDate, numRec);
|
|
rawData = JsonConvert.SerializeObject(dbResult);
|
|
redisDataList = Encoding.UTF8.GetBytes(rawData);
|
|
await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true));
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB + caching per PlantLogGetFilt: {ts.TotalMilliseconds} ms");
|
|
}
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
public async Task<bool> PlantLogInsert(List<PlantLogModel> newItems)
|
|
{
|
|
bool fatto = false;
|
|
// init valori
|
|
int IntervalMin = 60;
|
|
int.TryParse(_configuration["IntervalMin"], out IntervalMin);
|
|
List<PlantLogModel> item2insert = new List<PlantLogModel>();
|
|
int PlantId = newItems.FirstOrDefault().PlantId;
|
|
// aggiorno valori ACT x DTO
|
|
await updateCurrDTO(newItems);
|
|
|
|
// recupero ultimi inseriti
|
|
List<PlantLogModel> lastValues = PlantLogGetLastByFlux(PlantId).Result;
|
|
// verifico i flussi presenti tra quelli ricevuti
|
|
List<string> fluxList = newItems
|
|
.GroupBy(g => g.FluxType)
|
|
.Select(s => s.First().FluxType)
|
|
.ToList();
|
|
|
|
foreach (var item in fluxList)
|
|
{
|
|
// cerco se c'è valore...
|
|
var lastInserted = lastValues.Where(x => x.FluxType == item).FirstOrDefault();
|
|
DateTime dateLimit = DateTime.Today.AddDays(-1);
|
|
if (lastInserted != null)
|
|
{
|
|
// per ogni flusso calcolo il valore minimo x inserimento (arrotondando a minInt)
|
|
dateLimit = dbController.DateRoundEnd(lastInserted.DtEvent, IntervalMin);
|
|
}
|
|
|
|
// cerco se ho record > valore minimo x ogni flusso ricevuto
|
|
List<PlantLogModel> insCandidates = newItems.Where(x => x.FluxType == item && x.DtEvent >= dateLimit).OrderBy(x => x.DtEvent).ToList();
|
|
|
|
int num2ins = insCandidates.Count;
|
|
while (num2ins > 0)
|
|
{
|
|
var newRec = insCandidates.First();
|
|
// il primo lo accodo da inserire
|
|
item2insert.Add(newRec);
|
|
// calcolo nuovo veto
|
|
dateLimit = dbController.DateRoundEnd(newRec.DtEvent, IntervalMin);
|
|
// ...e se ho record > data limite accodo
|
|
insCandidates = newItems.Where(x => x.FluxType == item && x.DtEvent > dateLimit).OrderBy(x => x.DtEvent).ToList();
|
|
num2ins = insCandidates.Count;
|
|
}
|
|
}
|
|
|
|
// se ho record da inserire...
|
|
if (item2insert.Count > 0)
|
|
{
|
|
// faccio vero insert
|
|
fatto = dbController.PlantLogInsertNew(item2insert);
|
|
|
|
// invalido i vari valori in cache
|
|
await distributedCache.RemoveAsync($"DATA:PLANTS:LastFlux:{PlantId}");
|
|
await distributedCache.RemoveAsync($"DATA:PLANTS:ListDTO");
|
|
Log.Trace($"PlantLogInsert | PlantId: {PlantId} | Completato insert {item2insert.Count} rec");
|
|
}
|
|
|
|
// restituisco
|
|
return await Task.FromResult(fatto);
|
|
}
|
|
|
|
public async Task<List<PlantLevSumDTO>> PlantsAnalisysGetByCode(SelectOrderData CurrFilter)
|
|
{
|
|
List<PlantLevSumDTO> dbResult = new List<PlantLevSumDTO>();
|
|
string cacheKey = $"DATA:PLANTS:LevelSum:{CurrFilter.PlantId}:{CurrFilter.DateStart:yyMMdd}:{CurrFilter.DateEnd:yyMMdd}";
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
dbResult = JsonConvert.DeserializeObject<List<PlantLevSumDTO>>(rawData);
|
|
}
|
|
else
|
|
{
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetPlantLogSummary(CurrFilter.PlantId, CurrFilter.DateStart, CurrFilter.DateEnd);
|
|
rawData = JsonConvert.SerializeObject(dbResult);
|
|
redisDataList = Encoding.UTF8.GetBytes(rawData);
|
|
await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true));
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB + caching per PlantsAnalisysGetByCode: {ts.TotalMilliseconds} ms");
|
|
}
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
public async Task<bool> PlantsAnalisysReset(SelectOrderData CurrFilter)
|
|
{
|
|
bool answ = false;
|
|
string cacheKey = $"DATA:PLANTS:LevelSum:{CurrFilter.PlantId}:{CurrFilter.DateStart:yyMMdd}:{CurrFilter.DateEnd:yyMMdd}";
|
|
await distributedCache.RemoveAsync(cacheKey);
|
|
answ = true;
|
|
return await Task.FromResult(answ);
|
|
}
|
|
|
|
public async Task<PlantDetailModel> PlantsGetByCode(string PlantCode)
|
|
{
|
|
PlantDetailModel answ = new PlantDetailModel();
|
|
var ListRecords = await PlantsList();
|
|
var found = ListRecords.Where(x => x.PlantCode == PlantCode).FirstOrDefault();
|
|
if (found != null)
|
|
{
|
|
answ = found;
|
|
}
|
|
return await Task.FromResult(answ);
|
|
}
|
|
|
|
public async Task<List<PlantDetailModel>> PlantsList()
|
|
{
|
|
List<PlantDetailModel> dbResult = new List<PlantDetailModel>();
|
|
string cacheKey = "DATA:PLANTS:ListModel";
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
dbResult = JsonConvert.DeserializeObject<List<PlantDetailModel>>(rawData);
|
|
}
|
|
else
|
|
{
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetPlants();
|
|
rawData = JsonConvert.SerializeObject(dbResult);
|
|
redisDataList = Encoding.UTF8.GetBytes(rawData);
|
|
await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true));
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB + caching per PlantsList: {ts.TotalMilliseconds} ms");
|
|
}
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
public async Task<bool> PlantUpdate(PlantDTO currItem)
|
|
{
|
|
bool done = false;
|
|
try
|
|
{
|
|
done = dbController.PlantUpdate(currItem);
|
|
await InvalidateAllCache();
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Eccezione in OrderUpdate:{Environment.NewLine}{exc}");
|
|
}
|
|
return await Task.FromResult(done);
|
|
}
|
|
|
|
public void RebootLogInsert(RebootLogModel newItem)
|
|
{
|
|
try
|
|
{
|
|
dbController.RecordRebootLog(newItem);
|
|
}
|
|
catch
|
|
{ }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Rimuove un item da parametri correnti x IOB
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <param name="currValues"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> remObjItem(string idxMacchina, objItem item2rem)
|
|
{
|
|
bool answ = false;
|
|
if (item2rem != null)
|
|
{
|
|
string cacheKey = currParametersHash(idxMacchina);
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
var actValues = JsonConvert.DeserializeObject<List<objItem>>(rawData);
|
|
// cerco e rimuovo
|
|
var remCand = actValues
|
|
.Where(x => x.uid == item2rem.uid)
|
|
.FirstOrDefault();
|
|
if (remCand != null)
|
|
{
|
|
actValues.Remove(remCand);
|
|
}
|
|
// salvo!
|
|
rawData = JsonConvert.SerializeObject(actValues);
|
|
await distributedCache.SetAsync(cacheKey, Encoding.UTF8.GetBytes(rawData));
|
|
}
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// RIMUOVE un PARAMETRO OPZIONALE dall'elenco di quelli salvati
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <param name="taskKey"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> remOptPar4Machine(string idxMacchina, string taskKey)
|
|
{
|
|
bool answ = false;
|
|
string currHash = optParHash(idxMacchina);
|
|
try
|
|
{
|
|
// leggo task attuali...
|
|
var currVal = await mOptParMacchina(idxMacchina);
|
|
currVal.Remove(taskKey);
|
|
// salvo in redis!
|
|
string rawData = JsonConvert.SerializeObject(currVal);
|
|
await distributedCache.SetAsync(currHash, Encoding.UTF8.GetBytes(rawData));
|
|
}
|
|
catch { }
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// RIMUOVE un task dall'elenco di quelli salvati
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <param name="taskKey"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> remTask4Machine(string idxMacchina, taskType taskKey)
|
|
{
|
|
bool answ = false;
|
|
string currHash = exeTaskHash(idxMacchina);
|
|
try
|
|
{
|
|
// leggo task attuali...
|
|
var currTasks = await mTaskMacchina(idxMacchina);
|
|
// cerco se chiave esiste -_> sostituisco
|
|
if (currTasks.ContainsKey($"{taskKey}"))
|
|
{
|
|
currTasks.Remove($"{taskKey}");
|
|
// salvo in redis!
|
|
string rawData = JsonConvert.SerializeObject(currTasks);
|
|
await distributedCache.SetAsync(currHash, Encoding.UTF8.GetBytes(rawData));
|
|
Log.Info($"Task REM | idxMacchina: {idxMacchina} | taskKey: {taskKey}");
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Errore in remTask4Machine | idxMacchina: {idxMacchina} | taskKey: {taskKey}{Environment.NewLine}{exc}");
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
public void rollBackEdit(object item)
|
|
{
|
|
dbController.rollBackEntity(item);
|
|
}
|
|
|
|
/// <summary>
|
|
/// salva la conf di memoria della amcchina in redis
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <param name="currMap"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> saveMemMap(string idxMacchina, plcMemMap currMap)
|
|
{
|
|
bool answ = false;
|
|
if (currMap != null)
|
|
{
|
|
string currHash = currMamMapHash(idxMacchina);
|
|
// salvo in redis!
|
|
string rawData = JsonConvert.SerializeObject(currMap);
|
|
await distributedCache.SetAsync(currHash, Encoding.UTF8.GetBytes(rawData));
|
|
answ = true;
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// SET elenco parametri correnti x IOB
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <param name="currValues"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> setCurrObjItems(string idxMacchina, List<objItem> currValues)
|
|
{
|
|
bool answ = false;
|
|
taskType currTask = taskType.nihil;
|
|
if (currValues != null)
|
|
{
|
|
string currHash = currParametersHash(idxMacchina);
|
|
// salvo in redis!
|
|
string rawData = JsonConvert.SerializeObject(currValues);
|
|
await distributedCache.SetAsync(currHash, Encoding.UTF8.GetBytes(rawData));
|
|
// controllo se ha valori write...
|
|
foreach (var item in currValues)
|
|
{
|
|
// se fosse un valore WRITE e mi ha dato un valore vuoto --> mando un fix x riscrittura
|
|
if (item.writable && string.IsNullOrEmpty(item.value))
|
|
{
|
|
currTask = taskType.nihil;
|
|
// verifico se si tratti di un task da salvare....
|
|
if (Enum.TryParse(item.uid, true, out currTask))
|
|
{
|
|
if (Enum.IsDefined(typeof(taskType), currTask))
|
|
{
|
|
currTask = (taskType)Enum.Parse(typeof(taskType), item.uid);
|
|
await addCheckTask4Machine(idxMacchina, currTask, item.value);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
answ = true;
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
public async Task<List<SupplierModel>> SuppliersGetAll()
|
|
{
|
|
List<SupplierModel> dbResult = new List<SupplierModel>();
|
|
string cacheKey = "DATA:SUPPL:List";
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
dbResult = JsonConvert.DeserializeObject<List<SupplierModel>>(rawData);
|
|
}
|
|
else
|
|
{
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetSuppliers();
|
|
rawData = JsonConvert.SerializeObject(dbResult);
|
|
redisDataList = Encoding.UTF8.GetBytes(rawData);
|
|
await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true));
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB + caching per PlantDtoGetAll: {ts.TotalMilliseconds} ms");
|
|
}
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
public async Task<bool> TestSendEmail(string destEmail, string oggetto, string corpo)
|
|
{
|
|
bool answ = false;
|
|
try
|
|
{
|
|
await _emailSender.SendEmailAsync(destEmail, oggetto, corpo);
|
|
answ = true;
|
|
}
|
|
catch
|
|
{ }
|
|
|
|
return answ;
|
|
}
|
|
|
|
public async Task<List<TransporterModel>> TransportersGetAll()
|
|
{
|
|
List<TransporterModel> dbResult = new List<TransporterModel>();
|
|
string cacheKey = $"DATA:TRANSP:List";
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
dbResult = JsonConvert.DeserializeObject<List<TransporterModel>>(rawData);
|
|
}
|
|
else
|
|
{
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetTransporters();
|
|
rawData = JsonConvert.SerializeObject(dbResult);
|
|
redisDataList = Encoding.UTF8.GetBytes(rawData);
|
|
await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true));
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB + caching per PlantDtoGetAll: {ts.TotalMilliseconds} ms");
|
|
}
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Aggiornamento parametro per macchina
|
|
/// </summary>
|
|
/// <param name="PlantId"></param>
|
|
/// <param name="Original_uid">Parametro macchina come definito in file json</param>
|
|
/// <param name="reqValue"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> updateMachineParameter(int PlantId, string Original_uid, string reqValue)
|
|
{
|
|
bool fatto = false;
|
|
var plantList = await PlantDtoGetAll();
|
|
var currPlant = plantList
|
|
.Where(x => x.PlantId == PlantId)
|
|
.FirstOrDefault();
|
|
if (currPlant != null)
|
|
{
|
|
fatto = await updateMachineParameter(currPlant.PlantCode, Original_uid, reqValue);
|
|
}
|
|
return fatto;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Aggiornamento parametro per macchina
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <param name="Original_uid">Parametro macchina come definito in file json</param>
|
|
/// <param name="reqValue"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> updateMachineParameter(string idxMacchina, string Original_uid, string reqValue)
|
|
{
|
|
bool answ = false;
|
|
// recupero items...
|
|
List<objItem> dcList = await getCurrObjItems(idxMacchina);
|
|
List<objItem> list2Update = new List<objItem>();
|
|
// cerco quello da aggiornare
|
|
objItem trovato = dcList.Find(obj => obj.uid == Original_uid);
|
|
// se non trova --> crea ed aggiunge...
|
|
if (trovato == null)
|
|
{
|
|
dcList.Add(new objItem() { uid = Original_uid });
|
|
trovato = dcList.Find(obj => obj.uid == Original_uid);
|
|
}
|
|
|
|
// se trovato procedo
|
|
if (trovato != null)
|
|
{
|
|
// aggiorno valore richiesto + dt richiesta
|
|
trovato.reqValue = reqValue;
|
|
trovato.lastRequest = DateTime.Now;
|
|
list2Update.Add(trovato);
|
|
await upsertCurrObjItems(idxMacchina, list2Update);
|
|
// accodo in Task2Exe la richiesta di processing
|
|
await addTask4Machine(idxMacchina, taskType.setParameter, trovato.uid);
|
|
|
|
if (Enum.IsDefined(typeof(taskType), trovato.uid))
|
|
{
|
|
// salvo ANCHE il valore di setup ASSOCIATO...
|
|
taskType currTask = (taskType)Enum.Parse(typeof(taskType), trovato.uid);
|
|
await addTask4Machine(idxMacchina, currTask, reqValue);
|
|
}
|
|
|
|
answ = true;
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua UPSERT elenco parametri correnti x IOB (se c'è UPDATE, se manca ADD)
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <param name="innovations"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> upsertCurrObjItems(string idxMacchina, List<objItem> innovations)
|
|
{
|
|
bool answ = false;
|
|
if (innovations != null)
|
|
{
|
|
string currHash = currParametersHash(idxMacchina);
|
|
// leggo i valori attuali...
|
|
List<objItem> actValues = await getCurrObjItems(idxMacchina);
|
|
var oldUid = actValues.Select(x => x.uid).Intersect(innovations.Select(i => i.uid)).ToList();
|
|
actValues.RemoveAll(x => oldUid.Contains(x.uid));
|
|
innovations.AddRange(actValues);
|
|
// serializzo e salvo
|
|
string serVal = JsonConvert.SerializeObject(innovations);
|
|
await distributedCache.SetAsync(currHash, Encoding.UTF8.GetBytes(serVal));
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
public async Task<List<UserData>> UserDataGetFilt(string searchVal)
|
|
{
|
|
// Collezione utenti
|
|
List<IdentityUser> RawList = new List<IdentityUser>();
|
|
List<UserData> UsersList = new List<UserData>();
|
|
// recupero utenti da obj _userManager
|
|
var allData = _userManager.Users.ToList();
|
|
if (!string.IsNullOrEmpty(searchVal))
|
|
{
|
|
RawList = allData.Where(x => x.NormalizedEmail.Contains(searchVal.ToUpper()) || x.NormalizedUserName.Contains(searchVal.ToUpper())).ToList();
|
|
}
|
|
else
|
|
{
|
|
RawList = allData;
|
|
}
|
|
var user = RawList.Select(x => new IdentityUser
|
|
{
|
|
Id = x.Id,
|
|
UserName = x.UserName,
|
|
Email = x.Email,
|
|
PhoneNumber = x.PhoneNumber,
|
|
PasswordHash = "*****",
|
|
EmailConfirmed = x.EmailConfirmed
|
|
}).ToList();
|
|
|
|
foreach (var item in user)
|
|
{
|
|
var UserRoles = await _userManager.GetRolesAsync(item);
|
|
var UserClaims = await _userManager.GetClaimsAsync(item);
|
|
|
|
var newItem = new UserData()
|
|
{
|
|
Identity = item,
|
|
Roles = UserRoles.ToList(),
|
|
Claims = UserClaims.ToList()
|
|
};
|
|
UsersList.Add(newItem);
|
|
}
|
|
return await Task.FromResult(UsersList);
|
|
}
|
|
|
|
public async void WeekPlanDelete(WeekPlanModel currItem)
|
|
{
|
|
try
|
|
{
|
|
//dbController.ResetController();
|
|
dbController.WeekPlanDelete(currItem);
|
|
string cacheKey = $"DATA:WEEKPLAN:List";
|
|
await distributedCache.RemoveAsync(cacheKey);
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
}
|
|
|
|
public async Task<List<WeekPlanModel>> WeekPlanGet()
|
|
{
|
|
List<WeekPlanModel> dbResult = new List<WeekPlanModel>();
|
|
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetWeekPlan();
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB per WeekPlanGet: {ts.TotalMilliseconds} ms");
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
public async void WeekPlanUpdate(WeekPlanModel currItem)
|
|
{
|
|
try
|
|
{
|
|
//dbController.ResetController();
|
|
dbController.WeekPlanUpdate(currItem);
|
|
string cacheKey = $"DATA:WEEKPLAN:List";
|
|
await distributedCache.RemoveAsync(cacheKey);
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
}
|
|
|
|
#endregion Public Methods
|
|
|
|
#region Protected Fields
|
|
|
|
protected static string connStringBBM = "";
|
|
|
|
#endregion Protected Fields
|
|
|
|
#region Protected Methods
|
|
|
|
/// <summary>
|
|
/// Hash dati EXE TASK x la macchina specificata
|
|
/// </summary>
|
|
/// <param name="idxMacchina"></param>
|
|
/// <returns></returns>
|
|
protected static string exeTaskHash(string idxMacchina)
|
|
{
|
|
return mHash(string.Format("ExeTask:{0}", idxMacchina));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Funzione verifica eventuale creazione NUOVI ordini di consegna
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
protected async Task<bool> checkCreateOrders()
|
|
{
|
|
bool fatto = false;
|
|
List<OrderModel> NewOrders = new List<OrderModel>();
|
|
DateTime adesso = DateTime.Now;
|
|
int supplierId = 1;
|
|
int transporterId = 1;
|
|
double qtyOrd = 0;
|
|
// faccio ciclo x tutti gli impianti
|
|
List<PlantDTO> currPlantData = await PlantDtoGetAll();
|
|
List<WeekPlanModel> fullWeekPlan = WeekPlanGet().Result;
|
|
foreach (var item in currPlantData)
|
|
{
|
|
// recupero ordini x il plant
|
|
var currOrderOpen = await OrdersGetOpen(item.PlantId);
|
|
// calcolo delta ordinato
|
|
qtyOrd = currOrderOpen.Sum(x => x.OrderQty);
|
|
// verifico il livello attuale + i valori degli ordini APERTI rispetto al livello di riordino...
|
|
if (item.LevelAct + qtyOrd < item.LevelReorder)
|
|
{
|
|
// calcolo supplier/transporter da tab WeekPlan
|
|
var dailyPlan = fullWeekPlan.Where(x => x.PlantId == item.PlantId && (int)x.DayNum == ((int)(adesso.AddDays(1).DayOfWeek))).FirstOrDefault();
|
|
if (dailyPlan != null)
|
|
{
|
|
supplierId = dailyPlan.SupplierId;
|
|
transporterId = dailyPlan.TransporterId;
|
|
}
|
|
else
|
|
{
|
|
supplierId = 1;
|
|
transporterId = 1;
|
|
}
|
|
// stacco un NUOVO ordine di quantità finita
|
|
NewOrders.Add(new OrderModel() { DtOrder = adesso, DtETA = adesso.AddDays(1), OrderQty = item.OrderQtyStd, PlantId = item.PlantId, OrderCode = $"O{item.PlantCode}{adesso:yyMMddHHmm}", OrderDesc = $"Ordine {item.PlantDesc} - {adesso}", SupplierId = supplierId, TransporterId = transporterId });
|
|
}
|
|
}
|
|
if (NewOrders.Count > 0)
|
|
{
|
|
// effettuo inserimento ordini!
|
|
dbController.OrderInsert(NewOrders);
|
|
|
|
// recupero elenco users associati al FORNITORE....
|
|
var rawUserList = UserDataGetFilt("").Result;
|
|
var supplList = rawUserList
|
|
.Where(x => x.Roles.Contains("ExtUser"))
|
|
.ToList();
|
|
var transpList = rawUserList
|
|
.Where(x => x.Roles.Contains("ExtTransp"))
|
|
.ToList();
|
|
|
|
// recupero NUOVI ordini x plant...
|
|
foreach (var plant in currPlantData)
|
|
{
|
|
var newOrderOpen = await OrdersGetOpen(plant.PlantId);
|
|
string emailDest = "";
|
|
string emailSubj = "";
|
|
string emailBody = "";
|
|
StringBuilder sb = new StringBuilder();
|
|
|
|
// invio email x ogni fornitore / trasportatore x i NUOVI ordini inseriti
|
|
foreach (var item in newOrderOpen)
|
|
{
|
|
// FORNITORI!
|
|
emailSubj = $"GWMS: Ordine FORNITURA GAS per {item.Plant.PlantDesc}";
|
|
sb = new StringBuilder();
|
|
sb.AppendLine($"<h3>Fornitore {item.Supplier.SupplierDesc}</h3>");
|
|
sb.AppendLine($"<b>Trasportatore {item.Transporter.TransporterDesc}</b>");
|
|
sb.AppendLine($"Impianto di destinazione {item.Plant.PlantDesc}");
|
|
sb.AppendLine("");
|
|
sb.AppendLine($"Ordine di consegna: {item.OrderCode}");
|
|
sb.AppendLine($"Data ordine: {item.DtOrder}");
|
|
sb.AppendLine($"Data consegna indicativa: {item.DtETA}");
|
|
sb.AppendLine($"Quantità ordinata: {item.OrderQty}");
|
|
emailBody = sb.ToString().Replace(Environment.NewLine, "<br/>");
|
|
|
|
System.Security.Claims.Claim suppClaim = new System.Security.Claims.Claim("SupplierId", $"{item.SupplierId}");
|
|
|
|
// recupero elenco users associati al FORNITORE....
|
|
var userListSupp = supplList
|
|
.Where(x => x.Claims.Where(c => c.Type == "SupplierId" && c.Value == $"{item.SupplierId}").Count() > 0)
|
|
.ToList();
|
|
|
|
foreach (var user in userListSupp)
|
|
{
|
|
// invio email di notifica nuovi ordini inseriti
|
|
emailDest = user.Identity.Email;
|
|
//emailDest = user.Email;
|
|
// invio!
|
|
await _emailSender.SendEmailAsync(emailDest, emailSubj, emailBody);
|
|
_logger.LogInformation($"Email sento to SUPPLIER {emailDest}!");
|
|
}
|
|
|
|
// TRASPORTATORI!
|
|
emailSubj = $"GWMS: Ordine TRASPORTO GAS per {item.Plant.PlantDesc}";
|
|
sb = new StringBuilder();
|
|
sb.AppendLine($"<h3>Trasportatore {item.Transporter.TransporterDesc}</h3>");
|
|
sb.AppendLine($"<b>Fornitore {item.Supplier.SupplierDesc}</b>");
|
|
sb.AppendLine($"Impianto di destinazione {item.Plant.PlantDesc}");
|
|
sb.AppendLine("");
|
|
sb.AppendLine($"Ordine di consegna: {item.OrderCode}");
|
|
sb.AppendLine($"Data ordine: {item.DtOrder}");
|
|
sb.AppendLine($"Data consegna indicativa: {item.DtETA}");
|
|
sb.AppendLine($"Quantità ordinata: {item.OrderQty}");
|
|
sb.AppendLine("");
|
|
sb.AppendLine($"Note: {item.OrderDesc}");
|
|
emailBody = sb.ToString().Replace(Environment.NewLine, "<br/>");
|
|
|
|
// recupero elenco users associati al TRASPORTATORE....
|
|
var userListTransp = transpList
|
|
.Where(x => x.Claims.Where(c => c.Type == "TransporterId" && c.Value == $"{item.TransporterId}").Count() > 0)
|
|
.ToList();
|
|
foreach (var user in userListTransp)
|
|
{
|
|
// invio email di notifica nuovi ordini inseriti
|
|
emailDest = user.Identity.Email;
|
|
//emailDest = user.Email;
|
|
// invio!
|
|
await _emailSender.SendEmailAsync(emailDest, emailSubj, emailBody);
|
|
_logger.LogInformation($"Email sento to TRANSPORTER {emailDest}!");
|
|
}
|
|
}
|
|
}
|
|
fatto = true;
|
|
}
|
|
return fatto;
|
|
}
|
|
|
|
protected string getCacheKey(string TableName, SelectOrderData CurrFilter)
|
|
{
|
|
string answ = $"{TableName}:P_{CurrFilter.PlantId:00}:S_{CurrFilter.SupplierId:00}:T_{CurrFilter.TransporterId:00}:D_{CurrFilter.DateStart:yyyyMMddHHmm}_{CurrFilter.DateEnd:yyyyMMddHHmm}";
|
|
return answ;
|
|
}
|
|
|
|
protected async Task<List<PlantLogModel>> PlantLogGetLastByFlux(int PlantId)
|
|
{
|
|
List<PlantLogModel> lastValues = new List<PlantLogModel>();
|
|
// cerco in cache
|
|
string cacheKey = $"DATA:PLANTS:LastFlux:{PlantId}";
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
lastValues = JsonConvert.DeserializeObject<List<PlantLogModel>>(rawData);
|
|
}
|
|
// altrimenti DB e salvo...
|
|
else
|
|
{
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
lastValues = dbController.PlantLogGetLastByFlux(PlantId);
|
|
rawData = JsonConvert.SerializeObject(lastValues);
|
|
redisDataList = Encoding.UTF8.GetBytes(rawData);
|
|
await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true));
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB + caching per PlantLogGetLastByFlux: {ts.TotalMilliseconds} ms");
|
|
}
|
|
return await Task.FromResult(lastValues);
|
|
}
|
|
|
|
#endregion Protected Methods
|
|
|
|
#region Private Fields
|
|
|
|
private static IConfiguration _configuration;
|
|
private static ILogger<GWMSDataService> _logger;
|
|
private static NLog.Logger Log = LogManager.GetCurrentClassLogger();
|
|
private readonly IEmailSender _emailSender;
|
|
private readonly UserManager<IdentityUser> _userManager;
|
|
private readonly IDistributedCache distributedCache;
|
|
private readonly IMemoryCache memoryCache;
|
|
|
|
/// <summary>
|
|
/// Durata assoluta massima della cache IN SECONDI (default 300s)
|
|
/// </summary>
|
|
private int chAbsExp = 60 * 5;
|
|
|
|
/// <summary>
|
|
/// Durata della cache IN SECONDI (default 60s) in modalità inattiva (non acceduta) prima di
|
|
/// venire rimossa NON estende oltre il tempo massimo di validità della cache (chAbsExp)
|
|
/// </summary>
|
|
private int chSliExp = 60 * 1;
|
|
|
|
#endregion Private Fields
|
|
|
|
#region Private Methods
|
|
|
|
/// <summary>
|
|
/// Calcola cache con expyry in modalità fast/slow...
|
|
/// </summary>
|
|
/// <param name="fastCache">fast: 1/5 min, slow: 10/50 min</param>
|
|
/// <returns></returns>
|
|
private DistributedCacheEntryOptions cacheOpt(bool fastCache)
|
|
{
|
|
var numSecAbsExp = fastCache ? chAbsExp : chAbsExp * 10;
|
|
var numSecSliExp = fastCache ? chSliExp : chSliExp * 10;
|
|
return new DistributedCacheEntryOptions().SetAbsoluteExpiration(DateTime.Now.AddSeconds(numSecAbsExp)).SetSlidingExpiration(TimeSpan.FromSeconds(numSecSliExp));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Cache ultrafast: 1 sec e max 5...
|
|
/// </summary>
|
|
/// <param name="fastCache"></param>
|
|
/// <returns></returns>
|
|
private DistributedCacheEntryOptions cacheOptFast(bool fastCache)
|
|
{
|
|
var numSecAbsExp = fastCache ? 5 : chAbsExp * 10;
|
|
var numSecSliExp = fastCache ? 15 : chSliExp * 10;
|
|
return new DistributedCacheEntryOptions().SetAbsoluteExpiration(DateTime.Now.AddSeconds(numSecAbsExp)).SetSlidingExpiration(TimeSpan.FromSeconds(numSecSliExp));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Recupera PlantDTO e aggiorno valori attuali (se presente...)
|
|
/// ATTENZIONE: i dati sono sempre ricevuti PER SINGOLO PlantId!!!
|
|
/// </summary>
|
|
/// <param name="newItems"></param>
|
|
private async Task updateCurrDTO(List<PlantLogModel> newItems)
|
|
{
|
|
DateTime adesso = DateTime.Now;
|
|
List<PlantDTO> dbResult = new List<PlantDTO>();
|
|
int PlantId = newItems.FirstOrDefault().PlantId;
|
|
string cacheKey = "DATA:PLANTS:ListDTO";
|
|
string rawData;
|
|
var redisDataList = await distributedCache.GetAsync(cacheKey);
|
|
if (redisDataList != null)
|
|
{
|
|
rawData = Encoding.UTF8.GetString(redisDataList);
|
|
dbResult = JsonConvert.DeserializeObject<List<PlantDTO>>(rawData);
|
|
|
|
// ora ciclo x ogni flusso/macchina l'ultimo record
|
|
List<PlantLogModel> lastByFlux = newItems
|
|
.OrderByDescending(x => x.DtEvent)
|
|
.GroupBy(g => g.FluxType)
|
|
.Select(s => s.First())
|
|
.ToList();
|
|
// aggiorno il DTO x i valori trovati...
|
|
var currDto = dbResult.Where(x => x.PlantId == PlantId).FirstOrDefault();
|
|
|
|
// verifico SE c'è Level
|
|
var lastLev = lastByFlux.Where(x => x.FluxType == "Level").FirstOrDefault();
|
|
if (lastLev != null)
|
|
{
|
|
currDto.LevelAct = lastLev.ValNumber;
|
|
currDto.LastUpdate = adesso;
|
|
}
|
|
|
|
// verifico SE c'è MainPress
|
|
var lastMain = lastByFlux.Where(x => x.FluxType == "MainPress").FirstOrDefault();
|
|
if (lastMain != null)
|
|
{
|
|
if (currDto.PressAct.ContainsKey("Main"))
|
|
{
|
|
currDto.PressAct["Main"] = lastMain.ValNumber;
|
|
}
|
|
else
|
|
{
|
|
currDto.PressAct.Add("Main", lastMain.ValNumber);
|
|
}
|
|
}
|
|
|
|
// verifico SE c'è PressBH
|
|
var lastBH = lastByFlux.Where(x => x.FluxType == "PressBH").FirstOrDefault();
|
|
if (lastBH != null)
|
|
{
|
|
if (currDto.PressAct.ContainsKey("BH"))
|
|
{
|
|
currDto.PressAct["BH"] = lastBH.ValNumber;
|
|
}
|
|
else
|
|
{
|
|
currDto.PressAct.Add("BH", lastBH.ValNumber);
|
|
}
|
|
}
|
|
|
|
// verifico SE c'è PressBL
|
|
var lastBL = lastByFlux.Where(x => x.FluxType == "PressBL").FirstOrDefault();
|
|
if (lastBL != null)
|
|
{
|
|
if (currDto.PressAct.ContainsKey("BL"))
|
|
{
|
|
currDto.PressAct["BL"] = lastBL.ValNumber;
|
|
}
|
|
else
|
|
{
|
|
currDto.PressAct.Add("BL", lastBL.ValNumber);
|
|
}
|
|
}
|
|
|
|
// salvo DTO!
|
|
rawData = JsonConvert.SerializeObject(dbResult);
|
|
redisDataList = Encoding.UTF8.GetBytes(rawData);
|
|
await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true));
|
|
}
|
|
}
|
|
|
|
#endregion Private Methods
|
|
}
|
|
} |