using k8s.Models; using MagMan.Core; using MagMan.Core.DTO; using MagMan.Core.Services; 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; using Org.BouncyCastle.Asn1.Pkcs; using System.Diagnostics; using System.Globalization; namespace MagMan.UI.Controllers { [Route("api/[controller]")] [ApiController] public class ProjectsController : ControllerBase { #region Public Constructors public ProjectsController(MTAdminService MTDataService, TenantService TDataService, MessageService messageService) { MTAdmService = MTDataService; TService = TDataService; MService = messageService; // 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 ProjectsController"); } #endregion Public Constructors #region Public Methods /// /// Controllo status Alive /// GET: api/Projects/alive /// /// [HttpGet("alive")] public string alive() { return $"OK"; } // GET api/Projects/5 [HttpGet] public async Task> Get() { // se non ho chiave --> vuoto! List ListRecords = new List(); await Task.Delay(100); return ListRecords; } /// /// Elenco Progetti dato RestToken /// /// Rest Token cliente /// Chiave associata ai progetti /// // GET api/Projects/2cba60c7-7be4-40b1-aa0d-52e7c71fc1a7 [HttpGet("{id}")] public async Task> Get(string id, int KeyNum) { List ListRecords = new List(); if (!string.IsNullOrEmpty(id)) { // in primis recupero codice chiave da token... int nKey = await MTAdmService.MainKeyByToken(id); var rawList = await TService.ProjectGetAll(nKey); ListRecords = rawList.Select(x => TService.ProjectToDto(x)).ToList(); } return ListRecords; } /// /// Elenco Progetti dato RestToken /// GET api/Projects/single/2cba60c7-7be4-40b1-aa0d-52e7c71fc1a7 /// /// Rest Token cliente /// Key del proj /// [HttpGet("single/{id}")] public async Task GetSingle(string id, int ProjCloudId) { ProjectDTO CurrRec = new ProjectDTO(); if (!string.IsNullOrEmpty(id)) { // in primis recupero codice chiave da token... int nKey = await MTAdmService.MainKeyByToken(id); var rawResult = await TService.ProjectGetById(nKey, ProjCloudId); CurrRec = rawResult != null ? TService.ProjectToDto(rawResult) : new ProjectDTO(); } return CurrRec; } /// /// Elenco dizionario stato Progetti dato RestToken /// GET api/Projects/proj-arch/2cba60c7-7be4-40b1-aa0d-52e7c71fc1a7 /// /// Rest Token cliente /// DateTime di riferimento nel formato yyyyMMddHHmmss /// Dizionario nel formato CloudId / isArchived [HttpGet("proj-arch-get/{id}")] public async Task> ProjArchivedGet(string id, string DtIso) { Dictionary listRec = new Dictionary(); if (!string.IsNullOrEmpty(id)) { // in primis recupero codice chiave da token... int nKey = await MTAdmService.MainKeyByToken(id); // formato decodifica stringa DateTime string format = "yyyyMMddHHmmss"; CultureInfo provider = CultureInfo.InvariantCulture; DateTime dtRif = DateTime.Now; try { dtRif = DateTime.ParseExact(DtIso, format, provider); } catch (Exception exc) { Log.Error($"Eccezione in gestione parse stringa DateTime: IN: {DtIso} | format: {format}{Environment.NewLine}{exc}"); } var rawResult = TService.ProjectGetModAfter(nKey, dtRif); await Task.Delay(1); // converto in dizionario x uscita... listRec = rawResult.ToDictionary(x => x.ProjDbId, x => x.IsArchived); } return listRec; } /// /// Processa una chiamata POST per l'invio di un oggetto di aggiornamento da Dictionary [projCloudId,stato] /// POST: api/Projects/proj-arch-send/00000000-0000-0000-0000-000000000000 /// /// token comunicazione /// Bool esecuzione update dei proj ricevuti [HttpPost("proj-arch-send/{id}")] public async Task ProjArchivedSend(string id, [FromBody] RestPayload.ProjStatusData rawData) { // attenzione: si potrebbe dover verificare la data-ora modifica (per ogni record) x decidere update e/o bool answ = false; // verifico ci sia valore da processare if (!string.IsNullOrEmpty(id) && rawData != null) { // in primis recupero codice chiave da token... int nKey = await MTAdmService.MainKeyByToken(id); if (nKey > 0) { // processo update! if (rawData.ProjStatusList != null) { try { answ = await TService.ProjectUpdArchived(nKey, rawData.ProjStatusList); } catch (Exception exc) { Log.Error($"ProjectsController.ProjArchivedSend | Errore in fase update stato archived per {rawData.ProjStatusList.Count} rec{Environment.NewLine}{exc}"); } // resetto cache redis await MTAdmService.FlushRedisCache(); // broadcast update via redis, indico nKey x update puntuale MService.QueUpdProj.sendMessage($"{nKey}"); } } } return answ; } /// /// Processa una chiamata POST per l'invio di un oggetto di aggiornamento info produzione progetto /// PUT: api/Inventory/upsert/00000000-0000-0000-0000-000000000000 /// /// token comunicazione /// ID del progetto creato da usare come CloudId [HttpPost("prod-update/{id}")] public async Task prodUpdate(string id, [FromBody] RestPayload.ProdInfoData rawData) { bool answ = false; // verifico ci sia valore da processare if (!string.IsNullOrEmpty(id) && rawData != null) { // in primis recupero codice chiave da token... int nKey = await MTAdmService.MainKeyByToken(id); if (nKey > 0) { // recupero il tipo di info comprese if (rawData.ProjectProgress != null) { var cRec = rawData.ProjectProgress; try { answ = await TService.ProjectSetProgr(nKey, cRec.ProjCloudId, cRec.ProcTimeReal, cRec.ValAct, cRec.ValMax); } catch (Exception exc) { Log.Error($"ProjectsController.upsert | Errore in fase salvataggio ProjectDTO{Environment.NewLine}{exc}"); } // resetto cache redis await MTAdmService.FlushRedisCache(); // broadcast update via redis, indico nKey x update puntuale MService.QueUpdProj.sendMessage($"{nKey}"); } } } return answ; } /// /// Processa una chiamata POST per l'invio di un oggetto di upsert progetto /// PUT: api/Inventory/upsert/00000000-0000-0000-0000-000000000000 /// /// token comunicazione /// ID del progetto creato da usare come CloudId [HttpPost("upsert/{id}")] public async Task upsert(string id, [FromBody] RestPayload.Projects rawData) { int answ = 0; // verifico ci sia valore if (!string.IsNullOrEmpty(id) && rawData != null && rawData.Project != null) { // in primis recupero codice chiave da token... int nKey = await MTAdmService.MainKeyByToken(id); if (nKey > 0) { // converto ProjDto --> DB var currRec = TService.ProjectFromDto(rawData.Project); try { answ = await TService.ProjectUpsert(nKey, currRec); } catch (Exception exc) { Log.Error($"ProjectsController.upsert | Errore in fase salvataggio ProjectDTO{Environment.NewLine}{exc}"); } // resetto cache redis await MTAdmService.FlushRedisCache(); // broadcast update via redis, indico nKey x update puntuale MService.QueUpdProj.sendMessage($"{nKey}"); } } return answ; } #endregion Public Methods #region Private Fields private static JsonSerializerSettings? JSSettings; /// /// Classe per logging /// private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); #endregion Private Fields #region Private Properties private MessageService MService { get; set; } = null!; private MTAdminService MTAdmService { get; set; } = null!; private TenantService TService { get; set; } = null!; #endregion Private Properties } }