using System.Text; using MesaFabApproval.Shared.Models; using Microsoft.Extensions.Caching.Memory; namespace MesaFabApproval.API.Services; public interface IPCRBService { public Task CreateNewPCRB(PCRB pcrb); public Task> GetAllPCRBs(bool bypassCache); public Task GetPCRBByPlanNumber(int planNumber, bool bypassCache); public Task GetPCRBByTitle(string title, bool bypassCache); public Task UpdatePCRB(PCRB pcrb); public Task DeletePCRB(int planNumber); } public class PCRBService : IPCRBService { private readonly ILogger _logger; private readonly IDalService _dalService; private readonly IMemoryCache _cache; private readonly IUserService _userService; public PCRBService(ILogger logger, IDalService dalService, IMemoryCache cache, IUserService userService) { _logger = logger ?? throw new ArgumentNullException("ILogger not injected"); _dalService = dalService ?? throw new ArgumentNullException("IDalService not injected"); _cache = cache ?? throw new ArgumentNullException("IMemoryCache not injected"); _userService = userService ?? throw new ArgumentNullException("IUserService not injected"); } public async Task CreateNewPCRB(PCRB pcrb) { try { _logger.LogInformation("Attempting to create new PCRB"); if (pcrb is null) throw new ArgumentNullException("PCRB cannot be null"); StringBuilder queryBuilder = new(); queryBuilder.Append("insert into CCChangeControl (OwnerID, Title, ChangeLevel, ReasonForChange, "); queryBuilder.Append("ChangeDescription, IsITAR, CurrentStep, InsertTimeStamp, LastUpdateDate) "); queryBuilder.Append($"values ({pcrb.OwnerID}, '{pcrb.Title}', '{pcrb.ChangeLevel}', "); queryBuilder.Append($"'{pcrb.ReasonForChange}', '{pcrb.ChangeDescription}', "); queryBuilder.Append($"{Convert.ToInt32(pcrb.IsITAR)}, {pcrb.CurrentStep}, "); queryBuilder.Append($"'{pcrb.InsertTimeStamp.ToString("yyyy-MM-dd HH:mm:ss")}', "); queryBuilder.Append($"'{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')"); int rowsCreated = await _dalService.ExecuteAsync(queryBuilder.ToString()); if (rowsCreated <= 0) throw new Exception("unable to insert new PCRB in the database"); } catch (Exception ex) { _logger.LogError($"Unable to create new PCRB, because {ex.Message}"); throw; } } public async Task> GetAllPCRBs(bool bypassCache) { try { _logger.LogInformation("Attempting to get all PCRBs"); IEnumerable? allPCRBs = null; if (!bypassCache) allPCRBs = _cache.Get>("allPCRBs"); if (allPCRBs is null) { string sql = "select * from CCChangeControl"; allPCRBs = (await _dalService.QueryAsync(sql)).ToList(); foreach (PCRB pcrb in allPCRBs) { if (string.IsNullOrWhiteSpace(pcrb.OwnerName) && pcrb.OwnerID > 0) pcrb.OwnerName = (await _userService.GetUserByUserId(pcrb.OwnerID)).GetFullName(); } _cache.Set("allPCRBs", allPCRBs, DateTimeOffset.Now.AddHours(1)); } if (allPCRBs is null || allPCRBs.Count() == 0) throw new Exception("no PCRBs found"); return allPCRBs; } catch (Exception ex) { _logger.LogError($"Unable to get all PCRBs, because {ex.Message}"); throw; } } public async Task GetPCRBByPlanNumber(int planNumber, bool bypassCache) { try { _logger.LogInformation("Attempting to get a PCRB by plan#"); if (planNumber <= 0) throw new ArgumentException($"{planNumber} is not a valid PCRB#"); PCRB? pcrb = null; if (!bypassCache) pcrb = _cache.Get($"pcrb{planNumber}"); if (pcrb is null) { string sql = $"select * from CCChangeControl where PlanNumber={planNumber}"; pcrb = (await _dalService.QueryAsync(sql)).FirstOrDefault(); if (pcrb is not null) { if (string.IsNullOrWhiteSpace(pcrb.OwnerName) && pcrb.OwnerID > 0) pcrb.OwnerName = (await _userService.GetUserByUserId(pcrb.OwnerID)).GetFullName(); _cache.Set($"pcrb{planNumber}", pcrb, DateTimeOffset.Now.AddHours(1)); _cache.Set($"pcrb{pcrb.Title}", pcrb, DateTimeOffset.Now.AddHours(1)); } } if (pcrb is null) throw new Exception($"unable to find PCRB {planNumber}"); return pcrb; } catch (Exception ex) { _logger.LogError($"Unable to get PCRB by Plan #, because {ex.Message}"); throw; } } public async Task GetPCRBByTitle(string title, bool bypassCache) { try { _logger.LogInformation("Attempting to get a PCRB by title"); if (string.IsNullOrWhiteSpace(title)) throw new ArgumentException("Title cannot be null or empty"); PCRB? pcrb = null; if (!bypassCache) pcrb = _cache.Get($"pcrb{title}"); if (pcrb is null) { string sql = $"select * from CCChangeControl where Title='{title}'"; pcrb = (await _dalService.QueryAsync(sql)).FirstOrDefault(); if (pcrb is not null) { if (string.IsNullOrWhiteSpace(pcrb.OwnerName) && pcrb.OwnerID > 0) pcrb.OwnerName = (await _userService.GetUserByUserId(pcrb.OwnerID)).GetFullName(); _cache.Set($"pcrb{title}", pcrb, DateTimeOffset.Now.AddHours(1)); _cache.Set($"pcrb{pcrb.PlanNumber}", pcrb, DateTimeOffset.Now.AddHours(1)); } } if (pcrb is null) throw new Exception($"unable to find PCRB {title}"); return pcrb; } catch (Exception ex) { _logger.LogError($"Unable to get PCRB by title, because {ex.Message}"); throw; } } public async Task UpdatePCRB(PCRB pcrb) { try { _logger.LogInformation($"Attempting to update PCRB"); if (pcrb is null) throw new ArgumentNullException("PCRB cannot be null"); StringBuilder queryBuilder = new(); queryBuilder.Append($"update CCChangeControl set OwnerID={pcrb.OwnerID}, "); queryBuilder.Append($"Title='{pcrb.Title}', ChangeLevel='{pcrb.ChangeLevel}', "); queryBuilder.Append($"CurrentStep={pcrb.CurrentStep}, ReasonForChange='{pcrb.ReasonForChange}', "); queryBuilder.Append($"ChangeDescription='{pcrb.ChangeDescription}', "); queryBuilder.Append($"IsITAR={Convert.ToInt32(pcrb.IsITAR)}, "); queryBuilder.Append($"InsertTimeStamp='{pcrb.InsertTimeStamp.ToString("yyyy-MM-dd HH:mm:ss")}', "); queryBuilder.Append($"LastUpdateDate='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' "); queryBuilder.Append($"where PlanNumber={pcrb.PlanNumber}"); int rowsAffected = await _dalService.ExecuteAsync(queryBuilder.ToString()); if (rowsAffected <= 0) throw new Exception("unable to perform update in database"); _cache.Set($"pcrb{pcrb.Title}", pcrb, DateTimeOffset.Now.AddHours(1)); _cache.Set($"pcrb{pcrb.PlanNumber}", pcrb, DateTimeOffset.Now.AddHours(1)); IEnumerable? allPCRBs = _cache.Get>("allPCRBs"); if (allPCRBs is not null) { List pcrbList = allPCRBs.ToList(); pcrbList.RemoveAll(p => p.PlanNumber == pcrb.PlanNumber); pcrbList.Add(pcrb); _cache.Set("allPCRBs", pcrbList, DateTimeOffset.Now.AddHours(1)); } } catch (Exception ex) { _logger.LogError($"Unable to update PCRB, because {ex.Message}"); throw; } } public async Task DeletePCRB(int planNumber) { try { _logger.LogInformation($"Attempting to delete PCRB {planNumber}"); if (planNumber <= 0) throw new ArgumentException($"{planNumber} is not a valid PCRB Plan #"); string sql = $"delete from CCChangeControl where PlanNumber={planNumber}"; int rowsAffected = await _dalService.ExecuteAsync(sql); if (rowsAffected <= 0) throw new Exception("delete operation failed in database"); IEnumerable? allPCRBs = _cache.Get>("allPCRBs"); if (allPCRBs is not null) { List pcrbList = allPCRBs.ToList(); pcrbList.RemoveAll(p => p.PlanNumber == planNumber); _cache.Set("allPCRBs", pcrbList, DateTimeOffset.Now.AddHours(1)); } } catch (Exception ex) { _logger.LogError($"Unable to delete PCRB {planNumber}, because {ex.Message}"); throw; } } }