Created CA follow up worker
This commit is contained in:
10
FabApprovalWorkerService/Models/CorrectiveAction.cs
Normal file
10
FabApprovalWorkerService/Models/CorrectiveAction.cs
Normal file
@ -0,0 +1,10 @@
|
||||
namespace FabApprovalWorkerService.Models;
|
||||
|
||||
public class CorrectiveAction {
|
||||
public required int CANo { get; set; }
|
||||
public bool ApprovalStatus { get; set; }
|
||||
public DateTime FollowUpDate { get; set; }
|
||||
public DateTime ClosedDate { get; set; }
|
||||
public int QAID { get; set; }
|
||||
public required string CATitle { get; set; }
|
||||
}
|
@ -7,8 +7,9 @@ public class ECN {
|
||||
[Key]
|
||||
public required int ECNNumber { get; set; }
|
||||
public bool IsTECN { get; set; } = false;
|
||||
public DateTime ExpirationDate { get; set; }
|
||||
public DateTime ExtensionDate { get; set; } = DateTime.MinValue;
|
||||
public required DateTime ExpirationDate { get; set; }
|
||||
public DateTime ExtensionDate { get; set; }
|
||||
public required int OriginatorID { get; set; }
|
||||
public required string Title { get; set; }
|
||||
public DateTime CloseDate { get; set; } = DateTime.MaxValue;
|
||||
}
|
||||
|
@ -1,12 +1,16 @@
|
||||
using Dapper.Contrib.Extensions;
|
||||
|
||||
namespace FabApprovalWorkerService.Models;
|
||||
|
||||
[Table("TrainingAssignment")]
|
||||
public class TrainingAssignment {
|
||||
[Key]
|
||||
public int ID { get; set; }
|
||||
public required int UserID { get; set; }
|
||||
public required DateTime DateAssigned { get; set; }
|
||||
public int TrainingID { get; set; }
|
||||
public bool Status { get; set; } = false;
|
||||
public bool status { get; set; } = false;
|
||||
public bool Deleted { get; set; } = false;
|
||||
public DateTime DeletedDate { get; set; }
|
||||
public DateTime LastNotification { get; set; }
|
||||
}
|
||||
|
@ -28,6 +28,7 @@ builder.Services.AddScoped<ISmtpService, SmtpService>();
|
||||
builder.Services.AddScoped<IUserService, UserService>();
|
||||
builder.Services.AddScoped<IECNService, ECNService>();
|
||||
builder.Services.AddScoped<ITrainingService, TrainingService>();
|
||||
builder.Services.AddScoped<ICorrectiveActionService, CorrectiveActionService>();
|
||||
|
||||
builder.Services.AddQuartz(q => {
|
||||
JobKey pendingOOOStatusJob = new JobKey("Pending OOO status job");
|
||||
@ -69,6 +70,26 @@ builder.Services.AddQuartz(q => {
|
||||
.WithIdentity("Expired TECN trigger")
|
||||
.WithCronSchedule(CronScheduleBuilder.DailyAtHourAndMinute(6, 0))
|
||||
);
|
||||
|
||||
JobKey trainingReminderJob = new JobKey("Training reminder job");
|
||||
q.AddJob<TrainingNotificationWorker>(opts => opts
|
||||
.WithIdentity(trainingReminderJob)
|
||||
);
|
||||
q.AddTrigger(opts => opts
|
||||
.ForJob(trainingReminderJob)
|
||||
.WithIdentity("Training reminder trigger")
|
||||
.WithCronSchedule(CronScheduleBuilder.DailyAtHourAndMinute(6, 0))
|
||||
);
|
||||
|
||||
JobKey caFollowUpJob = new JobKey("CA follow up job");
|
||||
q.AddJob<CAFollowUpWorker>(opts => opts
|
||||
.WithIdentity(caFollowUpJob)
|
||||
);
|
||||
q.AddTrigger(opts => opts
|
||||
.ForJob(caFollowUpJob)
|
||||
.WithIdentity("CA follow up trigger")
|
||||
.WithCronSchedule(CronScheduleBuilder.DailyAtHourAndMinute(6, 0))
|
||||
);
|
||||
});
|
||||
|
||||
builder.Services.AddQuartzHostedService(opt => {
|
||||
|
67
FabApprovalWorkerService/Services/CorrectiveActionService.cs
Normal file
67
FabApprovalWorkerService/Services/CorrectiveActionService.cs
Normal file
@ -0,0 +1,67 @@
|
||||
using FabApprovalWorkerService.Models;
|
||||
|
||||
using System.Text;
|
||||
|
||||
namespace FabApprovalWorkerService.Services;
|
||||
|
||||
public interface ICorrectiveActionService {
|
||||
Task<IEnumerable<CorrectiveAction>> GetCorrectiveActionsWithFollowUpInFiveDays();
|
||||
Task CreateCorrectiveActionFollowUpApproval(int caNo, int qaId);
|
||||
}
|
||||
|
||||
public class CorrectiveActionService : ICorrectiveActionService {
|
||||
private readonly ILogger<CorrectiveActionService> _logger;
|
||||
private readonly IDalService _dalService;
|
||||
|
||||
public CorrectiveActionService(ILogger<CorrectiveActionService> logger, IDalService dalService) {
|
||||
_logger = logger ?? throw new ArgumentNullException("ILogger not injected");
|
||||
_dalService = dalService ?? throw new ArgumentNullException("IDalService not injected");
|
||||
}
|
||||
|
||||
public async Task CreateCorrectiveActionFollowUpApproval(int caNo, int qaId) {
|
||||
try {
|
||||
_logger.LogInformation($"Attempting to create a follow up approval for CA {caNo} by QA {qaId}");
|
||||
|
||||
if (caNo <= 0) throw new ArgumentException($"{caNo} is not a valid CA number");
|
||||
if (qaId <= 0) throw new ArgumentException($"{qaId} is not a valid User Id");
|
||||
|
||||
string today = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
|
||||
|
||||
StringBuilder queryBuilder = new();
|
||||
queryBuilder.Append("insert into Approval (IssueID, RoleName, SubRole, UserID, SubRoleID, ItemStatus, Step, ");
|
||||
queryBuilder.Append("AssignedDate, NotifyDate,RoleAssignedDate, ApprovalType, DocumentTypeID) ");
|
||||
queryBuilder.Append($"values ({caNo}, '8DQAFollowUp', '8DQAFollowUp', {qaId}, 335, 0, 2, ");
|
||||
queryBuilder.Append($"{today}, {today}, {today}, 1, 9);");
|
||||
|
||||
await _dalService.ExecuteAsync(queryBuilder.ToString());
|
||||
} catch (Exception ex) {
|
||||
StringBuilder errMsgBuilder = new();
|
||||
errMsgBuilder.Append($"An exception occurred when attempting to create a follow up approval for CA {caNo} by QA {qaId}. ");
|
||||
errMsgBuilder.Append($"Exception: {ex.Message}");
|
||||
_logger.LogError(errMsgBuilder.ToString());
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<CorrectiveAction>> GetCorrectiveActionsWithFollowUpInFiveDays() {
|
||||
try {
|
||||
_logger.LogInformation("Attempting to get all CAs needing follow up in five days");
|
||||
|
||||
DateTime fiveDaysFromToday = DateTime.Now.Date.AddDays(5);
|
||||
DateTime sixDaysFromToday = DateTime.Now.Date.AddDays(6);
|
||||
|
||||
StringBuilder queryBuilder = new();
|
||||
queryBuilder.Append("select * from _8DCorrectiveAction where ApprovalStatus = 1 and FollowUpDate is not null ");
|
||||
queryBuilder.Append($"and FollowUpDate < '{sixDaysFromToday.ToString("yyyy-MM-dd HH:mm:ss")}' ");
|
||||
queryBuilder.Append($"and FollowUpDate >= '{fiveDaysFromToday.ToString("yyyy-MM-dd HH:mm:ss")}';");
|
||||
|
||||
return (await _dalService.QueryAsync<CorrectiveAction>(queryBuilder.ToString())).ToList();
|
||||
} catch (Exception ex) {
|
||||
StringBuilder errMsgBuilder = new();
|
||||
errMsgBuilder.Append($"An exception occurred when attempting to get all CAs needing follow up in five days. ");
|
||||
errMsgBuilder.Append($"Exception: {ex.Message}");
|
||||
_logger.LogError(errMsgBuilder.ToString());
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
@ -6,9 +6,10 @@ namespace FabApprovalWorkerService.Services;
|
||||
|
||||
public interface IECNService {
|
||||
Task<IEnumerable<ECN>> GetExpiringTECNs();
|
||||
Task<IEnumerable<ECN>> GetExpiredTECNs();
|
||||
Task<IEnumerable<ECN>> GetExpiredTECNsInPastDay();
|
||||
Task<IEnumerable<string>> GetTECNNotificationUserEmails();
|
||||
Task<ECN> GetEcnByNumber(int ecnNumber);
|
||||
bool EcnIsExpired(ECN ecn);
|
||||
}
|
||||
|
||||
public class ECNService : IECNService {
|
||||
@ -20,6 +21,31 @@ public class ECNService : IECNService {
|
||||
_dalService = dalService ?? throw new ArgumentNullException("IDalService not injected");
|
||||
}
|
||||
|
||||
public bool EcnIsExpired(ECN ecn) {
|
||||
try {
|
||||
_logger.LogInformation("Attempting to determine if ECN is expired");
|
||||
|
||||
if (ecn is null) throw new ArgumentNullException("ECN cannot be null");
|
||||
|
||||
if (!ecn.IsTECN) return false;
|
||||
if (ecn.CloseDate <= DateTime.Now) return false;
|
||||
|
||||
DateTime tomorrow = DateTime.Now.Date.AddDays(1);
|
||||
|
||||
bool isExpired = (ecn.ExpirationDate < tomorrow) && (ecn.ExtensionDate < tomorrow);
|
||||
|
||||
_logger.LogInformation($"ECN {ecn.ECNNumber} expired: {isExpired}");
|
||||
|
||||
return isExpired;
|
||||
} catch (Exception ex) {
|
||||
StringBuilder errMsgBuilder = new();
|
||||
errMsgBuilder.Append($"An exception occurred when attempting to determine if ECN is expired. ");
|
||||
errMsgBuilder.Append($"Exception: {ex.Message}");
|
||||
_logger.LogError(errMsgBuilder.ToString());
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ECN> GetEcnByNumber(int ecnNumber) {
|
||||
try {
|
||||
_logger.LogInformation($"Attempting to get ECN {ecnNumber}");
|
||||
@ -42,7 +68,7 @@ public class ECNService : IECNService {
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ECN>> GetExpiredTECNs() {
|
||||
public async Task<IEnumerable<ECN>> GetExpiredTECNsInPastDay() {
|
||||
try {
|
||||
_logger.LogInformation("Attempting to get all TECNs expired in the last day");
|
||||
|
||||
|
@ -29,7 +29,7 @@ public class SmtpService : ISmtpService {
|
||||
string subject,
|
||||
string body) {
|
||||
if (recipients.IsNullOrEmpty()) throw new ArgumentNullException("recipients cannot be null or empty!");
|
||||
if (ccRecipients.IsNullOrEmpty()) throw new ArgumentNullException("ccRecipients cannot be null or empty!");
|
||||
if (ccRecipients is null) throw new ArgumentNullException("ccRecipients cannot be null!");
|
||||
if (subject.IsNullOrEmpty()) throw new ArgumentNullException("subject cannot be null or empty!");
|
||||
if (body.IsNullOrEmpty()) throw new ArgumentNullException("body cannot be null or empty!");
|
||||
|
||||
|
@ -7,12 +7,14 @@ namespace FabApprovalWorkerService.Services;
|
||||
public interface ITrainingService {
|
||||
Task<IEnumerable<int>> GetTrainingIdsForECN(int ecnNumber);
|
||||
Task MarkTrainingAsComplete(int trainingId);
|
||||
Task DeleteTrainingAssignment(int trainingId);
|
||||
Task DeleteTrainingAssignmentsByTrainingId(int trainingId);
|
||||
Task DeleteTrainingAssignmentById(int trainingAssignmentId);
|
||||
Task<IEnumerable<int>> GetTrainingAssignmentIdsForTraining(int trainingId);
|
||||
Task DeleteDocAssignment(int trainingAssignmentId);
|
||||
Task<IEnumerable<TrainingAssignment>> GetActiveTrainingAssignments();
|
||||
Task UpdateTrainingAssignmentLastNotification(int trainingAssignmentId);
|
||||
Task<int> GetEcnNumberByTrainingId(int trainingId);
|
||||
Task<IEnumerable<int>> GetTrainingAssignmentIdsByUserId(int userId);
|
||||
}
|
||||
|
||||
public class TrainingService : ITrainingService {
|
||||
@ -47,22 +49,44 @@ public class TrainingService : ITrainingService {
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DeleteTrainingAssignment(int trainingId) {
|
||||
public async Task DeleteTrainingAssignmentsByTrainingId(int trainingId) {
|
||||
if (trainingId <= 0) throw new ArgumentException($"Invalid training id: {trainingId}");
|
||||
|
||||
try {
|
||||
_logger.LogInformation($"Attempting to delete training assignment {trainingId}");
|
||||
_logger.LogInformation($"Attempting to delete training assignments for training ID {trainingId}");
|
||||
|
||||
StringBuilder queryBuilder = new();
|
||||
queryBuilder.Append($"update TrainingAssignments set Deleted = 1, ");
|
||||
queryBuilder.Append($"DeletedDate = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' ");
|
||||
queryBuilder.Append($"where TrainingID = {trainingId} and status = 0;");
|
||||
|
||||
await _dalService.ExecuteAsync(queryBuilder.ToString());
|
||||
} catch (Exception ex) {
|
||||
StringBuilder errMsgBuilder = new();
|
||||
errMsgBuilder.Append($"An exception occurred when attempting to delete training assignments ");
|
||||
errMsgBuilder.Append($"for training id {trainingId}. Exception: {ex.Message}");
|
||||
_logger.LogError(errMsgBuilder.ToString());
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DeleteTrainingAssignmentById(int trainingAssignmentId) {
|
||||
if (trainingAssignmentId <= 0)
|
||||
throw new ArgumentException($"Invalid training assignment id: {trainingAssignmentId}");
|
||||
|
||||
try {
|
||||
_logger.LogInformation($"Attempting to delete training assignment {trainingAssignmentId}");
|
||||
|
||||
StringBuilder queryBuilder = new();
|
||||
queryBuilder.Append($"update TrainingAssignments set Deleted = 1, ");
|
||||
queryBuilder.Append($"DeletedDate = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' ");
|
||||
queryBuilder.Append($"where ID = {trainingAssignmentId};");
|
||||
|
||||
await _dalService.ExecuteAsync(queryBuilder.ToString());
|
||||
} catch (Exception ex) {
|
||||
StringBuilder errMsgBuilder = new();
|
||||
errMsgBuilder.Append($"An exception occurred when attempting to delete training assignment ");
|
||||
errMsgBuilder.Append($"{trainingId}. Exception: {ex.Message}");
|
||||
errMsgBuilder.Append($"{trainingAssignmentId}. Exception: {ex.Message}");
|
||||
_logger.LogError(errMsgBuilder.ToString());
|
||||
throw;
|
||||
}
|
||||
@ -151,7 +175,7 @@ public class TrainingService : ITrainingService {
|
||||
throw new ArgumentException($"{trainingAssignmentId} is not a valid training assignment Id");
|
||||
|
||||
StringBuilder queryBuilder = new();
|
||||
queryBuilder.Append($"update TrainingAssignments set LastNotification = {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}");
|
||||
queryBuilder.Append($"update TrainingAssignments set LastNotification = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}'");
|
||||
queryBuilder.Append($"where ID = {trainingAssignmentId};");
|
||||
|
||||
await _dalService.ExecuteAsync(queryBuilder.ToString());
|
||||
@ -186,4 +210,22 @@ public class TrainingService : ITrainingService {
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<int>> GetTrainingAssignmentIdsByUserId(int userId) {
|
||||
try {
|
||||
_logger.LogInformation($"Attempting to get all training assignment Ids for user {userId}");
|
||||
|
||||
if (userId <= 0) throw new ArgumentException($"{userId} is not a valid User ID");
|
||||
|
||||
string sql = $"select ID from TrainingAssignments where UserID = {userId};";
|
||||
|
||||
return (await _dalService.QueryAsync<int>(sql)).ToList();
|
||||
} catch (Exception ex) {
|
||||
StringBuilder errMsgBuilder = new();
|
||||
errMsgBuilder.Append($"An exception occurred when attempting to get all training assignment Ids for user {userId}. ");
|
||||
errMsgBuilder.Append($"Exception: {ex.Message}");
|
||||
_logger.LogError(errMsgBuilder.ToString());
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
87
FabApprovalWorkerService/Workers/CAFollowUpWorker.cs
Normal file
87
FabApprovalWorkerService/Workers/CAFollowUpWorker.cs
Normal file
@ -0,0 +1,87 @@
|
||||
using FabApprovalWorkerService.Models;
|
||||
using FabApprovalWorkerService.Services;
|
||||
|
||||
using Infineon.Monitoring.MonA;
|
||||
|
||||
using Quartz;
|
||||
|
||||
using System.Net.Mail;
|
||||
using System.Text;
|
||||
|
||||
namespace FabApprovalWorkerService.Workers;
|
||||
|
||||
public class CAFollowUpWorker : IJob {
|
||||
private readonly ILogger<CAFollowUpWorker> _logger;
|
||||
private readonly ICorrectiveActionService _caService;
|
||||
private readonly IUserService _userService;
|
||||
private readonly ISmtpService _smtpService;
|
||||
private readonly IMonInClient _monInClient;
|
||||
private readonly string _baseUrl;
|
||||
|
||||
public CAFollowUpWorker(ILogger<CAFollowUpWorker> logger,
|
||||
ICorrectiveActionService caService,
|
||||
IUserService userService,
|
||||
ISmtpService smtpService,
|
||||
IMonInClient monInClient) {
|
||||
_logger = logger ?? throw new ArgumentNullException("ILogger not injected");
|
||||
_caService = caService ?? throw new ArgumentNullException("ICorrectiveActionService not injected");
|
||||
_userService = userService ?? throw new ArgumentNullException("IUserService not injected");
|
||||
_smtpService = smtpService ?? throw new ArgumentNullException("ISmtpService not injected");
|
||||
_monInClient = monInClient ?? throw new ArgumentNullException("IMonInClient not injected");
|
||||
_baseUrl = Environment.GetEnvironmentVariable("FabApprovalBaseUrl") ??
|
||||
throw new ArgumentNullException("FabApprovalBaseUrl environment variable not found");
|
||||
}
|
||||
|
||||
public async Task Execute(IJobExecutionContext context) {
|
||||
DateTime start = DateTime.Now;
|
||||
bool isInternalError = false;
|
||||
StringBuilder errorMessage = new();
|
||||
string metricName = "CAFollowUpWorker";
|
||||
|
||||
try {
|
||||
_logger.LogInformation("Attempting to create follow up approvals for CAs needing it in five days");
|
||||
|
||||
IEnumerable<CorrectiveAction> followUpCAs = (await _caService.GetCorrectiveActionsWithFollowUpInFiveDays())
|
||||
.ToList();
|
||||
foreach (CorrectiveAction ca in followUpCAs) {
|
||||
await _caService.CreateCorrectiveActionFollowUpApproval(ca.CANo, ca.QAID);
|
||||
|
||||
string qaEmail = await _userService.GetUserEmail(ca.QAID);
|
||||
IEnumerable<MailAddress> recipients = new List<MailAddress>() {
|
||||
new MailAddress(qaEmail)
|
||||
};
|
||||
|
||||
IEnumerable<MailAddress> ccRecipients = new List<MailAddress>();
|
||||
|
||||
string subject = $"Fab Approval CA Follow Up - CA# {ca.CANo} - {ca.CATitle}";
|
||||
|
||||
StringBuilder bodyBuilder = new();
|
||||
bodyBuilder.Append($"Corrective Action# {ca.CANo} is ready for follow up. Please log on to Fab Approval ");
|
||||
bodyBuilder.Append("and review this item. <br/><br/>");
|
||||
bodyBuilder.Append($"{_baseUrl}/CorrectiveAction/Edit?issueID={ca.CANo} <br/><br/>");
|
||||
bodyBuilder.Append("If you have any questions or trouble, please contact a site administrator.");
|
||||
bodyBuilder.Append("<br/><br/> Thank You!");
|
||||
|
||||
await _smtpService.SendEmail(recipients, ccRecipients, subject, bodyBuilder.ToString());
|
||||
}
|
||||
|
||||
_logger.LogInformation("Successfully created follow up approvals for CAs needing it in five days");
|
||||
} catch (Exception ex) {
|
||||
StringBuilder errMsgBuilder = new();
|
||||
errMsgBuilder.Append("An exception occurred when attempting to create follow up approvals for ");
|
||||
errMsgBuilder.Append($"CAs needing it in five days. Exception: {ex.Message}");
|
||||
_logger.LogError(errMsgBuilder.ToString());
|
||||
isInternalError = true;
|
||||
} finally {
|
||||
DateTime end = DateTime.Now;
|
||||
double latencyInMS = (end - start).TotalMilliseconds;
|
||||
_monInClient.PostMetric(metricName + "Latency", latencyInMS);
|
||||
|
||||
if (isInternalError) {
|
||||
_monInClient.PostStatus(metricName, State.Critical);
|
||||
} else {
|
||||
_monInClient.PostStatus(metricName, State.Ok);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -50,7 +50,7 @@ public class ExpiredTECNWorker : IJob {
|
||||
try {
|
||||
_logger.LogInformation("Attempting to process expired TECNs");
|
||||
|
||||
List<ECN> expiredEcns = (await _ecnService.GetExpiredTECNs()).ToList();
|
||||
List<ECN> expiredEcns = (await _ecnService.GetExpiredTECNsInPastDay()).ToList();
|
||||
|
||||
List<MailAddress> tecnNotificationUserEmails = new();
|
||||
|
||||
@ -63,7 +63,7 @@ public class ExpiredTECNWorker : IJob {
|
||||
List<int> trainingIds = (await _trainingService.GetTrainingIdsForECN(ecn.ECNNumber)).ToList();
|
||||
|
||||
foreach (int trainingId in trainingIds) {
|
||||
await _trainingService.DeleteTrainingAssignment(trainingId);
|
||||
await _trainingService.DeleteTrainingAssignmentsByTrainingId(trainingId);
|
||||
|
||||
List<int> trainingAssignmentIds =
|
||||
(await _trainingService.GetTrainingAssignmentIdsForTraining(trainingId)).ToList();
|
||||
|
@ -5,6 +5,7 @@ using Infineon.Monitoring.MonA;
|
||||
|
||||
using Quartz;
|
||||
|
||||
using System.Net.Mail;
|
||||
using System.Text;
|
||||
|
||||
namespace FabApprovalWorkerService.Workers;
|
||||
@ -16,6 +17,7 @@ public class TrainingNotificationWorker : IJob {
|
||||
private readonly IECNService _ecnService;
|
||||
private readonly ISmtpService _smtpService;
|
||||
private readonly IMonInClient _monInClient;
|
||||
private readonly string _baseUrl;
|
||||
|
||||
public TrainingNotificationWorker(ILogger<TrainingNotificationWorker> logger,
|
||||
ITrainingService trainingService,
|
||||
@ -29,6 +31,8 @@ public class TrainingNotificationWorker : IJob {
|
||||
_ecnService = ecnService ?? throw new ArgumentNullException("IECNService not injected");
|
||||
_smtpService = smtpService ?? throw new ArgumentNullException("ISmtpService not injected");
|
||||
_monInClient = monInClient ?? throw new ArgumentNullException("IMonInClient not injected");
|
||||
_baseUrl = Environment.GetEnvironmentVariable("FabApprovalBaseUrl") ??
|
||||
throw new ArgumentNullException("FabApprovalBaseUrl environment variable not found");
|
||||
}
|
||||
|
||||
public async Task Execute(IJobExecutionContext context) {
|
||||
@ -42,11 +46,54 @@ public class TrainingNotificationWorker : IJob {
|
||||
|
||||
IEnumerable<TrainingAssignment> trainingAssignments = await _trainingService.GetActiveTrainingAssignments();
|
||||
|
||||
_logger.LogInformation($"There are {trainingAssignments.Count()} active training assignments");
|
||||
|
||||
foreach (TrainingAssignment trainingAssignment in trainingAssignments) {
|
||||
ECN ecn = await _ecnService.GetEcnByNumber
|
||||
int ecnNumber = await _trainingService.GetEcnNumberByTrainingId(trainingAssignment.TrainingID);
|
||||
ECN ecn = await _ecnService.GetEcnByNumber(ecnNumber);
|
||||
|
||||
bool ecnIsExpired = _ecnService.EcnIsExpired(ecn);
|
||||
if (ecnIsExpired) {
|
||||
_logger.LogInformation($"ECN {ecn.ECNNumber} is expired. Cancelling all training.");
|
||||
|
||||
await _trainingService.DeleteTrainingAssignmentsByTrainingId(trainingAssignment.TrainingID);
|
||||
await _trainingService.DeleteDocAssignment(trainingAssignment.ID);
|
||||
await _trainingService.MarkTrainingAsComplete(trainingAssignment.TrainingID);
|
||||
}
|
||||
|
||||
User user = await _userService.GetUserById(trainingAssignment.UserID);
|
||||
|
||||
bool userIsActive = user.IsActive;
|
||||
if (!userIsActive) {
|
||||
_logger.LogInformation($"User {user.UserID} is inactive. Cancelling all training.");
|
||||
|
||||
IEnumerable<int> userTrainingAssignmentIds = await _trainingService.GetTrainingAssignmentIdsByUserId(user.UserID);
|
||||
|
||||
foreach (int trainingAssignmentId in userTrainingAssignmentIds) {
|
||||
await _trainingService.DeleteTrainingAssignmentById(trainingAssignmentId);
|
||||
await _trainingService.DeleteDocAssignment(trainingAssignmentId);
|
||||
}
|
||||
}
|
||||
|
||||
if (!ecnIsExpired && userIsActive && !user.OOO) {
|
||||
bool lastNotificationMoreThanFourDaysAgo = (DateTime.Now.Date - trainingAssignment.LastNotification).Days >= 5;
|
||||
bool dateAssignedMoreThanFourteenDaysAgo = (DateTime.Now.Date - trainingAssignment.DateAssigned).Days >= 15;
|
||||
|
||||
bool notificationSent = false;
|
||||
if (lastNotificationMoreThanFourDaysAgo && dateAssignedMoreThanFourteenDaysAgo) {
|
||||
await SendTrainingReminder(ecn, user);
|
||||
notificationSent = true;
|
||||
await _trainingService.UpdateTrainingAssignmentLastNotification(trainingAssignment.ID);
|
||||
}
|
||||
|
||||
if (!notificationSent) {
|
||||
DateTime latestExpirationDate = (ecn.ExtensionDate > ecn.ExpirationDate ? ecn.ExtensionDate : ecn.ExpirationDate);
|
||||
int daysTillExpiration = (latestExpirationDate - DateTime.Now.Date).Days;
|
||||
if (daysTillExpiration > 0 && daysTillExpiration <= 5) {
|
||||
await SendTrainingReminder(ecn, user);
|
||||
await _trainingService.UpdateTrainingAssignmentLastNotification(trainingAssignment.ID);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("Successfully sent training notifications");
|
||||
@ -68,4 +115,23 @@ public class TrainingNotificationWorker : IJob {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendTrainingReminder(ECN ecn, User user) {
|
||||
_logger.LogInformation($"Attempting to send training reminder for ECN {ecn.ECNNumber} to user {user.UserID}");
|
||||
|
||||
IEnumerable<MailAddress> recipients = new List<MailAddress>() {
|
||||
new MailAddress(user.Email)
|
||||
};
|
||||
|
||||
IEnumerable<MailAddress> ccRecipients = new List<MailAddress>();
|
||||
|
||||
StringBuilder bodyBuilder = new();
|
||||
bodyBuilder.Append("Hello, you have open training assignments in Fab Approval. This is a reminder to ");
|
||||
bodyBuilder.Append("finish your training assignments. <br /> View your open training assignments ");
|
||||
bodyBuilder.Append($"<a href='{_baseUrl}/Training/ViewMyTrainingAssignments'>here. </a>");
|
||||
|
||||
string subject = $"Fab Approval Training Reminder - ECN# {ecn.ECNNumber} - {ecn.Title}";
|
||||
|
||||
await _smtpService.SendEmail(recipients, ccRecipients, subject, bodyBuilder.ToString());
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user