diff --git a/MagMan.Core/DTO/ProjectDTO.cs b/MagMan.Core/DTO/ProjectDTO.cs new file mode 100644 index 0000000..b8bb59c --- /dev/null +++ b/MagMan.Core/DTO/ProjectDTO.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using static MagMan.Core.Enums; + +namespace MagMan.Core.DTO +{ + public class ProjectDTO + { + /// + /// Id macchina (MagMan) + /// + public int MachineID { get; set; } = 0; + + /// + /// Key di riferimento per il progetto + /// + public int KeyNum { get; set; } = 0; + + /// + /// ID del DB EgtBW, univoco con KeyNum + /// + public int ProjExtDbId { get; set; } = 0; + + /// + /// ID esterno (da EgtBW) + /// + public int ProjExtId { get; set; } = 0; + + /// + /// Nome file BTL originale + /// + public string BTLFileName { get; set; } = ""; + + /// + /// Tipologia del progetto (Travi, Pareti, ...) + /// + public BWType PType { get; set; } = BWType.NULL; + + /// + /// Macchina (Costruttore/Modello) + /// + public string Machine { get; set; } = ""; + + /// + /// Descrizione progetto (copiata da BTLFileName inizialmente) + /// + public string ProjDescription { get; set; } = ""; + + /// + /// Data Creazione progetto + /// + public DateTime DtCreated { get; set; } = DateTime.Now; + + /// + /// Data di schedulazione (prevista) + /// + public DateTime DtSchedule { get; set; } = DateTime.Today.AddMonths(3); + + /// + /// Data Inizio Produzione + /// + public DateTime DtStartProd { get; set; } = DateTime.MinValue; + + /// + /// Data ora ultima operazione registrata + /// + public DateTime DtLastAction { get; set; } = DateTime.MinValue; + + /// + /// ListName del BTL + /// + public string ListName { get; set; } = ""; + + /// + /// Tempo lavorazione previsto (stima) in minuti + /// + public double ProcTimeEst { get; set; } = 0; + + /// + /// Tempo lavorazione reale in minuti (parziale o totale se chiuso/completato/archiviato) + /// + public double ProcTimeReal { get; set; } = 0; + + /// + /// Record attivo (se false == cancellazione logica) + /// + public bool IsActive { get; set; } = true; + + /// + /// Stato Archiviato = NON visualizzabile normalmente, già prodotto/chiuso + /// + public bool IsArchived { get; set; } = false; + + } +} diff --git a/MagMan.Data.Tenant/Controllers/TenantController.cs b/MagMan.Data.Tenant/Controllers/TenantController.cs index 01d90a6..44fe134 100644 --- a/MagMan.Data.Tenant/Controllers/TenantController.cs +++ b/MagMan.Data.Tenant/Controllers/TenantController.cs @@ -1,4 +1,5 @@ using MagMan.Data.Tenant.DbModels; +using MagMan.Data.Tenant.Services; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using NLog; @@ -277,8 +278,8 @@ namespace MagMan.Data.Tenant.Controllers } /// /// Elenco Materiali gestiti a magazzino Stringa - /// connessione (variabile x cliente) Materiale richiesto, 0 = - /// tutti Se true allora include record child + /// connessione (variabile x cliente) Materiale richiesto, 0 + /// = tutti Se true allora include record child /// (Items) public List MaterialGetFilt(string connString, int matID, bool withChild) { @@ -363,6 +364,165 @@ namespace MagMan.Data.Tenant.Controllers return done; } + /// + /// Elimina record Project + /// + /// Stringa connessione (variabile x cliente) + /// Item da eliminare + /// + public bool ProjectDelete(string connString, ProjModel rec2del) + { + bool done = false; + using (MagManContext dbCtx = new MagManContext(connString)) + { + try + { + var currData = dbCtx + .DbSetProjects + .Where(x => x.ProjDbId == rec2del.ProjDbId) + .FirstOrDefault(); + if (currData != null) + { + dbCtx + .DbSetProjects + .Remove(currData); + dbCtx.SaveChanges(); + done = true; + } + } + catch (Exception exc) + { + Log.Error($"Eccezione in ProjectDelete{Environment.NewLine}{exc}"); + } + } + return done; + } + + /// + /// Elenco Projects (all) + /// + /// Stringa connessione (variabile x cliente) + /// + public List ProjectGetAll(string connString) + { + List dbResult = new List(); + using (MagManContext dbCtx = new MagManContext(connString)) + { + dbResult = dbCtx + .DbSetProjects + .OrderBy(x => x.DtCreated) + .ToList(); + } + return dbResult; + } + + /// + /// Elenco Items gestiti a magazzino dato Materiale + /// + /// Stringa connessione (variabile x cliente) + /// ID del materiale x cui filtrare, 0 = tutti + /// + public List ProjectGetByNumKey(string connString, int numKey) + { + List dbResult = new List(); + using (MagManContext dbCtx = new MagManContext(connString)) + { + dbResult = dbCtx + .DbSetProjects + .Where(x => numKey == 0 || x.KeyNum == numKey) + .OrderBy(x => x.DtCreated) + .ToList(); + } + return dbResult; + } + + /// + /// Elenco Items gestiti a magazzino dato Materiale + /// + /// Stringa connessione (variabile x cliente) + /// ID master key, 0 = tutti + /// periodo x filtraggio + /// + public List ProjectGetFilt(string connString, int numKey, SelectData period) + { + List dbResult = new List(); + using (MagManContext dbCtx = new MagManContext(connString)) + { + dbResult = dbCtx + .DbSetProjects + .Where(x => (numKey == 0 || x.KeyNum == numKey) && + ((x.DtCreated >= period.DateStart && x.DtCreated <= period.DateEnd) + || (x.DtSchedule >= period.DateStart && x.DtSchedule <= period.DateEnd) + || (x.DtLastAction >= period.DateStart && x.DtLastAction <= period.DateEnd) + )) + .OrderBy(x => x.DtCreated) + .ToList(); + } + return dbResult; + } + + /// + /// Aggiunge/Modifica un record Project + /// + /// Stringa connessione (variabile x cliente) + /// Record da aggiungere/aggiornare + /// + public bool ProjectUpdate(string connString, ProjModel rec2upd) + { + bool done = false; + using (MagManContext dbCtx = new MagManContext(connString)) + { + try + { + /* + * Ricerca: + * - DbId corrisponde + * - Key + Id remoti corrispondono + * */ + var currData = dbCtx + .DbSetProjects + .Where(x => (x.ProjDbId == rec2upd.ProjDbId) || + (x.ProjExtDbId == rec2upd.ProjExtDbId && x.KeyNum == rec2upd.KeyNum) || + (x.ProjExtId == rec2upd.ProjExtId && x.KeyNum == rec2upd.KeyNum)) + .FirstOrDefault(); + if (currData != null) + { + currData.MachineID = rec2upd.MachineID; + currData.KeyNum = rec2upd.KeyNum; + currData.ProjExtDbId = rec2upd.ProjExtDbId; + currData.ProjExtId = rec2upd.ProjExtId; + currData.BTLFileName = rec2upd.BTLFileName; + currData.PType = rec2upd.PType; + currData.Machine = rec2upd.Machine; + currData.ProjDescription = rec2upd.ProjDescription; + currData.DtCreated = rec2upd.DtCreated; + currData.DtLastAction = rec2upd.DtLastAction; + currData.DtSchedule = rec2upd.DtSchedule; + currData.DtStartProd = rec2upd.DtStartProd; + currData.ListName = rec2upd.ListName; + currData.ProcTimeEst = rec2upd.ProcTimeEst; + currData.ProcTimeReal = rec2upd.ProcTimeReal; + currData.IsActive = rec2upd.IsActive; + currData.IsArchived = rec2upd.IsArchived; + dbCtx.Entry(currData).State = EntityState.Modified; + } + else + { + dbCtx + .DbSetProjects + .Add(rec2upd); + } + dbCtx.SaveChanges(); + done = true; + } + catch (Exception exc) + { + Log.Error($"Eccezione in ItemUpdate{Environment.NewLine}{exc}"); + } + } + return done; + } + #endregion Public Methods #region Private Fields diff --git a/MagMan.Data.Tenant/Services/MessageService.cs b/MagMan.Data.Tenant/Services/MessageService.cs deleted file mode 100644 index 0ad9e5c..0000000 --- a/MagMan.Data.Tenant/Services/MessageService.cs +++ /dev/null @@ -1,481 +0,0 @@ -using Blazored.LocalStorage; -using Blazored.SessionStorage; -using Microsoft.Extensions.Configuration; -using NLog; -using NLog.Fluent; -using StackExchange.Redis; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Reflection.Metadata; -using System.Text; -using System.Threading.Tasks; - -namespace MagMan.Data.Tenant.Services -{ - public class MessageService - { - #region Public Events - - public event Action EA_FilterUpdated = null!; - - public event Action EA_HideSearch = null!; - - public event Action EA_PageUpdated = null!; - - public event Action EA_SearchUpdated = null!; - - public event Action EA_ShowSearch = null!; - - #endregion Public Events - - #region Public Properties - - public SelectData DetailFilter - { - get => _detailFilter; - set - { - if (_detailFilter != value) - { - _detailFilter = value; - - if (EA_FilterUpdated != null) - { - EA_FilterUpdated?.Invoke(); - } - } - } - } - - public SelectOrderData Order_Filter { get; set; } = SelectOrderData.Init(5, 30); - - public string PageIcon - { - get => _pageIcon; - set - { - if (_pageIcon != value) - { - _pageIcon = value; - ReportPageUpd(); - } - } - } - - public string PageName - { - get => _pageName; - set - { - if (_pageName != value) - { - _pageName = value; - ReportPageUpd(); - } - } - } - - public string SearchVal - { - get => _searchVal; - set - { - if (_searchVal != value) - { - _searchVal = value; - - if (EA_SearchUpdated != null) - { - EA_SearchUpdated?.Invoke(); - } - } - } - } - - public string SelOrderCode { get; set; } = ""; - public string SelPlantId { get; set; } = "0"; - - public bool ShowSearch - { - get => _showSearch; - set - { - if (_showSearch != value) - { - _showSearch = value; - if (_showSearch) - { - if (EA_ShowSearch != null) - { - EA_ShowSearch?.Invoke(); - } - } - else - { - if (EA_HideSearch != null) - { - EA_HideSearch?.Invoke(); - } - } - } - } - } - - #endregion Public Properties - - public MessageService(IConfiguration configuration, ILocalStorageService genLocalStorage, ISessionStorageService sessStore) - { - _configuration = configuration; - // gestione sessioni in browser - localStore = genLocalStorage; - sessionStore = sessStore; - // setup compoenti REDIS - redisConn = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("Redis")); - redisDb = redisConn.GetDatabase(); - } - protected static IConfiguration _configuration = null!; - - #region Public Methods - - /// - /// Svuota localstorage (clear) - /// - /// - public async Task StoreLocalClear() - { - bool answ = false; - try - { - await localStore.ClearAsync(); - answ = true; - } - catch (Exception ex) - { - Log.Error($"Eccezione in StoreLocalClear{Environment.NewLine}{ex}"); - } - return answ; - } - - /// - /// Restituisce il valore richiesto da localstorage - /// - /// Chiave - /// - public async Task StoreLocalGet(string sKey) - { - string answ = ""; - var result = await localStore.GetItemAsync(sKey); - if (result != null) - { - answ = result; - } - return answ; - } - - /// - /// Scrive il valore nel localstorage - /// - /// Chiave - /// Valore associato - /// - public async Task StoreLocalSet(string sKey, string sVal) - { - bool answ = false; - try - { - await localStore.SetItemAsStringAsync(sKey, sVal); - answ = true; - } - catch (Exception ex) - { - Log.Error($"Eccezione in StoreLocalSet{Environment.NewLine}{ex}"); - } - return answ; - } - - /// - /// Svuota sessionstorage (clear) - /// - /// - public async Task StoreSessClear() - { - bool answ = false; - try - { - await sessionStore.ClearAsync(); - answ = true; - } - catch (Exception ex) - { - Log.Error($"Eccezione in StoreLocalClear{Environment.NewLine}{ex}"); - } - return answ; - } - - /// - /// Restituisce il valore richiesto da sessionstorage - /// - /// Chiave - /// - public async Task StoreSessGet(string sKey) - { - string answ = ""; - var result = await sessionStore.GetItemAsync(sKey); - if (result != null) - { - answ = result; - } - return answ; - } - - /// - /// Scrive il valore nel sessionstorage (tab) - /// - /// Chiave - /// Valore associato - /// - public async Task StoreSessSet(string sKey, string sVal) - { - bool answ = false; - try - { - await sessionStore.SetItemAsStringAsync(sKey, sVal); - answ = true; - } - catch (Exception ex) - { - Log.Error($"Eccezione in StoreSessSet{Environment.NewLine}{ex}"); - } - return answ; - } - - #endregion Public Methods - - #region Protected Properties - - protected ILocalStorageService localStore { get; set; } = null!; - protected ISessionStorageService sessionStore { get; set; } = null!; - - #endregion Protected Properties - - #region Private Fields - - private SelectData _detailFilter = SelectData.Init(5, 15); - private string _pageIcon = ""; - private string _pageName = ""; - private string _searchVal = ""; - private bool _showSearch = false; - private Logger Log = LogManager.GetCurrentClassLogger(); - - #endregion Private Fields - - #region Private Methods - - private void ReportPageUpd() - { - if (EA_PageUpdated != null) - { - EA_PageUpdated?.Invoke(); - } - } - - private void ReportSearch() - { - if (EA_SearchUpdated != null) - { - EA_SearchUpdated?.Invoke(); - } - } - - #endregion Private Methods - - /// - /// Recupero HashSet redis come Dictionary - /// - /// - /// - private Dictionary RedisHashDictGet(RedisKey currKey) - { - Dictionary answ = new Dictionary(); - try - { - answ = redisDb - .HashGetAll(currKey) - .ToDictionary(x => $"{x.Name}", x => $"{x.Value}"); - } - catch (Exception exc) - { - Log.Info($"Errore RedisHashDictGet | currKey: {currKey}{Environment.NewLine}{exc}"); - } - return answ; - } - /// - /// Oggetto per connessione a REDIS - /// - protected ConnectionMultiplexer redisConn = null!; - - /// - /// Oggetto DB redis da impiegare x chiamate R/W - /// - protected IDatabase redisDb = null!; - - /// - /// Salvataggio Dictionary come HashSet Redis - /// - /// - /// - private bool RedisHashDictSet(RedisKey currKey, Dictionary dict) - { - bool fatto = false; - try - { - HashEntry[] data2ins = new HashEntry[dict.Count]; - int i = 0; - foreach (KeyValuePair kvp in dict) - { - data2ins[i] = new HashEntry(kvp.Key, kvp.Value); - i++; - } - // salvo! - redisDb.HashSet(currKey, data2ins); - fatto = true; - } - catch (Exception exc) - { - Log.Error($"Eccezione in RedisHashDictSet | currKey: {currKey}{Environment.NewLine}{exc}"); - } - return fatto; - } - /// - /// Salvataggio Dictionary come HashSet Redis - /// - /// - /// - /// - private bool RedisHashDictSet(RedisKey currKey, Dictionary dict, TimeSpan ttl) - { - bool fatto = false; - try - { - HashEntry[] data2ins = new HashEntry[dict.Count]; - int i = 0; - foreach (KeyValuePair kvp in dict) - { - data2ins[i] = new HashEntry(kvp.Key, kvp.Value); - i++; - } - // salvo! - redisDb.HashSet(currKey, data2ins); - redisDb.KeyExpire(currKey, ttl); - fatto = true; - } - catch (Exception exc) - { - Log.Error($"Eccezione in RedisHashDictSet(+TTL) | currKey: {currKey} | ttl: {ttl}{Environment.NewLine}{exc}"); - } - return fatto; - } - /// - /// Effettua upsert in HasList redis - /// - /// Chiave redis della Hashlist - /// Chiave nella HashList - /// Valore da salvare - /// Num record nella HashList - protected async Task RedisHashUpsert(RedisKey currKey, string chiave, string valore) - { - long numReq = 0; - Stopwatch stopWatch = new Stopwatch(); - stopWatch.Start(); - await redisDb.HashSetAsync(currKey, chiave, valore); - numReq = await redisDb.HashLengthAsync(currKey); - stopWatch.Stop(); - TimeSpan ts = stopWatch.Elapsed; - Log.Trace($"RedisHashUpsert | {currKey} | in: {ts.TotalMilliseconds} ms"); - return numReq; - } - /// - /// Get single hash record - /// - /// Redis Key for Hashlist - /// Requested key on list - /// Value as Int - public async Task RedisHashGetInt(RedisKey currKey, string chiave) - { - int result = 0; - Stopwatch stopWatch = new Stopwatch(); - stopWatch.Start(); - var hasVal = await redisDb.HashExistsAsync(currKey, chiave); - if (hasVal) - { - var rawRes = await redisDb.HashGetAsync(currKey, chiave); - if (rawRes.HasValue) - { - int.TryParse($"{rawRes}", out result); - } - } - stopWatch.Stop(); - TimeSpan ts = stopWatch.Elapsed; - Log.Trace($"RedisHashGetInt | {currKey} | in: {ts.TotalMilliseconds} ms"); - return result; - } - - /// - /// Get single hash record - /// - /// Redis Key for Hashlist - /// Requested key on list - /// Value as string - public async Task RedisHashGetString(RedisKey currKey, string chiave) - { - string result = ""; - Stopwatch stopWatch = new Stopwatch(); - stopWatch.Start(); - var hasVal = await redisDb.HashExistsAsync(currKey, chiave); - if (hasVal) - { - var rawRes = await redisDb.HashGetAsync(currKey, chiave); - if (rawRes.HasValue) - { - result = $"{rawRes}"; - } - } - stopWatch.Stop(); - TimeSpan ts = stopWatch.Elapsed; - Log.Trace($"RedisHashGetString | {currKey} | in: {ts.TotalMilliseconds} ms"); - return result; - } - - /// - /// Remove for single hash record - /// - /// Chiave redis della Hashlist - /// Chiave nella HashList - /// Esito rimozione - public async Task RedisHashRemove(RedisKey currKey, string chiave) - { - bool fatto = false; - Stopwatch stopWatch = new Stopwatch(); - stopWatch.Start(); - fatto = await redisDb.HashDeleteAsync(currKey, chiave); - stopWatch.Stop(); - TimeSpan ts = stopWatch.Elapsed; - Log.Trace($"RedisHashRemove | {currKey} | in: {ts.TotalMilliseconds} ms"); - return fatto; - } - - -#if false - /// - /// Dizionario totale preferenze utente - /// - public Dictionary UsersPrefDict - { - get => RedisHashDictGet((RedisKey)$"{redisBaseKey}:{MatrOpr}"); - set => RedisHashDictSet((RedisKey)$"{redisBaseKey}:{MatrOpr}", value); - } -#endif - } -} \ No newline at end of file diff --git a/MagMan.Data.Tenant/Services/TenantService.cs b/MagMan.Data.Tenant/Services/TenantService.cs index ab9e80b..177061e 100644 --- a/MagMan.Data.Tenant/Services/TenantService.cs +++ b/MagMan.Data.Tenant/Services/TenantService.cs @@ -83,7 +83,7 @@ namespace MagMan.Data.Tenant.Services /// Converte il DTO in ItemModel /// /// DTO di partenza - /// Parametro active da impostare + /// Parametro active da impostare /// public RawItemModel ItemFromDto(ItemDTO origItem, bool isActive) { @@ -166,7 +166,7 @@ namespace MagMan.Data.Tenant.Services List? dbResult = new List(); try { - string currKey = $"{Const.rKeyConfig}:{nKey}:{matID}:ItemList"; + string currKey = $"{Const.rKeyConfig}:{nKey}:ItemList:{matID}"; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); string? rawData = await redisDb.StringGetAsync(currKey); @@ -438,6 +438,188 @@ namespace MagMan.Data.Tenant.Services return fatto; } + /// + /// Elimina record Project + refresh cache + /// + /// Key di riferimento + /// Item da eliminare + /// + public async Task ProjectDelete(int nKey, ProjModel rec2del) + { + bool fatto = false; + string cString = ConnString(nKey); + try + { + fatto = dbController.ProjectDelete(cString, rec2del); + if (fatto) + { + await FlushRedisCache(); + } + } + catch (Exception exc) + { + Log.Error($"Error during ProjectDelete:{Environment.NewLine}{exc}"); + } + return fatto; + } + + /// + /// Converte il DTO in ItemModel + /// + /// DTO di partenza + /// + public ProjModel ProjectFromDto(ProjectDTO origItem) + { + ProjModel answ = new ProjModel() + { + MachineID = origItem.MachineID, + KeyNum = origItem.KeyNum, + ProjExtDbId = origItem.ProjExtDbId, + ProjExtId = origItem.ProjExtId, + BTLFileName = origItem.BTLFileName, + PType = origItem.PType, + Machine = origItem.Machine, + ProjDescription = origItem.ProjDescription, + DtCreated = origItem.DtCreated, + DtLastAction = origItem.DtLastAction, + DtSchedule = origItem.DtSchedule, + DtStartProd = origItem.DtStartProd, + ListName = origItem.ListName, + ProcTimeEst = origItem.ProcTimeEst, + ProcTimeReal = origItem.ProcTimeReal, + IsActive = origItem.IsActive, + IsArchived = origItem.IsArchived + }; + + return answ; + } + + /// + /// Lista Projects gestiti a magazzino + /// + /// Key di riferimento + /// + public async Task> ProjectGetAll(int nKey) + { + string source = "DB"; + string cString = ConnString(nKey); + List? dbResult = new List(); + try + { + string currKey = $"{Const.rKeyConfig}:ProjList:{nKey}"; + Stopwatch stopWatch = new Stopwatch(); + stopWatch.Start(); + string? rawData = await redisDb.StringGetAsync(currKey); + if (!string.IsNullOrEmpty(rawData)) + { + source = "REDIS"; + var tempResult = JsonConvert.DeserializeObject>(rawData); + if (tempResult == null) + { + dbResult = new List(); + } + else + { + dbResult = tempResult; + } + } + else + { + dbResult = dbController.ProjectGetAll(cString); + rawData = JsonConvert.SerializeObject(dbResult, JSSettings); + await redisDb.StringSetAsync(currKey, rawData, LongCache); + } + if (dbResult == null) + { + dbResult = new List(); + } + stopWatch.Stop(); + TimeSpan ts = stopWatch.Elapsed; + Log.Debug($"ProjectGetAll | {source} in: {ts.TotalMilliseconds} ms"); + } + catch (Exception exc) + { + Log.Error($"Error during ProjectGetAll:{Environment.NewLine}{exc}"); + } + return dbResult; + } + + /// + /// Lista Items gestiti a magazzino x materiale + /// + /// Key di riferimento + /// ID del materiale x cui filtrare, 0 = tutti + /// + public async Task> ProjectGetByNumKey(int nKey, int numKey) + { + string source = "DB"; + string cString = ConnString(nKey); + List? dbResult = new List(); + try + { + string currKey = $"{Const.rKeyConfig}:{nKey}:ProjList:{numKey}"; + Stopwatch stopWatch = new Stopwatch(); + stopWatch.Start(); + string? rawData = await redisDb.StringGetAsync(currKey); + if (!string.IsNullOrEmpty(rawData)) + { + source = "REDIS"; + var tempResult = JsonConvert.DeserializeObject>(rawData); + if (tempResult == null) + { + dbResult = new List(); + } + else + { + dbResult = tempResult; + } + } + else + { + dbResult = dbController.ProjectGetByNumKey(cString, numKey); + rawData = JsonConvert.SerializeObject(dbResult, JSSettings); + await redisDb.StringSetAsync(currKey, rawData, LongCache); + } + if (dbResult == null) + { + dbResult = new List(); + } + stopWatch.Stop(); + TimeSpan ts = stopWatch.Elapsed; + Log.Debug($"ProjectGetByNumKey | {source} in: {ts.TotalMilliseconds} ms"); + } + catch (Exception exc) + { + Log.Error($"Error during ProjectGetByNumKey:{Environment.NewLine}{exc}"); + } + return dbResult; + } + + /// + /// Update record Item + refresh cache + /// + /// Key di riferimento + /// Item interesato + /// + public async Task ProjectUpdate(int nKey, ProjModel currItem) + { + bool fatto = false; + string cString = ConnString(nKey); + try + { + fatto = dbController.ProjectUpdate(cString, currItem); + if (fatto) + { + await FlushRedisCache(); + } + } + catch (Exception exc) + { + Log.Error($"Error during ProjectUpdate:{Environment.NewLine}{exc}"); + } + return fatto; + } + #endregion Public Methods #region Private Fields @@ -484,40 +666,5 @@ namespace MagMan.Data.Tenant.Services } #endregion Private Methods - -#if false - /// - /// Dizionario dei token 2 connectionStrings - /// - private Dictionary TokenList { get; set; } = new Dictionary(); - - /// - /// Recupera ConnectionString dal dizionario dei token noti o cercando sul DB - /// - /// - /// - public string ConnStringByToken(string RestToken) - { - string answ = ""; - if (TokenList.ContainsKey(RestToken)) - { - answ = TokenList[RestToken]; - } - else - { - // cerco nel DB - var custList = dbController.CustomerGetAll(); - var custRow = custList.FirstOrDefault(x => x.RestToken == RestToken); - // se trovato salvo - if (custRow != null) - { - answ = DbConfig.CustomerConnString(DbServerAddr, nKey); - TokenList.Add(RestToken, answ); - Log.Info($"TokenList: added {RestToken} --> {answ}"); - } - } - return answ; - } -#endif } } \ No newline at end of file diff --git a/MagMan.UI/Controllers/ProjectsController.cs b/MagMan.UI/Controllers/ProjectsController.cs index 52b777e..3e841a4 100644 --- a/MagMan.UI/Controllers/ProjectsController.cs +++ b/MagMan.UI/Controllers/ProjectsController.cs @@ -71,13 +71,13 @@ namespace MagMan.UI.Controllers } /// - /// Processa una chiamata POST per l'invio di un oggetto di aggiornamento risorse progetto (RestPayload.Resources) + /// Processa una chiamata POST per l'invio di un oggetto di aggiornamento progetto /// PUT: api/Inventory/upsert/00000000-0000-0000-0000-000000000000 /// /// token comunicazione /// [HttpPost("upsert/{id}")] - public async Task upsert(string id, [FromBody] RestPayload.Resources projectData) + public async Task upsert(string id, [FromBody] ProjectDTO projectData) { string answ = "ND"; bool fatto = false; diff --git a/MagMan.UI/Controllers/ResourcesController.cs b/MagMan.UI/Controllers/ResourcesController.cs new file mode 100644 index 0000000..81edb1b --- /dev/null +++ b/MagMan.UI/Controllers/ResourcesController.cs @@ -0,0 +1,117 @@ +using k8s.Models; +using MagMan.Core; +using MagMan.Core.DTO; +using MagMan.Data.Admin.DbModels; +using MagMan.Data.Admin.Services; +using MagMan.Data.Tenant.DbModels; +using MagMan.Data.Tenant.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; +using NLog; + +namespace MagMan.UI.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class ResourcesController : ControllerBase + { + /// + /// Classe per logging + /// + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + private MTAdminService MTAdmService { get; set; } = null!; + private static JsonSerializerSettings? JSSettings; + private TenantService TService { get; set; } = null!; + public ResourcesController(MTAdminService MTDataService, TenantService TDataService) + { + MTAdmService = MTDataService; + TService = TDataService; + // json serializer... FIX errore loop circolare https://www.ryadel.com/en/jsonserializationexception-self-referencing-loop-detected-error-fix-entity-framework-asp-net-core/ + JSSettings = new JsonSerializerSettings() + { + ReferenceLoopHandling = ReferenceLoopHandling.Ignore + }; + Log.Info("Avviata classe ResourcesController"); + } + + /// + /// Controllo status Alive + /// GET: api/Machines/alive + /// + /// + [HttpGet("alive")] + public string alive() + { + //Log.Debug("Chiamata alive"); + return $"OK"; + } + + // GET api/Machines/5 + [HttpGet] + public async Task> Get() + { + // se non ho chaive --> vuoto! + List ListRecords = new List(); + await Task.Delay(100); + return ListRecords; + } + + /// + /// Elenco Macchine dato RestToken + /// + /// Rest Token cliente + /// + // GET api/Machines/2cba60c7-7be4-40b1-aa0d-52e7c71fc1a7 + [HttpGet("{id}")] + public async Task> Get(string id, int KeyNum) + { + var ListRecords = await MTAdmService.MachineGetByToken(id); + return ListRecords; + } + + /// + /// Processa una chiamata POST per l'invio di un oggetto di aggiornamento risorse progetto (RestPayload.Resources) + /// PUT: api/Inventory/upsert/00000000-0000-0000-0000-000000000000 + /// + /// token comunicazione + /// + [HttpPost("upsert/{id}")] + public async Task upsert(string id, [FromBody] RestPayload.Resources projectData) + { + string answ = "ND"; + bool fatto = false; + // verifico ci sia valore + if (!string.IsNullOrEmpty(id) && projectData != null) + { + // in primis recupero codice chiave da token... + int nKey = await MTAdmService.MainKeyByToken(id); + if (nKey > 0) + { +#if false + // creo oggetti materiale da lista ricevuta + List matList = item2Consume.ItemList.Select(jpl => TService.ItemFromDto(jpl, true)).ToList(); + + foreach (var item in matList) + { + try + { + await TService.ItemUpdate(nKey, item); + fatto = true; + } + catch (Exception exc) + { + Log.Error($"InventoryController.upsert | Errore in fase salvataggio ItemDto{Environment.NewLine}{exc}"); + fatto = false; + } + } +#endif + // resetto cache redis + await MTAdmService.FlushRedisCache(); + } + } + answ = fatto ? "OK" : "NO"; + return answ; + } + } +} diff --git a/MagMan.UI/MagMan.UI.csproj b/MagMan.UI/MagMan.UI.csproj index 0e4a33f..a99d61a 100644 --- a/MagMan.UI/MagMan.UI.csproj +++ b/MagMan.UI/MagMan.UI.csproj @@ -2,7 +2,7 @@ net6.0 - 1.0.2401.2218 + 1.0.2401.2219 enable enable true diff --git a/MagMan.UI/Pages/WareHouse.razor b/MagMan.UI/Pages/WareHouse.razor index 357e6f4..91abc55 100644 --- a/MagMan.UI/Pages/WareHouse.razor +++ b/MagMan.UI/Pages/WareHouse.razor @@ -4,14 +4,6 @@
- @* *@
diff --git a/MagMan.UI/Shared/NavMenu.razor b/MagMan.UI/Shared/NavMenu.razor index 8c09629..8d63bc6 100644 --- a/MagMan.UI/Shared/NavMenu.razor +++ b/MagMan.UI/Shared/NavMenu.razor @@ -46,6 +46,11 @@ Dati Macchine
+