using Core; using LiMan.APi.Data; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using NLog; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LiMan.APi.Controllers { /// /// Controller livello LICENZA /// [Route("api/licenza")] [ApiController] public class LicenzaController : ControllerBase { #region Public Constructors /// /// Init Controller Licenze /// /// /// /// public LicenzaController(IConfiguration configuration, IEmailSender emailSender, ApiDataService DataService) { _configuration = configuration; _emailSender = emailSender; dataService = DataService; Log.Info("Avviata classe LicenzaController"); } #endregion Public Constructors #region Public Methods /// /// Recupera dati Licenza Applicativa (id licenza + num utenze) dati cliente + programma + licenza ATTUALE /// /// GET api/licenza/id?CodApp=xxx&Chiave=yyyy /// /// Codice cliente/Installazione /// Codice Applicazione /// Chiave licenza da validare /// [HttpGet("{id}")] public async Task> Get(string id, string CodApp, string Chiave) { var result = await dataService.LicenzeSearch(id, CodApp, Chiave, false); await dataService.recordCall(id, CodApp, $"GET:api/licenza:{Chiave}"); return result; } /// /// Effettua verifica scadenze licenze secondo 3 livelli dati da diversi orizzonti temporali /// - urgente: entro 1 settimana /// - importante: entro 1 mese /// - info: entro 2 mesi /// /// [HttpGet("CheckScadenze")] public async Task Get() { // oggetti base string answ = "ND"; string msgBody = ""; StringBuilder sbMain = new StringBuilder(); StringBuilder sbActions = new StringBuilder(); StringBuilder sbAllProj = new StringBuilder(); // orizzonti da valutare DateTime oggi = DateTime.Today; doLog("Esito della verifica Licenze (scadute/in scadenza)", logType.info, ref sbMain); // verifico quelle GIA' SCADUTE (< oggi) List elencoScadute = await dataService.LicenzeExpiring(DateTime.MinValue, oggi); List elencoWeek = await dataService.LicenzeExpiring(oggi, oggi.AddDays(8)); List elencoMonth = await dataService.LicenzeExpiring(oggi.AddDays(8), oggi.AddDays(1).AddMonths(1)); List elencoTrim = await dataService.LicenzeExpiring(oggi.AddDays(1).AddMonths(1), oggi.AddDays(1).AddMonths(3)); int numScadute = elencoScadute.Count; int numWeek = elencoWeek.Count; int numMonth = elencoMonth.Count; int numTrim = elencoTrim.Count; // display scadute scadute... msgBody += formatCheckPeriodo(elencoScadute, "Licenze SCADUTE", "font-size: 1.3em; color: #D62424;"); msgBody += formatCheckPeriodo(elencoWeek, "Licenze in scadenza nella SETTIMANA", "font-size: 1.2em; color: #DF701C;"); msgBody += formatCheckPeriodo(elencoMonth, "Licenze in scadenza nel MESE", "font-size: 1.15em; color: #A99C45;"); msgBody += formatCheckPeriodo(elencoTrim, "Licenze in scadenza nel TRIMESTRE", "font-size: 1.1em; color: #9Dc935;"); // predispongo email string msgTopic = "LiMan: verifica Licenze in scadenza"; // invio email string destList = _configuration["MailDest:ExpiryNotify"]; await sendEmailExpiry(destList, msgTopic, msgBody.Replace($"{Environment.NewLine}", "
")); // ritorno solo LOG azioni answ = $"Scadute {numScadute} | Settimana: {numWeek} | Mese: {numMonth} | Trimestre: {numTrim}"; return answ; } /// /// Effettua test invio email /// /// [HttpGet("test-email")] public async Task TestEmail() { // oggetti base string answ = "ND"; string msgBody = "Prova invio email a destinatari MailDest:ExpiryNotify"; // predispongo email string msgTopic = "LiMan: Test invio email!"; // invio email string destList = _configuration["MailDest:ExpiryNotify"]; await sendEmailExpiry(destList, msgTopic, msgBody.Replace($"{Environment.NewLine}", "
")); // ritorno solo LOG azioni answ = $"Test effettuato!"; return answ; } /// POST api/licenza /// /// Recupera dati Licenza Applicativa (id licenza + num utenze) dati cliente + programma + /// licenza ATTUALE /// /// Info licenza in formato LicenseCoord /// [HttpPost()] public async Task> Post([FromBody] LicenseCoord AppInfo) { var result = await dataService.LicenzeSearch(AppInfo.CodInst, AppInfo.CodApp, AppInfo.MasterKey, false); await dataService.recordCall(AppInfo.CodInst, AppInfo.CodApp, $"POST:api/licenza:{AppInfo.MasterKey}"); return result; } /// POST api/licenza/refreshPayload /// /// Effettua refresh del payload calcolato ed aggiorna record ed infine lo restituisce /// /// Info licenza in formato LicenseCoord [HttpPost("refreshPayload")] public async Task RefreshPayload([FromBody] LicenseCoord AppInfo) { var done = await dataService.LicenzaRefreshPayload(AppInfo); await dataService.recordCall(AppInfo.CodInst, AppInfo.CodApp, $"POST:api/licenza/refreshPayload:{AppInfo.MasterKey}"); return done; } #endregion Public Methods #region Protected Enums protected enum logType { none, local, trace, info, warn } #endregion Protected Enums #region Protected Properties /// /// Dataservice x accesso DB /// protected ApiDataService dataService { get; set; } #endregion Protected Properties #region Protected Methods /// /// Effettua log del tipo richiesto aggiungendo riga anche allo stringbuilder indicato /// /// /// /// protected void doLog(string message, logType tipoLog, ref StringBuilder currSB) { bool doLine = true; switch (tipoLog) { case logType.info: Log.Info(message); break; case logType.trace: Log.Trace(message); break; case logType.warn: Log.Warn(message); break; case logType.local: break; default: case logType.none: doLine = false; break; } if (doLine) { currSB.AppendLine(message); } else { currSB.Append(message); } } protected string formatCheckPeriodo(List elencoLicenze, string tipoVerifica, string titleStyle) { StringBuilder sbMain = new StringBuilder(); doLog($"
", logType.none, ref sbMain); int numScadute = elencoLicenze.Count; doLog($"{tipoVerifica}: {numScadute}", logType.info, ref sbMain); doLog("
", logType.none, ref sbMain); if (elencoLicenze.Count == 0) { doLog($" - nessuna", logType.info, ref sbMain); } else { foreach (var item in elencoLicenze) { doLog($" - {item.Scadenza:yyyy.MM.dd} | {item.CodInst} | {item.Descrizione}", logType.info, ref sbMain); } } doLog("
", logType.none, ref sbMain); doLog("
", logType.none, ref sbMain); return sbMain.ToString(); } /// /// Invio email a lista ExpiryNotify /// /// Elenco destinatari comma separated /// Oggetto Email /// MEssaggio /// protected async Task sendEmailExpiry(string destList, string subject, string message) { List emailDestList = destList.Split(",").ToList(); foreach (var dest in emailDestList) { try { await _emailSender.SendEmailAsync(dest, subject, message); } catch (Exception exc) { Log.Error($"Eccezione durante invio email:{Environment.NewLine}dest: {dest} | subject {subject}{Environment.NewLine}{exc}"); } } } #endregion Protected Methods #region Private Fields /// /// Classe per logging /// private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); private readonly IEmailSender _emailSender; private IConfiguration _configuration; #endregion Private Fields } }