PCRB follow up client side logic

This commit is contained in:
Chase Tucker
2025-03-19 10:01:35 -07:00
parent 4871668a90
commit cc4781b990
45 changed files with 3082 additions and 1008 deletions

View File

@ -1,4 +1,5 @@
using MesaFabApproval.API.Services;
using MesaFabApproval.API.Utilities;
using MesaFabApproval.Shared.Models;
using MesaFabApproval.Shared.Services;
@ -11,13 +12,13 @@ namespace MesaFabApproval.API.Controllers;
public class ApprovalController : ControllerBase {
private readonly ILogger<ApprovalController> _logger;
private readonly IApprovalService _approvalService;
private readonly IMonInWorkerClient _monInClient;
private readonly IMonInUtils _monInUtils;
public ApprovalController(ILogger<ApprovalController> logger, IApprovalService approvalService,
IMonInWorkerClient monInClient) {
IMonInUtils monInUtils) {
_logger = logger ?? throw new ArgumentNullException("ILogger not injected");
_approvalService = approvalService ?? throw new ArgumentNullException("IApprovalService not injected");
_monInClient = monInClient ?? throw new ArgumentNullException("IMonInWorkerClient not injected");
_monInUtils = monInUtils ?? throw new ArgumentNullException("IMonInUtils not injected");
}
[HttpPost]
@ -39,26 +40,19 @@ public class ApprovalController : ControllerBase {
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
_logger.LogWarning($"Argument error when attempting to create approval: {errorMessage}");
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot create new approval, because {ex.Message}";
_logger.LogError(errorMessage);
return Problem(errorMessage);
} finally {
string metricName = "CreateApproval";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
@ -81,26 +75,19 @@ public class ApprovalController : ControllerBase {
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
_logger.LogWarning($"Argument error when getting approvals for issue {issueId}: {errorMessage}");
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get approvals, because {ex.Message}";
_logger.LogError(errorMessage);
return Problem(errorMessage);
} finally {
string metricName = "GetApprovalsForIssueId";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
@ -123,26 +110,19 @@ public class ApprovalController : ControllerBase {
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
_logger.LogWarning($"Argument error when getting approvals for user {userId}: {errorMessage}");
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get approvals, because {ex.Message}";
_logger.LogError(errorMessage);
return Problem(errorMessage);
} finally {
string metricName = "GetApprovalsForUserId";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
@ -165,26 +145,19 @@ public class ApprovalController : ControllerBase {
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
_logger.LogWarning($"Argument error when getting approval group members for sub role {subRoleId}: {errorMessage}");
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get approval group members, because {ex.Message}";
_logger.LogError(errorMessage);
return Problem(errorMessage);
} finally {
string metricName = "GetApprovalsGroupMembers";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
@ -197,7 +170,7 @@ public class ApprovalController : ControllerBase {
string errorMessage = "";
try {
_logger.LogInformation($"Attempting to update approval");
_logger.LogInformation("Attempting to update approval");
if (approval is null) throw new ArgumentNullException($"approval cannot be null");
@ -207,26 +180,54 @@ public class ApprovalController : ControllerBase {
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
_logger.LogWarning($"Argument error when attempting to update approval: {errorMessage}");
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot update approval, because {ex.Message}";
_logger.LogError(errorMessage);
return Problem(errorMessage);
} finally {
string metricName = "UpdateApproval";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
[HttpDelete]
[Route("approval")]
public async Task<IActionResult> DeleteApproval(int approvalID) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation($"Attempting to delete approval {approvalID}");
if (approvalID <= 0) throw new ArgumentException("Invalid approval ID");
await _approvalService.DeleteApproval(approvalID);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
_logger.LogWarning($"Argument error when attempting to delete approval: {errorMessage}");
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot delete approval, because {ex.Message}";
_logger.LogError(errorMessage);
return Problem(errorMessage);
} finally {
string metricName = "UpdateApproval";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
@ -249,26 +250,19 @@ public class ApprovalController : ControllerBase {
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
_logger.LogWarning($"Argument error when attempting to approve: {errorMessage}");
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot approve, because {ex.Message}";
_logger.LogError(errorMessage);
return Problem(errorMessage);
} finally {
string metricName = "Approve";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
@ -291,26 +285,19 @@ public class ApprovalController : ControllerBase {
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
_logger.LogWarning($"Argument error when attempting to deny approval: {errorMessage}");
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Approval denial failed, because {ex.Message}";
_logger.LogError(errorMessage);
return Problem(errorMessage);
} finally {
string metricName = "Deny";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
@ -333,26 +320,19 @@ public class ApprovalController : ControllerBase {
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
_logger.LogWarning($"Argument error when attempting to get role ID by role name: {errorMessage}");
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get role ID, because {ex.Message}";
_logger.LogError(errorMessage);
return Problem(errorMessage);
} finally {
string metricName = "GetRoleIdForRoleName";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
@ -376,26 +356,19 @@ public class ApprovalController : ControllerBase {
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
_logger.LogWarning($"Argument error when attempting to get sub roles by sub role name: {errorMessage}");
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get role ID, because {ex.Message}";
_logger.LogError(errorMessage);
return Problem(errorMessage);
} finally {
string metricName = "GetSubRoleIdForSubRoleName";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
}

View File

@ -790,6 +790,42 @@ public class PCRBController : ControllerBase {
}
}
[HttpPost]
[Route("pcrb/notify/approver")]
public async Task<IActionResult> NotifyApprover(PCRBNotification notification) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to notify an approver");
if (notification is null) throw new ArgumentNullException("notification cannot be null");
if (notification.PCRB is null) throw new ArgumentNullException("PCRB cannot be null");
if (notification.Approval is null) throw new ArgumentNullException("approval cannot be null");
if (string.IsNullOrWhiteSpace(notification.Message)) throw new ArgumentException("message cannot be null or empty");
await _pcrbService.NotifyApprover(notification);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Unable to notify an approver, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "NotifyPCRBApprover";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
[HttpPost]
[Route("pcrb/notify/approvers")]
public async Task<IActionResult> NotifyApprovers(PCRBNotification notification) {
@ -937,7 +973,7 @@ public class PCRBController : ControllerBase {
string errorMessage = "";
try {
_logger.LogInformation($"Attempting to get attendees for plan# {planNumber}");
_logger.LogInformation($"Attempting to get follow ups for plan# {planNumber}");
if (planNumber <= 0) throw new ArgumentException($"{planNumber} is not a valid PCRB Plan#");
@ -1026,4 +1062,136 @@ public class PCRBController : ControllerBase {
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
[HttpPost]
[Route("pcrb/followUpComment")]
public async Task<IActionResult> CreateFollowUpComment(PCRBFollowUpComment comment) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to create follow up comment");
if (comment is null) throw new ArgumentNullException("comment cannot be null");
await _pcrbService.CreateFollowUpComment(comment);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Unable to create follow up comment, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "CreatePCRBFollowUpComment";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
[HttpGet]
[Route("pcrb/followUpComments")]
public async Task<IActionResult> GetFollowUpCommentsByPlanNumber(int planNumber, bool bypassCache) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation($"Attempting to get follow up comments for plan# {planNumber}");
if (planNumber <= 0) throw new ArgumentException($"{planNumber} is not a valid PCRB Plan#");
List<PCRBFollowUpComment> comments = (await _pcrbService.GetFollowUpCommentsByPlanNumber(planNumber, bypassCache)).ToList();
return Ok(comments);
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get follow up comments for plan# {planNumber}, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetPCRBFollowUpComments";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
[HttpPut]
[Route("pcrb/followUpComment")]
public async Task<IActionResult> UpdateFollowUpComment(PCRBFollowUpComment comment) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to update follow up comment");
if (comment is null) throw new ArgumentNullException("comment cannot be null");
await _pcrbService.UpdateFollowUpComment(comment);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Unable to update follow up comment, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "UpdatePCRBFollowUpComment";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
[HttpDelete]
[Route("pcrb/followUpComment")]
public async Task<IActionResult> DeleteFollowUpComment(int id) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to delete follow up comment");
if (id <= 0) throw new ArgumentException($"{id} is not a valid PCRB follow up comment ID");
await _pcrbService.DeleteFollowUpComment(id);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Unable to delete follow up comment, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "DeletePCRBFollowUpComment";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInUtils.PostMetrics(metricName, millisecondsDiff, isArgumentError, isInternalError);
}
}
}

View File

@ -13,6 +13,7 @@ public interface IApprovalService {
Task<IEnumerable<User>> GetApprovalGroupMembers(int subRoleId);
Task CreateApproval(Approval approval);
Task UpdateApproval(Approval approval);
Task DeleteApproval(int approvalID);
Task Approve(Approval approval);
Task Deny(Approval approval);
Task<IEnumerable<Approval>> GetApprovalsForIssueId(int issueId, bool bypassCache);
@ -40,12 +41,11 @@ public class ApprovalService : IApprovalService {
StringBuilder queryBuilder = new();
queryBuilder.Append("insert into Approval (IssueID, RoleName, SubRole, UserID, SubRoleID, ItemStatus, ");
queryBuilder.Append("AssignedDate, DocumentTypeID, DisplayDeniedDocument, Step, TaskID) ");
queryBuilder.Append($"values ({approval.IssueID}, '{approval.RoleName}', '{approval.SubRole}', {approval.UserID}, ");
queryBuilder.Append($"{approval.SubRoleID}, 0, '{approval.AssignedDate.ToString("yyyy-MM-dd HH:mm:ss")}', ");
queryBuilder.Append($"3, 0, {approval.Step}, {approval.TaskID});");
queryBuilder.Append("AssignedDate, DocumentTypeID, DisplayDeniedDocument, Step, TaskID, CompletedDate) ");
queryBuilder.Append("values (@IssueID, @RoleName, @SubRole, @UserID, @SubRoleID, 0, @AssignedDate, 3, 0, @Step, ");
queryBuilder.Append("@TaskID, @CompletedDate)");
int rowsCreated = await _dalService.ExecuteAsync(queryBuilder.ToString());
int rowsCreated = await _dalService.ExecuteAsync(queryBuilder.ToString(), approval);
if (rowsCreated <= 0) throw new Exception("Unable to insert approval in database");
@ -70,19 +70,16 @@ public class ApprovalService : IApprovalService {
if (approvals is null || approvals.Count() == 0) {
StringBuilder queryBuilder = new();
queryBuilder.Append("select a.*, src.SubRoleCategoryItem from Approval a ");
queryBuilder.Append("join SubRole sr on a.SubRoleID=sr.SubRoleID ");
queryBuilder.Append("join SubRoleCategory src on sr.SubRoleCategoryID=src.SubRoleCategoryID ");
queryBuilder.Append("left outer join SubRole sr on a.SubRoleID=sr.SubRoleID ");
queryBuilder.Append("left outer join SubRoleCategory src on sr.SubRoleCategoryID=src.SubRoleCategoryID ");
queryBuilder.Append($"where a.IssueID={issueId}");
approvals = (await _dalService.QueryAsync<Approval>(queryBuilder.ToString())).ToList();
foreach (Approval approval in approvals) {
int successfulUpdates = 0;
User? user = await _userService.GetUserByUserId(approval.UserID);
if (user is not null) {
approval.User = user;
successfulUpdates++;
}
if (approval.ItemStatus < 0)
@ -91,6 +88,9 @@ public class ApprovalService : IApprovalService {
approval.StatusMessage = "Assigned";
if (approval.ItemStatus > 0)
approval.StatusMessage = "Approved";
if (string.IsNullOrWhiteSpace(approval.SubRoleCategoryItem))
approval.SubRoleCategoryItem = approval.RoleName;
}
_cache.Set($"approvals{issueId}", approvals, DateTimeOffset.Now.AddMinutes(5));
@ -217,8 +217,8 @@ public class ApprovalService : IApprovalService {
if (approvals is null) {
StringBuilder queryBuilder = new();
queryBuilder.Append($"select a.*, src.SubRoleCategoryItem from Approval a ");
queryBuilder.Append("join SubRole sr on a.SubRoleID=sr.SubRoleID ");
queryBuilder.Append("join SubRoleCategory src on sr.SubRoleCategoryID=src.SubRoleCategoryID ");
queryBuilder.Append("left outer join SubRole sr on a.SubRoleID=sr.SubRoleID ");
queryBuilder.Append("left outer join SubRoleCategory src on sr.SubRoleCategoryID=src.SubRoleCategoryID ");
queryBuilder.Append($"where UserID={userId} and ItemStatus=0 and ");
queryBuilder.Append($"(AssignedDate is not null and ");
queryBuilder.Append($"AssignedDate <= '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' and ");
@ -265,6 +265,23 @@ public class ApprovalService : IApprovalService {
}
}
public async Task DeleteApproval(int approvalID) {
try {
_logger.LogInformation($"Attempting to delete approval with ID: {approvalID}");
if (approvalID <= 0) throw new ArgumentException("Invalid approval ID");
string sql = "delete from Approval where ApprovalID=@ApprovalID";
int rowsDeleted = await _dalService.ExecuteAsync(sql, new { ApprovalID = approvalID });
if (rowsDeleted <= 0) throw new Exception("unable to delete approval from database");
} catch (Exception ex) {
_logger.LogError($"Unable to delete approval with ID: {approvalID}, because {ex.Message}");
throw;
}
}
public async Task Approve(Approval approval) {
try {
_logger.LogInformation("Attempting to submit approval");

View File

@ -144,7 +144,7 @@ public class AuthenticationService : IAuthenticationService {
Audience = _jwtAudience,
Subject = identity,
NotBefore = DateTime.Now,
Expires = DateTime.Now.AddHours(8),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};

View File

@ -34,6 +34,7 @@ public interface IPCRBService {
Task UpdatePCR3Document(PCR3Document document);
Task<IEnumerable<PCR3Document>> GetPCR3DocumentsForPlanNumber(int planNumber, bool bypassCache);
Task NotifyNewApprovals(PCRB pcrb);
Task NotifyApprover(PCRBNotification notification);
Task NotifyApprovers(PCRBNotification notification);
Task NotifyOriginator(PCRBNotification notification);
Task NotifyResponsiblePerson(PCRBActionItemNotification notification);
@ -41,6 +42,10 @@ public interface IPCRBService {
Task<IEnumerable<PCRBFollowUp>> GetFollowUpsByPlanNumber(int planNumber, bool bypassCache);
Task UpdateFollowUp(PCRBFollowUp followUp);
Task DeleteFollowUp(int id);
Task CreateFollowUpComment(PCRBFollowUpComment comment);
Task<IEnumerable<PCRBFollowUpComment>> GetFollowUpCommentsByPlanNumber(int planNumber, bool bypassCache);
Task UpdateFollowUpComment(PCRBFollowUpComment comment);
Task DeleteFollowUpComment(int id);
}
public class PCRBService : IPCRBService {
@ -110,6 +115,7 @@ public class PCRBService : IPCRBService {
foreach (PCRB pcrb in allPCRBs) {
if (string.IsNullOrWhiteSpace(pcrb.OwnerName) && pcrb.OwnerID > 0)
pcrb.OwnerName = (await _userService.GetUserByUserId(pcrb.OwnerID)).GetFullName();
pcrb.FollowUps = await GetFollowUpsByPlanNumber(pcrb.PlanNumber, bypassCache);
}
_cache.Set("allPCRBs", allPCRBs, DateTimeOffset.Now.AddHours(1));
@ -144,6 +150,8 @@ public class PCRBService : IPCRBService {
if (string.IsNullOrWhiteSpace(pcrb.OwnerName) && pcrb.OwnerID > 0)
pcrb.OwnerName = (await _userService.GetUserByUserId(pcrb.OwnerID)).GetFullName();
pcrb.FollowUps = await GetFollowUpsByPlanNumber(pcrb.PlanNumber, bypassCache);
_cache.Set($"pcrb{planNumber}", pcrb, DateTimeOffset.Now.AddHours(1));
_cache.Set($"pcrb{pcrb.Title}", pcrb, DateTimeOffset.Now.AddHours(1));
}
@ -659,6 +667,62 @@ public class PCRBService : IPCRBService {
}
}
public async Task NotifyApprover(PCRBNotification notification) {
try {
_logger.LogInformation("Attempting to send a notification to an approver");
if (notification is null) throw new ArgumentNullException("notification cannot be null");
if (notification.PCRB is null) throw new ArgumentNullException("PCRB cannot be null");
if (notification.Approval is null) throw new ArgumentNullException("approval cannot be null");
User user = await _userService.GetUserByUserId(notification.Approval.UserID);
List<MailAddress> toAddresses = new();
toAddresses.Add(new MailAddress(user.Email));
List<string> ccEmails = new List<string>();
if (notification.NotifyQaPreApprover) {
IEnumerable<User> qaPreApprovers = await GetQAPreApprovers();
foreach (User qaPreApprover in qaPreApprovers) {
if (!ccEmails.Contains(qaPreApprover.Email))
ccEmails.Add(qaPreApprover.Email);
}
}
List<MailAddress> ccAddresses = new();
foreach (string email in ccEmails) {
ccAddresses.Add(new MailAddress(email));
}
StringBuilder sb = new();
string subject = string.Empty;
if (!string.IsNullOrWhiteSpace(notification.Subject)) {
subject = notification.Subject;
} else {
sb.Append($"[Approval Update] Mesa Fab Approval - PCRB# {notification.PCRB.PlanNumber} - ");
sb.Append($"{notification.PCRB.Title}");
subject = sb.ToString();
}
sb.Clear();
sb.Append($"{notification.Message} <br /> <br />");
sb.Append($"Click {_siteBaseUrl}/redirect?redirectPath=pcrb/{notification.PCRB.PlanNumber} ");
sb.Append("to view the PCRB.");
await _smtpService.SendEmail(toAddresses, ccAddresses, subject, sb.ToString());
notification.Approval.NotifyDate = DateTime.Now;
await _approvalService.UpdateApproval(notification.Approval);
} catch (Exception ex) {
_logger.LogError($"Unable to send notification to approver, because {ex.Message}");
throw;
}
}
public async Task NotifyApprovers(PCRBNotification notification) {
try {
_logger.LogInformation("Attempting to send notification to approvers");
@ -712,9 +776,28 @@ public class PCRBService : IPCRBService {
List<MailAddress> toAddresses = new();
toAddresses.Add(new MailAddress(user.Email));
List<MailAddress> ccAddresses = new();
List<string> ccEmails = new List<string>();
string subject = $"[Update] Mesa Fab Approval - PCRB# {notification.PCRB.PlanNumber} - {notification.PCRB.Title}";
if (notification.NotifyQaPreApprover) {
IEnumerable<User> qaPreApprovers = await GetQAPreApprovers();
foreach (User qaPreApprover in qaPreApprovers) {
if (!ccEmails.Contains(qaPreApprover.Email))
ccEmails.Add(qaPreApprover.Email);
}
}
List<MailAddress> ccAddresses = new();
foreach (string email in ccEmails) {
ccAddresses.Add(new MailAddress(email));
}
string subject = string.Empty;
if (!string.IsNullOrWhiteSpace(notification.Subject)) {
subject = notification.Subject;
} else {
subject = $"[Update] Mesa Fab Approval - PCRB# {notification.PCRB.PlanNumber} - {notification.PCRB.Title}";
}
StringBuilder bodyBuilder = new();
bodyBuilder.Append($"{notification.Message} <br /> <br />");
@ -763,8 +846,8 @@ public class PCRBService : IPCRBService {
if (followUp is null) throw new ArgumentNullException("follow up cannot be null");
StringBuilder queryBuilder = new();
queryBuilder.Append("insert into CCPCRBFollowUp (PlanNumber, Step, FollowUpDate, CompletedDate) ");
queryBuilder.Append("values (@PlanNumber, @Step, @FollowUpDate, @CompletedDate)");
queryBuilder.Append("insert into CCPCRBFollowUp (PlanNumber, Step, FollowUpDate, CompletedDate, UpdateDate) ");
queryBuilder.Append("values (@PlanNumber, @Step, @FollowUpDate, @CompletedDate, @UpdateDate)");
int rowsReturned = await _dalService.ExecuteAsync<PCRBFollowUp>(queryBuilder.ToString(), followUp);
@ -792,7 +875,7 @@ public class PCRBService : IPCRBService {
followUps = await _dalService.QueryAsync<PCRBFollowUp>(sql, new { PlanNumber = planNumber });
if (followUps is not null)
_cache.Set($"pcrbFollowUps{planNumber}", followUps, DateTimeOffset.Now.AddMinutes(15));
_cache.Set($"pcrbFollowUps{planNumber}", followUps, DateTimeOffset.Now.AddHours(1));
}
return followUps ?? new List<PCRBFollowUp>();
@ -811,7 +894,8 @@ public class PCRBService : IPCRBService {
StringBuilder queryBuilder = new();
queryBuilder.Append("update CCPCRBFollowUp set Step=@Step, FollowUpDate=@FollowUpDate, IsComplete=@IsComplete, ");
queryBuilder.Append("IsDeleted=@IsDeleted, CompletedDate=@CompletedDate, Comments=@Comments ");
queryBuilder.Append("IsDeleted=@IsDeleted, CompletedDate=@CompletedDate, IsPendingApproval=@IsPendingApproval, ");
queryBuilder.Append("UpdateDate=@UpdateDate ");
queryBuilder.Append("where ID=@ID");
int rowsAffected = await _dalService.ExecuteAsync<PCRBFollowUp>(queryBuilder.ToString(), followUp);
@ -840,6 +924,89 @@ public class PCRBService : IPCRBService {
}
}
public async Task CreateFollowUpComment(PCRBFollowUpComment comment) {
try {
_logger.LogInformation("Attempting to create PCRB follow up");
if (comment is null) throw new ArgumentNullException("comment cannot be null");
StringBuilder queryBuilder = new();
queryBuilder.Append("insert into CCPCRBFollowUpComments (PlanNumber, FollowUpID, Comment, CommentDate, UserID) ");
queryBuilder.Append("values (@PlanNumber, @FollowUpID, @Comment, @CommentDate, @UserID)");
int rowsReturned = await _dalService.ExecuteAsync<PCRBFollowUpComment>(queryBuilder.ToString(), comment);
if (rowsReturned <= 0) throw new Exception("unable to insert new follow up comment in the database");
} catch (Exception ex) {
_logger.LogError($"Unable to create new follow up comment, because {ex.Message}");
throw;
}
}
public async Task<IEnumerable<PCRBFollowUpComment>> GetFollowUpCommentsByPlanNumber(int planNumber, bool bypassCache) {
try {
_logger.LogInformation($"Attempting to fetch follow up comments for PCRB {planNumber}");
if (planNumber <= 0) throw new ArgumentException($"{planNumber} is not a valid PCRB Plan#");
IEnumerable<PCRBFollowUpComment>? comments = new List<PCRBFollowUpComment>();
if (!bypassCache)
comments = _cache.Get<IEnumerable<PCRBFollowUpComment>>($"pcrbFollowUpComments{planNumber}");
if (comments is null || comments.Count() == 0) {
string sql = "select * from CCPCRBFollowUpComments where PlanNumber=@PlanNumber";
comments = await _dalService.QueryAsync<PCRBFollowUpComment>(sql, new { PlanNumber = planNumber });
if (comments is not null)
_cache.Set($"pcrbFollowUpComments{planNumber}", comments, DateTimeOffset.Now.AddHours(1));
}
return comments ?? new List<PCRBFollowUpComment>();
} catch (Exception ex) {
_logger.LogError($"Unable to fetch follow up comments for PCRB {planNumber}, because {ex.Message}");
throw;
}
}
public async Task UpdateFollowUpComment(PCRBFollowUpComment comment) {
try {
_logger.LogInformation("Attempting to update a follow up");
if (comment is null)
throw new ArgumentNullException("comment cannot be null");
StringBuilder queryBuilder = new();
queryBuilder.Append("update CCPCRBFollowUpComments set Comment=@Comment, CommentDate=@CommentDate, ");
queryBuilder.Append("UserID=@UserID where ID=@ID");
int rowsAffected = await _dalService.ExecuteAsync<PCRBFollowUpComment>(queryBuilder.ToString(), comment);
if (rowsAffected <= 0) throw new Exception("update failed in database");
} catch (Exception ex) {
_logger.LogError($"Unable to update follow up comment, because {ex.Message}");
throw;
}
}
public async Task DeleteFollowUpComment(int id) {
try {
_logger.LogInformation($"Attempting to delete follow up comment {id}");
if (id <= 0) throw new ArgumentException($"{id} is not a valid follow up ID");
string sql = "delete from CCPCRBFollowUpComments where ID=@ID";
int rowsAffected = await _dalService.ExecuteAsync(sql, new { ID = id });
if (rowsAffected <= 0) throw new Exception("delete operation failed in database");
} catch (Exception ex) {
_logger.LogError($"Unable to delete follow up comment {id}, because {ex.Message}");
throw;
}
}
private async Task SaveAttachmentInDb(IFormFile file, PCRBAttachment attachment) {
try {
_logger.LogInformation($"Attempting to save attachment to database");
@ -863,4 +1030,34 @@ public class PCRBService : IPCRBService {
throw;
}
}
private async Task<IEnumerable<User>> GetQAPreApprovers() {
try {
_logger.LogInformation("Attempting to fetch QA Pre-Approvers");
IEnumerable<User> qaPreApprovers = new List<User>();
int qaPreApproverRoleId = await _approvalService.GetRoleIdForRoleName("QA_PRE_APPROVAL");
if (qaPreApproverRoleId > 0) {
IEnumerable<SubRole> qaPreApproverSubRoles =
await _approvalService.GetSubRolesForSubRoleName("QA_PRE_APPROVAL", qaPreApproverRoleId);
foreach (SubRole subRole in qaPreApproverSubRoles) {
IEnumerable<User> members =
await _approvalService.GetApprovalGroupMembers(subRole.SubRoleID);
foreach (User member in members) {
if (!qaPreApprovers.Any(u => u.UserID == member.UserID))
qaPreApprovers = qaPreApprovers.Append(member);
}
}
}
return qaPreApprovers;
} catch (Exception ex) {
_logger.LogError($"Unable to fetch QA Pre-Approvers, because {ex.Message}");
throw;
}
}
}