using FabApprovalWorkerService.Models; using Microsoft.IdentityModel.Tokens; using System.Text; using System.Text.Json; namespace FabApprovalWorkerService.Services; public interface ITrainingService { Task> GetTrainingIdsForECN(int ecnNumber); Task MarkTrainingAsComplete(int trainingId); Task DeleteTrainingAssignmentsByTrainingId(int trainingId); Task DeleteTrainingAssignmentById(int trainingAssignmentId); Task> GetTrainingAssignmentIdsForTraining(int trainingId); Task DeleteDocAssignment(int trainingAssignmentId); Task> GetActiveTrainingAssignments(); Task UpdateTrainingAssignmentLastNotification(int trainingAssignmentId); Task GetEcnNumberByTrainingId(int trainingId); Task> GetTrainingAssignmentIdsByUserId(int userId); Task> GetUserCertificationRecords(); Task UpdateTrainingGroupMembership(IEnumerable certRecords); } public class TrainingService : ITrainingService { private ILogger _logger; private IDalService _dalService; private IUserService _userService; private readonly string _userCertRecordsFilePath; private readonly string _cleansTrainingGroupName; private readonly string _asmHtrTrainingGroupName; private readonly string _epiProTrainingGroupName; private readonly string _fqaTrainingGroupName; private readonly string _packagingAndLabelingTrainingGroupName; public TrainingService(ILogger logger, IDalService dalService, IUserService userService) { _logger = logger ?? throw new ArgumentNullException("ILogger not injected"); _dalService = dalService ?? throw new ArgumentNullException("IDalService not injected"); _userService = userService ?? throw new ArgumentNullException("IUserService not injected"); _userCertRecordsFilePath = Environment.GetEnvironmentVariable("UserCertificationRecordsFilePath") ?? throw new ArgumentNullException("UserCertificationRecordsFilePath environment variable not found"); _asmHtrTrainingGroupName = Environment.GetEnvironmentVariable("AsmHtrTrainingGroupName") ?? throw new ArgumentNullException("AsmHtrTrainingGroupName environment variable not found"); _cleansTrainingGroupName = Environment.GetEnvironmentVariable("CleansTrainingGroupName") ?? throw new ArgumentNullException("CleansTrainingGroupName environment variable not found"); _epiProTrainingGroupName = Environment.GetEnvironmentVariable("EpiProTrainingGroupName") ?? throw new ArgumentNullException("EpiProTrainingGroupName environment variable not found"); _fqaTrainingGroupName = Environment.GetEnvironmentVariable("FqaTrainingGroupName") ?? throw new ArgumentNullException("FqaTrainingGroupName environment variable not found"); _packagingAndLabelingTrainingGroupName = Environment.GetEnvironmentVariable("PackagingAndLabelingTrainingGroupName") ?? throw new ArgumentNullException("PackagingAndLabelingTrainingGroupName environment variable not found"); } public async Task DeleteDocAssignment(int trainingAssignmentId) { if (trainingAssignmentId <= 0) throw new ArgumentException($"Invalid training assignment id: {trainingAssignmentId}"); try { _logger.LogInformation($"Attempting to delete training doc assignments for training assignment {trainingAssignmentId}"); StringBuilder queryBuilder = new(); queryBuilder.Append($"update TrainingDocAcks set Deleted = 1, "); queryBuilder.Append($"DeletedDate = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' "); queryBuilder.Append($"where TrainingAssignmentID = {trainingAssignmentId} and Reviewed = 0;"); await _dalService.ExecuteAsync(queryBuilder.ToString()); } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append($"An exception occurred when attempting to delete training doc assignment "); errMsgBuilder.Append($"{trainingAssignmentId}. Exception: {ex.Message}"); _logger.LogError(errMsgBuilder.ToString()); throw; } } public async Task DeleteTrainingAssignmentsByTrainingId(int trainingId) { if (trainingId <= 0) throw new ArgumentException($"Invalid training id: {trainingId}"); try { _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($"{trainingAssignmentId}. Exception: {ex.Message}"); _logger.LogError(errMsgBuilder.ToString()); throw; } } public async Task MarkTrainingAsComplete(int trainingId) { if (trainingId <= 0) throw new ArgumentException($"Invalid training id: {trainingId}"); try { _logger.LogInformation($"Attempting to mark training {trainingId} as complete"); StringBuilder queryBuilder = new(); queryBuilder.Append($"update Training set Status = 1, "); queryBuilder.Append($"CompletedDate = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' "); queryBuilder.Append($"where TrainingID = {trainingId};"); await _dalService.ExecuteAsync(queryBuilder.ToString()); } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append($"An exception occurred when attempting to mark training {trainingId} "); errMsgBuilder.Append($"as complete. Exception: {ex.Message}"); _logger.LogError(errMsgBuilder.ToString()); throw; } } public async Task> GetTrainingAssignmentIdsForTraining(int trainingId) { if (trainingId <= 0) throw new ArgumentException($"Invalid trainingID: {trainingId}"); try { _logger.LogInformation($"Attempting to get training assignment ids for training id {trainingId}"); string sql = $"select ID from TrainingAssignments where TrainingID = {trainingId};"; return await _dalService.QueryAsync(sql); } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append($"An exception occurred when attempting to get training assignment ids "); errMsgBuilder.Append($"for training id {trainingId}. Exception: {ex.Message}"); _logger.LogError(errMsgBuilder.ToString()); throw; } } public async Task> GetTrainingIdsForECN(int ecnNumber) { if (ecnNumber <= 0) throw new ArgumentException($"Invalid ecnNumber: {ecnNumber}"); try { _logger.LogInformation($"Attempting to get training ids for ecn {ecnNumber}"); string sql = $"select TrainingID from Training where ECN = {ecnNumber};"; return await _dalService.QueryAsync(sql); } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append($"An exception occurred when attempting to get training ids "); errMsgBuilder.Append($"for ECN {ecnNumber}. Exception: {ex.Message}"); _logger.LogError(errMsgBuilder.ToString()); throw; } } public async Task> GetActiveTrainingAssignments() { try { _logger.LogInformation($"Attempting to get active training assignments"); StringBuilder queryBuilder = new(); queryBuilder.Append("select ID, UserID, DateAssigned, TrainingID, status, Deleted, DeletedDate, LastNotification "); queryBuilder.Append("from TrainingAssignments where status = 0 and (Deleted is null or Deleted = 0);"); return await _dalService.QueryAsync(queryBuilder.ToString()); } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append($"An exception occurred when attempting to get active training assignments. "); errMsgBuilder.Append($"Exception: {ex.Message}"); _logger.LogError(errMsgBuilder.ToString()); throw; } } public async Task UpdateTrainingAssignmentLastNotification(int trainingAssignmentId) { try { _logger.LogInformation($"Attempting to update last notification date for training assignment {trainingAssignmentId}"); if (trainingAssignmentId <= 0) 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($"where ID = {trainingAssignmentId};"); await _dalService.ExecuteAsync(queryBuilder.ToString()); } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append("An exception occurred when attempting to update last notification "); errMsgBuilder.Append($"for training assignment {trainingAssignmentId}. Exception: {ex.Message}"); _logger.LogError(errMsgBuilder.ToString()); throw; } } public async Task GetEcnNumberByTrainingId(int trainingId) { try { _logger.LogInformation($"Attempting to get ECN number for training {trainingId}"); if (trainingId <= 0) throw new ArgumentException($"{trainingId} is not a valid training Id"); string sql = $"select e.ECNNumber from Training t join ECN e on t.ECN = e.ECNNumber where t.TrainingID = {trainingId};"; int ecnNumber = (await _dalService.QueryAsync(sql)).FirstOrDefault(); if (ecnNumber <= 0) throw new Exception($"ECN number not found for training {trainingId}"); return ecnNumber; } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append($"An exception occurred when attempting to get ECN number for training {trainingId}. "); errMsgBuilder.Append($"Exception: {ex.Message}"); _logger.LogError(errMsgBuilder.ToString()); throw; } } public async Task> 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(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; } } public async Task> GetUserCertificationRecords() { try { _logger.LogInformation("Attempting to get user certification records"); string jsonUserCertRecords = await File.ReadAllTextAsync(_userCertRecordsFilePath); IEnumerable? records = JsonSerializer.Deserialize>(jsonUserCertRecords); if (records is null) throw new Exception("No user certification records found"); return records; } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append("An exception occurred when attempting to get user certification records. "); errMsgBuilder.Append($"Exception: {ex.Message}"); _logger.LogError(errMsgBuilder.ToString()); throw; } } public async Task UpdateTrainingGroupMembership(IEnumerable certRecords) { try { _logger.LogInformation("Attempting to update certification training group membership."); if (certRecords.IsNullOrEmpty()) throw new ArgumentNullException("certRecords cannot be null or empty"); int asmHtrGroupId = await GetGroupId(_asmHtrTrainingGroupName); await DeleteAllUsersFromTrainingGroup(asmHtrGroupId); int epiProGroupId = await GetGroupId(_epiProTrainingGroupName); await DeleteAllUsersFromTrainingGroup(epiProGroupId); int fqaGroupId = await GetGroupId(_fqaTrainingGroupName); await DeleteAllUsersFromTrainingGroup(fqaGroupId); int packagingAndLabelingGroupId = await GetGroupId(_packagingAndLabelingTrainingGroupName); await DeleteAllUsersFromTrainingGroup(packagingAndLabelingGroupId); int cleansGroupId = await GetGroupId(_cleansTrainingGroupName); await DeleteAllUsersFromTrainingGroup(cleansGroupId); List queryTasks = new(); foreach (UserCertificationRecord record in certRecords) { if (record is not null) { User user = null; try { user = await _userService.GetUserByEmail(record.Email); } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append($"An exception occurred when attempting to get user for email {record.Email}. "); errMsgBuilder.Append($"Exception: {ex.Message}"); } if (user is not null) { if (record.IsEpiProCertified) queryTasks.Add(AddUserToTrainingGroup(epiProGroupId, user)); if (record.IsPackagingLabelingCertified) queryTasks.Add(AddUserToTrainingGroup(packagingAndLabelingGroupId, user)); if (record.IsCleansCertified) queryTasks.Add(AddUserToTrainingGroup(cleansGroupId, user)); if (record.IsFqaCertified) queryTasks.Add(AddUserToTrainingGroup(fqaGroupId, user)); if (record.IsAnyLevelCertified) queryTasks.Add(AddUserToTrainingGroup(asmHtrGroupId, user)); } } } await Task.WhenAll(queryTasks); return true; } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append("An exception occurred when attempting to update certification training group membership. "); errMsgBuilder.Append($"Exception: {ex.Message}"); _logger.LogError(errMsgBuilder.ToString()); throw; } } private async Task GetGroupId(string groupName) { try { _logger.LogInformation($"Attempting to get {groupName} training group ID"); StringBuilder queryBuilder = new(); queryBuilder.Append("select TrainingGroupID from TrainingGroups "); queryBuilder.Append($"where TrainingGroupName = '{groupName}' collate SQL_Latin1_General_CP1_CI_AS;"); int groupId = (await _dalService.QueryAsync(queryBuilder.ToString())).FirstOrDefault(); if (groupId <= 0) throw new Exception($"{groupName} training group ID not found"); return groupId; } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append($"An exception occurred when attempting to get {groupName} training group ID. "); errMsgBuilder.Append($"Exception: {ex.Message}"); throw; } } private async Task DeleteAllUsersFromTrainingGroup(int groupId) { try { _logger.LogInformation($"Attempting to delete all members of training group {groupId}"); if (groupId <= 0) throw new ArgumentException($"{groupId} not a valid training group ID"); string sql = $"delete from TrainingGroupMembers where TrainingGroupID = {groupId};"; await _dalService.ExecuteAsync(sql); } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append($"An exception occurred when attempting to delete all members of training group {groupId}. "); errMsgBuilder.Append($"Exception: {ex.Message}"); _logger.LogError(errMsgBuilder.ToString()); throw; } } private async Task AddUserToTrainingGroup(int groupId, User user) { try { _logger.LogInformation($"Attempting to add user to training group {groupId}"); if (groupId <= 0) throw new ArgumentException($"{groupId} is not a valid training group Id"); if (user is null) throw new ArgumentNullException("User cannot be null"); StringBuilder queryBuilder = new(); queryBuilder.Append("insert into TrainingGroupMembers (TrainingGroupID, UserID, FullName) "); queryBuilder.Append($"values ({groupId}, {user.UserID}, '{user.FirstName + " " + user.LastName}');"); await _dalService.ExecuteAsync(queryBuilder.ToString()); } catch (Exception ex) { StringBuilder errMsgBuilder = new(); errMsgBuilder.Append($"An exception occurred when attempting to add user to training group {groupId}. "); errMsgBuilder.Append($"Exception: {ex.Message}"); _logger.LogError(errMsgBuilder.ToString()); throw; } } }