Created ExpiredOOOStatusWorker

This commit is contained in:
Chase Tucker
2024-03-25 12:22:26 -07:00
parent 27f78da969
commit 69fdd98ab3
46 changed files with 549 additions and 5118 deletions

View File

@ -1,7 +1,4 @@
using Dapper;
using Dapper.Contrib.Extensions;
using FabApprovalWorkerService.Models;
using System.Data;
@ -16,14 +13,14 @@ public class DalService : IDalService {
private static readonly int RETRIES = 3;
private static readonly int BACKOFF_SECONDS_INTERVAL = 30;
private readonly IDbConnection _dbConnection;
private readonly IDbConnectionService _connectionPoolService;
private readonly ILogger<DalService> _logger;
public DalService(IDbConnection dbConnection, ILogger<DalService> logger) {
_dbConnection = dbConnection;
if (_dbConnection is null) throw new ArgumentNullException("IDbConnection not injected");
_logger = logger;
if (_logger is null) throw new ArgumentNullException("ILogger not injected");
public DalService(IDbConnectionService connectionPoolService, ILogger<DalService> logger) {
_connectionPoolService = connectionPoolService ??
throw new ArgumentNullException("IConnectionPoolService not injected");
_logger = logger ??
throw new ArgumentNullException("ILogger not injected");
}
public async Task<IEnumerable<T>> QueryAsync<T>(string sql) {
@ -38,19 +35,15 @@ public class DalService : IDalService {
Task.Delay(backoffSeconds * 1000).Wait();
try {
_logger.LogInformation("Attempting to perform query with {sql}. Remaining retries: {remainingRetries}",
sql,
remainingRetries);
_logger.LogInformation($"Attempting to perform query with {sql}. Remaining retries: {remainingRetries}");
using (_dbConnection) {
result = await _dbConnection.QueryAsync<T>(sql);
using (IDbConnection conn = _connectionPoolService.GetConnection()) {
result = await conn.QueryAsync<T>(sql);
}
queryWasSuccessful = true;
} catch (Exception ex) {
_logger.LogError("An exception occurred while attempting to perform a query. Exception: {ex}",
ex.Message);
_logger.LogError($"An exception occurred while attempting to perform a query. Exception: {ex.Message}");
exception = ex;
}
}
@ -74,19 +67,15 @@ public class DalService : IDalService {
Task.Delay(backoffSeconds * 1000).Wait();
try {
_logger.LogInformation("Attempting to execute {sql}. Remaining retries: {remainingRetries}",
sql,
remainingRetries);
_logger.LogInformation($"Attempting to execute {sql}. Remaining retries: {remainingRetries}");
using (_dbConnection) {
rowsAffected = await _dbConnection.ExecuteAsync(sql);
using (IDbConnection conn = _connectionPoolService.GetConnection()) {
rowsAffected = await conn.ExecuteAsync(sql);
}
queryWasSuccessful = true;
} catch (Exception ex) {
_logger.LogError("An exception occurred while attempting to execute a query. Exception: {ex}",
ex.Message);
_logger.LogError($"An exception occurred while attempting to execute a query. Exception: {ex.Message}");
exception = ex;
}
}

View File

@ -0,0 +1,30 @@
using Microsoft.Data.SqlClient;
using Microsoft.Data.Sqlite;
using System.Data;
namespace FabApprovalWorkerService.Services;
public interface IDbConnectionService {
IDbConnection GetConnection();
}
public class DbConnectionService : IDbConnectionService {
private readonly string _envName;
private readonly string _dbConnectionString;
public DbConnectionService() {
_envName = Environment.GetEnvironmentVariable("FabApprovalEnvironmentName") ??
throw new ArgumentNullException("FabApprovalEnvironmentName environment variable not found");
_dbConnectionString = Environment.GetEnvironmentVariable("FabApprovalDbConnectionString") ??
throw new ArgumentNullException("FabApprovalDbConnectionString environment variable not found");
}
public IDbConnection GetConnection() {
if (_envName.ToLower().Equals("development")) {
return new SqliteConnection(_dbConnectionString);
} else {
return new SqlConnection(_dbConnectionString);
}
}
}

View File

@ -1,3 +0,0 @@
using FabApprovalWorkerService.Models;
namespace FabApprovalWorkerService.Services;

View File

@ -31,23 +31,23 @@ public class MonInWorkerClient : IMonInWorkerClient {
_httpClientFactory = httpClientFactory;
if (_httpClientFactory is null) throw new ArgumentNullException("IHttpClientFactory not injected");
_config = config;
if (_config is null) throw new ArgumentNullException("IConfiguration not injected");
_config = config ??
throw new ArgumentNullException("IConfiguration not injected");
_logger = logger;
if (_logger is null) throw new ArgumentNullException("ILogger not injected");
_logger = logger ??
throw new ArgumentNullException("ILogger not injected");
_baseUrl = _config["MonIn:workerUrl"];
if (_baseUrl is null) throw new ArgumentNullException("MonIn:workerUrl not found in config");
_baseUrl = Environment.GetEnvironmentVariable("MonInWorkerUrl") ??
throw new ArgumentNullException("MonInWorkerUrl environment variable not found");
Int32.TryParse(_config["MonIn:retries"], out _retryLimit);
if (_retryLimit == -1) throw new ArgumentNullException("MonIn:retries not found in config");
if (!Int32.TryParse(Environment.GetEnvironmentVariable("MonInRetries"), out _retryLimit))
throw new ArgumentNullException("Valid MonInRetries environment variable not found");
Int32.TryParse(_config["MonIn:backoffInSeconds"], out _backoffInSeconds);
if (_backoffInSeconds == -1) throw new ArgumentNullException("MonIn:backoffInSeconds not found in config");
if (!Int32.TryParse(Environment.GetEnvironmentVariable("MonInBackoffSeconds"), out _backoffInSeconds))
throw new ArgumentNullException("Valid MonInBackoffSeconds environment varialbe not found");
_resource = _config["MonIn:resource"];
if (_resource is null) throw new ArgumentNullException("MonIn:resource not found in config");
_resource = Environment.GetEnvironmentVariable("FabApprovalWorkerServiceMonInResource") ??
throw new ArgumentNullException("FabApprovalWorkerServiceMonInResource environment variable not found");
}
public async void PostStatus(string statusName, StatusValue statusValue) {

View File

@ -1,5 +1,7 @@
using FabApprovalWorkerService.Models;
using NLog.Filters;
using System.Text;
namespace FabApprovalWorkerService.Services;
@ -9,11 +11,15 @@ public interface IUserService {
Task<bool> IsUserAlreadyOOO(int userId);
Task<bool> IsDelegatorAlreadyDelegatedTo(int userId);
Task<bool> InsertDelegatedRoles(int userId);
Task<bool> UpdateUserSubRoles(int userId, int delegatedUserId);
Task<bool> RemoveDelegatedRoles(int userId);
Task<bool> DelegateUserSubRoles(int userId, int delegatedUserId);
Task<bool> RemoveDelegatedUserSubRoles(int userId, int delegatedUserId);
Task<bool> DelegateApprovalsForUser(int userId, int delegatedUserId);
Task<bool> RemoveDelegatedApprovalsForUser(int userId, int delegatedUserId);
Task<bool> FlagUserAsOOO(OOOTemp oooTemp);
Task<bool> RemoveOOOFlagForUser(int userId);
Task<bool> SetOOOTempProcessed(OOOTemp oOOTemp);
Task<List<User>> GetAllActiveOOOUsersAsync();
Task<List<User>> GetAllExpiredOOOUsersAsync();
}
public class UserService : IUserService {
@ -33,16 +39,18 @@ public class UserService : IUserService {
throw new ArgumentNullException("IDalService not injected");
}
public async Task<List<User>> GetAllActiveOOOUsersAsync() {
public async Task<List<User>> GetAllExpiredOOOUsersAsync() {
try {
_logger.LogInformation("Attempting to get all active OOO users.");
string sql = "select * from Users where OOO = 1;";
StringBuilder queryBuilder = new();
queryBuilder.Append("select * from Users where OOO = 1 and IsActive = 1 and ");
queryBuilder.Append($"OOOExpirationDate <= '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}';");
return (await _dalService.QueryAsync<User>(sql)).ToList();
return (await _dalService.QueryAsync<User>(queryBuilder.ToString())).ToList();
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to get all active OOO users. Exception: {0}",
ex.Message);
string errMsg = $"An exception occurred when attempting to get all active OOO users. Exception: {ex.Message}";
_logger.LogError(errMsg);
throw;
}
}
@ -51,72 +59,76 @@ public class UserService : IUserService {
try {
_logger.LogInformation("Attempting to get all pending OOO users.");
string sql = string.Format("select * from OOOTemp where Processed = 0 and OOOStartDate <= '{0}';", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
StringBuilder queryBuilder = new();
queryBuilder.Append("select * from OOOTemp where Processed = 0 and ");
queryBuilder.Append($"OOOStartDate <= '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}';");
return (await _dalService.QueryAsync<OOOTemp>(sql)).ToList();
return (await _dalService.QueryAsync<OOOTemp>(queryBuilder.ToString())).ToList();
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to get all pending OOO users. Exception: {0}",
ex.Message);
string errMsg = $"An exception occurred when attempting to get all pending OOO users. Exception: {ex.Message}";
_logger.LogError(errMsg);
throw;
}
}
public async Task<bool> IsUserAlreadyOOO(int userId) {
try {
_logger.LogInformation("Attempting to determine if user {userId} is already OOO", userId);
_logger.LogInformation($"Attempting to determine if user {userId} is already OOO");
if (userId <= 0) {
throw new ArgumentException(string.Format("User Id {0} is not a valid user Id", userId));
throw new ArgumentException($"User Id {userId} is not a valid user Id");
} else {
string sql = string.Format("select * from Users where OOO = 1 and UserID = {0}", userId);
string sql = $"select * from Users where OOO = 1 and UserID = {userId}";
return (await _dalService.QueryAsync<User>(sql)).Count() > 0;
}
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to determine if user {userId} is already OOO. Exception: {ex}",
userId,
ex.Message);
StringBuilder errMsgBuilder = new();
errMsgBuilder.Append("An exception occurred when attempting to determine if user ");
errMsgBuilder.Append($"{userId} is already OOO. Exception: {ex.Message}");
_logger.LogError(errMsgBuilder.ToString());
throw;
}
}
public async Task<bool> IsDelegatorAlreadyDelegatedTo(int userId) {
try {
_logger.LogInformation("Attempting to determine if user {userId} is already OOO.", userId);
_logger.LogInformation($"Attempting to determine if user {userId} is already OOO.");
if (userId <= 0) {
_logger.LogInformation("DelegatedTo is {id}, which is not an active user Id", userId);
_logger.LogInformation($"DelegatedTo is {userId}, which is not an active user Id");
return false;
} else {
string sql = string.Format("select * from Users where DelegatedTo = {0}", userId);
string sql = $"select * from Users where DelegatedTo = {userId}";
return (await _dalService.QueryAsync<User>(sql)).Count() > 0;
}
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to determine if user {userId} is already delegated to. Exception: {ex}",
userId,
ex.Message);
StringBuilder errMsgBuilder = new();
errMsgBuilder.Append("An exception occurred when attempting to determine if user ");
errMsgBuilder.Append($"{userId} is already delegated to. Exception: {ex.Message}");
_logger.LogError(errMsgBuilder.ToString());
throw;
}
}
public async Task<bool> InsertDelegatedRoles(int userId) {
try {
_logger.LogInformation("Attempting to add delegated roles for OOO user {id}", userId);
_logger.LogInformation($"Attempting to add delegated roles for OOO user {userId}");
if (userId <= 0) {
throw new ArgumentException(string.Format("User Id {0} is not a valid user Id", userId));
throw new ArgumentException($"User Id {userId} is not a valid user Id");
} else {
StringBuilder queryBuilder = new StringBuilder();
string sql = string.Format("select * from UserSubRole where UserID = {0}", userId);
string sql = $"select * from UserSubRole where UserID = {userId}";
List<UserSubRole> userSubRoles = (await _dalService.QueryAsync<UserSubRole>(sql)).ToList();
foreach (UserSubRole role in userSubRoles) {
queryBuilder.Clear();
queryBuilder.Append("insert into OOODelegatedRoles (UserID, DelegatedSubRoleID, InsertTimeStamp, Active) ");
queryBuilder.AppendFormat("values ({0}, {1}, '{2}', 1);", userId, role.SubRoleID, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
queryBuilder.Append($"values ({userId}, {role.SubRoleID}, '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}', 1);");
await _dalService.ExecuteAsync(queryBuilder.ToString());
}
@ -124,63 +136,155 @@ public class UserService : IUserService {
return true;
}
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to add delegated roles for OOO user {userId}. Exception: {ex}",
userId,
ex.Message);
StringBuilder errMsgBuilder = new();
errMsgBuilder.Append($"An exception occurred when attempting to add delegated roles for OOO user {userId}. ");
errMsgBuilder.Append($"Exception: {ex.Message}");
_logger.LogError(errMsgBuilder.ToString());
throw;
}
}
public async Task<bool> UpdateUserSubRoles(int userId, int delegatedUserId) {
public async Task<bool> RemoveDelegatedRoles(int userId) {
try {
_logger.LogInformation("Attempting to update sub roles for user {userId} to delegated user {delegatedUserId}",
userId,
delegatedUserId);
_logger.LogInformation($"Attempting to remove delegated roles for OOO user {userId}");
if (userId <= 0) {
throw new ArgumentException(string.Format("User Id {0} is not a valid user Id", userId));
} else if (delegatedUserId <= 0) {
throw new ArgumentException(string.Format("Delegated user Id {0} is not a valid user Id", delegatedUserId));
throw new ArgumentException($"User Id {userId} is not a valid user Id");
} else {
string sql = String.Format("update UserSubRole set UserID = {0}, Delegated = 1 where UserID = {1}", delegatedUserId, userId);
string sql = $"update OOODelegatedRoles set Active = 0 where UserID = {userId} and Active = 1;";
await _dalService.ExecuteAsync(sql);
return true;
}
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to update sub roles for user {userId} to delegated user {delegatedUserId}. Exception: {ex}",
userId,
delegatedUserId,
ex.Message);
StringBuilder errMsgBuilder = new();
errMsgBuilder.Append($"An exception occurred when attempting to remove delegated roles for OOO user {userId}. ");
errMsgBuilder.Append($"Exception: {ex.Message}");
_logger.LogError(errMsgBuilder.ToString());
throw;
}
}
public async Task<bool> DelegateUserSubRoles(int userId, int delegatedUserId) {
try {
StringBuilder logMsgBuilder = new();
logMsgBuilder.Append($"Attempting to update sub roles for user {userId} ");
logMsgBuilder.Append($"to delegated user {delegatedUserId}");
_logger.LogInformation(logMsgBuilder.ToString());
if (userId <= 0) {
throw new ArgumentException($"User Id {userId} is not a valid user Id");
} else if (delegatedUserId <= 0) {
throw new ArgumentException($"Delegated user Id {delegatedUserId} is not a valid user Id");
} else {
string sql = $"update UserSubRole set UserID = {delegatedUserId}, Delegated = 1 where UserID = {userId}";
await _dalService.ExecuteAsync(sql);
return true;
}
} catch (Exception ex) {
StringBuilder errMsgBuilder = new();
errMsgBuilder.Append($"An exception occurred when attempting to update sub roles for user {userId} ");
errMsgBuilder.Append($"to delegated user {delegatedUserId}. Exception: {ex.Message}");
_logger.LogError(errMsgBuilder.ToString());
throw;
}
}
public async Task<bool> RemoveDelegatedUserSubRoles(int userId, int delegatedUserId) {
try {
_logger.LogInformation($"Attempting to remove delegated roles for OOO user {userId}");
if (userId <= 0) {
throw new ArgumentException($"User Id {userId} is not a valid user Id");
} else {
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append("select SubRoleID from OOODelegatedRoles O inner join UserSubRole U ");
queryBuilder.Append("on O.DelegatedSubRoleID = U.UserSubRoleID ");
queryBuilder.Append($"where O.UserID = {userId} and Active = 1");
List<int> userSubRoleIds = (await _dalService.QueryAsync<int>(queryBuilder.ToString())).ToList();
foreach (int id in userSubRoleIds) {
queryBuilder.Clear();
queryBuilder.Append($"update UserSubRole set UserID = {userId}, Delegated = 0 ");
queryBuilder.Append($"where UserID = {delegatedUserId} and Delegated = 1 ");
queryBuilder.Append($"and SubRoleID in ({string.Join(',', userSubRoleIds)})");
await _dalService.ExecuteAsync(queryBuilder.ToString());
}
return true;
}
} catch (Exception ex) {
StringBuilder errMsgBuilder = new();
errMsgBuilder.Append("An exception occurred when attempting to remove delegated roles for ");
errMsgBuilder.Append($"OOO user {userId}. Exception: {ex.Message}");
_logger.LogError(errMsgBuilder.ToString());
throw;
}
}
public async Task<bool> DelegateApprovalsForUser(int userId, int delegatedUserId) {
try {
_logger.LogInformation("Attempting to delegate approvals for user {userId} to delegated user {delegatedUserId}",
userId,
delegatedUserId);
_logger.LogInformation($"Attempting to delegate approvals for user {userId} to delegated user {delegatedUserId}");
if (userId <= 0) {
throw new ArgumentException(string.Format("User Id {0} is not a valid user Id", userId));
throw new ArgumentException($"User Id {userId} is not a valid user Id");
} else if (delegatedUserId <= 0) {
throw new ArgumentException(string.Format("Delegated user Id {0} is not a valid user Id", delegatedUserId));
throw new ArgumentException($"Delegated user Id {delegatedUserId} is not a valid user Id");
} else {
string sql = String.Format("update Approval set UserID = {0}, Delegated = 1 where UserID = {1} and (ItemStatus = {2} or ItemStatus = {3})",
delegatedUserId,
userId,
PENDING_ITEM_STATUS,
DENITED_ITEM_STATUS);
StringBuilder queryBuilder = new();
queryBuilder.Append($"update Approval set UserID = {delegatedUserId}, ");
queryBuilder.Append($"Delegated = 1 where UserID = {userId} ");
queryBuilder.Append($"and (ItemStatus = {PENDING_ITEM_STATUS} or ItemStatus = {DENITED_ITEM_STATUS})");
await _dalService.ExecuteAsync(sql);
await _dalService.ExecuteAsync(queryBuilder.ToString());
return true;
}
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to delegate approvals for user {userId} to delegated user {delegatedUserId}. Exception: {ex}",
userId,
delegatedUserId,
ex.Message);
StringBuilder errMsgBuilder = new();
errMsgBuilder.Append($"An exception occurred when attempting to delegate approvals for user {userId} ");
errMsgBuilder.Append($"to delegated user {delegatedUserId}. Exception: {ex.Message}");
_logger.LogError(errMsgBuilder.ToString());
throw;
}
}
public async Task<bool> RemoveDelegatedApprovalsForUser(int userId, int delegatedUserId) {
try {
_logger.LogInformation($"Attempting to remove delegated roles for OOO user {userId}");
if (userId <= 0) {
throw new ArgumentException($"User Id {userId} is not a valid user Id");
} else {
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append("select SubRoleID from OOODelegatedRoles O inner join UserSubRole U ");
queryBuilder.Append("on O.DelegatedSubRoleID = U.UserSubRoleID ");
queryBuilder.Append($"where O.UserID = {userId} and Active = 1");
List<int> userSubRoleIds = (await _dalService.QueryAsync<int>(queryBuilder.ToString())).ToList();
foreach (int id in userSubRoleIds) {
queryBuilder.Clear();
queryBuilder.Append($"update Approval set UserID = {userId}, Delegated = 0 ");
queryBuilder.Append($"where UserID = {delegatedUserId} and Delegated = 1 and ");
queryBuilder.Append($"(ItemStatus = {PENDING_ITEM_STATUS} or ItemStatus = {DENITED_ITEM_STATUS}) ");
queryBuilder.Append($"and SubRoleID in ({string.Join(',', userSubRoleIds)})");
await _dalService.ExecuteAsync(queryBuilder.ToString());
}
return true;
}
} catch (Exception ex) {
StringBuilder errMsgBuilder = new();
errMsgBuilder.Append("An exception occurred when attempting to remove delegated roles ");
errMsgBuilder.Append($"for OOO user {userId}. Exception: {ex.Message}");
_logger.LogError(errMsgBuilder.ToString());
throw;
}
}
@ -189,19 +293,37 @@ public class UserService : IUserService {
try {
if (oooTemp is null) throw new ArgumentNullException("oooTemp cannot be null");
_logger.LogInformation("Attempting to flag user {id} as OOO", oooTemp.OOOUserID);
_logger.LogInformation($"Attempting to flag user {oooTemp.OOOUserID} as OOO");
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append("update Users set OOO = 1, ");
queryBuilder.AppendFormat("OOOStartDate = '{0}', ", oooTemp.OOOStartDate);
queryBuilder.AppendFormat("OOOExpirationDate = '{0}', ", oooTemp.OOOExpirationDate);
queryBuilder.AppendFormat("DelegatedTo = {0} ", oooTemp.DelegatedTo);
queryBuilder.AppendFormat("where UserID = {0}", oooTemp.OOOUserID);
queryBuilder.Append($"OOOStartDate = '{oooTemp.OOOStartDate}', ");
queryBuilder.Append($"OOOExpirationDate = '{oooTemp.OOOExpirationDate}', ");
queryBuilder.Append($"DelegatedTo = {oooTemp.DelegatedTo} ");
queryBuilder.Append($"where UserID = {oooTemp.OOOUserID}");
return (await _dalService.ExecuteAsync(queryBuilder.ToString())) > 0;
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to flag user as OOO. Exception: {ex}",
ex.Message);
_logger.LogError($"An exception occurred when attempting to flag user as OOO. Exception: {ex.Message}");
throw;
}
}
public async Task<bool> RemoveOOOFlagForUser(int userId) {
try {
if (userId <= 0) throw new ArgumentException($"User Id {userId} is not a valid user Id");
_logger.LogInformation($"Attempting to remove OOO flag for user {userId}");
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append("update Users set OOO = 0, ");
queryBuilder.Append("OOOStartDate = NULL, OOOExpirationDate = NULL, ");
queryBuilder.Append("DelegatedTo = NULL ");
queryBuilder.Append($"where UserID = {userId}");
return (await _dalService.ExecuteAsync(queryBuilder.ToString())) > 0;
} catch (Exception ex) {
_logger.LogError($"An exception occurred when attempting to flag user as OOO. Exception: {ex.Message}");
throw;
}
}
@ -210,14 +332,13 @@ public class UserService : IUserService {
try {
if (oooTemp is null) throw new ArgumentNullException("oooTemp cannot be null");
_logger.LogInformation("Attempting to set OOOTemp {id} Processed to {processed}", oooTemp.ID, oooTemp.Processed);
_logger.LogInformation($"Attempting to set OOOTemp {oooTemp.ID} Processed to {oooTemp.Processed}");
string sql = string.Format("update OOOTemp set Processed = {0} where ID = {1}", oooTemp.Processed, oooTemp.ID);
string sql = $"update OOOTemp set Processed = {oooTemp.Processed} where ID = {oooTemp.ID}";
return (await _dalService.ExecuteAsync(sql)) > 0;
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to flag user as OOO. Exception: {ex}",
ex.Message);
_logger.LogError($"An exception occurred when attempting to flag user as OOO. Exception: {ex.Message}");
throw;
}
}