1557 lines
63 KiB
C#
1557 lines
63 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using System.Configuration;
|
|
using System.Text;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Logging;
|
|
using GWMS.Data;
|
|
using Microsoft.Extensions.Caching.Distributed;
|
|
using Microsoft.Extensions.Caching.Memory;
|
|
using Newtonsoft.Json;
|
|
using System.Diagnostics;
|
|
using NLog;
|
|
using GWMS.Data.DTO;
|
|
using GWMS.Data.DatabaseModels;
|
|
using static GWMS.Data.IobObjects;
|
|
using System.Globalization;
|
|
using Microsoft.AspNetCore.Identity.UI.Services;
|
|
using Microsoft.AspNetCore.Identity;
|
|
|
|
namespace GWMS.UI.Data
|
|
{
|
|
public class GWMSDataService : IDisposable
|
|
{
|
|
#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
|
|
/// </summary>
|
|
private int chAbsExp = 60 * 5;
|
|
|
|
/// <summary>
|
|
/// Durata della cache IN SECONDI 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 Protected Fields
|
|
|
|
protected static string connStringBBM = "";
|
|
|
|
#endregion Protected Fields
|
|
|
|
#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 Private Methods
|
|
|
|
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>
|
|
/// 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
|
|
|
|
#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 PlantsGetAll();
|
|
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)
|
|
{
|
|
// (FARE !!! VERIFICA!!!!)
|
|
// calcolo supplier/transporter da tab WeekPlan
|
|
var dailyPlan = fullWeekPlan.Where(x => x.PlantId == item.PlantId && (int)x.DayNum == ((int)adesso.DayOfWeek + 1)).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 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;
|
|
}
|
|
|
|
/// <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
|
|
double valDbl = 0;
|
|
NumberStyles style = NumberStyles.Number;
|
|
CultureInfo culture = CultureInfo.CreateSpecificCulture("it-IT");
|
|
string valString = origData.valore;
|
|
// verifico SE contiene o meno la ","...
|
|
if (valString.IndexOf(',') > 0 && valString.IndexOf('.') > 0)
|
|
{
|
|
valString = origData.valore.Replace(".", "");
|
|
}
|
|
else if (valString.IndexOf(',') < 0)
|
|
{
|
|
valString = origData.valore.Replace(".", ",");
|
|
}
|
|
double.TryParse(valString, style, culture, out valDbl);
|
|
TimeSpan delta = origData.dtCurr.Subtract(origData.dtEve);
|
|
PlantLogModel answ = new PlantLogModel()
|
|
{
|
|
FluxType = origData.flux,
|
|
ValNumber = valDbl,
|
|
ValString = origData.valore,
|
|
PlantId = plantId,
|
|
DtEvent = DateTime.Now.Subtract(delta)
|
|
};
|
|
|
|
return answ;
|
|
}
|
|
|
|
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:SUPPL:List");
|
|
await distributedCache.RemoveAsync("DATA:TRANSP:List");
|
|
await distributedCache.RemoveAsync("DATA:WEEKPLAN: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>
|
|
/// 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
|
|
/// </summary>
|
|
/// <param name="PlantId"></param>
|
|
/// <returns></returns>
|
|
public async Task<List<ParamSetModel>> ParamSetGetByPlant(int PlantId)
|
|
{
|
|
List<ParamSetModel> dbResult = new List<ParamSetModel>();
|
|
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetParamSet(PlantId);
|
|
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;
|
|
try
|
|
{
|
|
done = dbController.ParamSetUpdate(currItem);
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Eccezione in ParamSetUpdate:{Environment.NewLine}{exc}");
|
|
}
|
|
return await Task.FromResult(done);
|
|
}
|
|
|
|
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<List<PlantDTO>> PlantsGetAll()
|
|
{
|
|
List<PlantDTO> dbResult = new List<PlantDTO>();
|
|
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);
|
|
}
|
|
else
|
|
{
|
|
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.Trace($"Effettuata lettura da DB + caching per PlantsGetAll: {ts.TotalMilliseconds} ms");
|
|
}
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
public async Task<PlantDTO> PlantsGetByCode(string PlantCode)
|
|
{
|
|
PlantDTO answ = new PlantDTO();
|
|
var ListRecords = await PlantsGetAll();
|
|
var found = ListRecords.Where(x => x.PlantCode == PlantCode).FirstOrDefault();
|
|
if (found != null)
|
|
{
|
|
answ = found;
|
|
}
|
|
return await Task.FromResult(answ);
|
|
}
|
|
|
|
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;
|
|
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))
|
|
{
|
|
taskType 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 PlantsGetAll: {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 PlantsGetAll: {ts.TotalMilliseconds} ms");
|
|
}
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
/// <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();
|
|
//var oldItems = actValues.Where(x => oldUid.Contains(x.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);
|
|
}
|
|
|
|
#if false
|
|
public async Task<List<UserModel>> UsersGetFilt(UserLevel UsrLvl, int PlantId, int SupplierId, int TransporterId)
|
|
{
|
|
List<UserModel> dbResult = new List<UserModel>();
|
|
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = dbController.GetUsersFilt(UsrLvl, PlantId, SupplierId, TransporterId);
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB per UsersGetFilt: {ts.TotalMilliseconds} ms");
|
|
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
public void UserUpdate(UserModel currItem)
|
|
{
|
|
try
|
|
{
|
|
dbController.UserUpdate(currItem);
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
}
|
|
#endif
|
|
|
|
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
|
|
}
|
|
} |