Created ExpiredOOOStatusWorker
This commit is contained in:
12
FabApprovalWorkerService/.config/dotnet-tools.json
Normal file
12
FabApprovalWorkerService/.config/dotnet-tools.json
Normal file
@ -0,0 +1,12 @@
|
||||
{
|
||||
"version": 1,
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"dotnet-ef": {
|
||||
"version": "8.0.3",
|
||||
"commands": [
|
||||
"dotnet-ef"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
@ -7,20 +7,28 @@
|
||||
<UserSecretsId>dotnet-FabApprovalWorkerService-e76dda63-1df3-422a-b758-1c057e5b1e25</UserSecretsId>
|
||||
<ServerGarbageCollection>true</ServerGarbageCollection>
|
||||
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild>
|
||||
<Configurations>Debug;Release;Staging</Configurations>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<Optimize>False</Optimize>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Staging|AnyCPU'">
|
||||
<Optimize>True</Optimize>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||
<Optimize>True</Optimize>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CsvHelper" Version="31.0.0" />
|
||||
<PackageReference Include="Dapper" Version="2.1.28" />
|
||||
<PackageReference Include="Dapper.Contrib" Version="2.0.78" />
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.2" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
|
||||
|
@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Controller_SelectedScaffolderID>ApiControllerEmptyScaffolder</Controller_SelectedScaffolderID>
|
||||
<Controller_SelectedScaffolderCategoryPath>root/Common/Api</Controller_SelectedScaffolderCategoryPath>
|
||||
<NameOfLastUsedPublishProfile>C:\Users\tuckerc\FabApprovalWorkerService\FabApprovalWorkerService\Properties\PublishProfiles\Staging.pubxml</NameOfLastUsedPublishProfile>
|
||||
</PropertyGroup>
|
||||
</Project>
|
@ -8,6 +8,7 @@ using NLog.Extensions.Logging;
|
||||
using Quartz;
|
||||
|
||||
using System.Data;
|
||||
using Microsoft.Data.SqlClient;
|
||||
|
||||
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
@ -17,25 +18,18 @@ builder.Logging.AddNLog();
|
||||
|
||||
builder.Services.AddHttpClient();
|
||||
|
||||
#if DEBUG
|
||||
builder.Services.AddScoped<IDbConnection>(db => new SqliteConnection(
|
||||
builder.Configuration.GetConnectionString("Default")));
|
||||
#else
|
||||
builder.Services.AddScoped<IDbConnection>(db => new SqlConnection(
|
||||
builder.Configuration.GetConnectionString("Default")));
|
||||
#endif
|
||||
|
||||
builder.Services.AddScoped<IDbConnectionService, DbConnectionService>();
|
||||
builder.Services.AddScoped<IMonInWorkerClient, MonInWorkerClient>();
|
||||
builder.Services.AddScoped<IDalService, DalService>();
|
||||
builder.Services.AddScoped<IUserService, UserService>();
|
||||
|
||||
builder.Services.AddQuartz(q => {
|
||||
JobKey updateCertDataJobKey = new JobKey("Pending OOO status job");
|
||||
JobKey pendingOOOStatusJob = new JobKey("Pending OOO status job");
|
||||
q.AddJob<PendingOOOStatusWorker>(opts => opts
|
||||
.WithIdentity(updateCertDataJobKey)
|
||||
.WithIdentity(pendingOOOStatusJob)
|
||||
);
|
||||
q.AddTrigger(opts => opts
|
||||
.ForJob(updateCertDataJobKey)
|
||||
.ForJob(pendingOOOStatusJob)
|
||||
.WithIdentity("Pending OOO status trigger")
|
||||
.WithSimpleSchedule(x => x
|
||||
.WithIntervalInMinutes(10)
|
||||
@ -43,6 +37,20 @@ builder.Services.AddQuartz(q => {
|
||||
)
|
||||
.StartNow()
|
||||
);
|
||||
|
||||
JobKey expiredOOOStatusJob = new JobKey("Expired OOO status job");
|
||||
q.AddJob<ExpiredOOOStatusWorker>(opts => opts
|
||||
.WithIdentity(expiredOOOStatusJob)
|
||||
);
|
||||
q.AddTrigger(opts => opts
|
||||
.ForJob(expiredOOOStatusJob)
|
||||
.WithIdentity("Expired OOO status trigger")
|
||||
.WithSimpleSchedule(x => x
|
||||
.WithIntervalInMinutes(10)
|
||||
.RepeatForever()
|
||||
)
|
||||
.StartNow()
|
||||
);
|
||||
});
|
||||
|
||||
builder.Services.AddQuartzHostedService(opt => {
|
||||
@ -50,4 +58,5 @@ builder.Services.AddQuartzHostedService(opt => {
|
||||
});
|
||||
|
||||
WebApplication app = builder.Build();
|
||||
|
||||
app.Run();
|
||||
|
@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||
-->
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<DeleteExistingFiles>false</DeleteExistingFiles>
|
||||
<ExcludeApp_Data>false</ExcludeApp_Data>
|
||||
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
|
||||
<LastUsedBuildConfiguration>Staging</LastUsedBuildConfiguration>
|
||||
<LastUsedPlatform>Any CPU</LastUsedPlatform>
|
||||
<PublishProvider>FileSystem</PublishProvider>
|
||||
<PublishUrl>C:\Users\tuckerc\FabApprovalWorkerService\FabApprovalWorkerService\bin\Staging\net8.0\win-x64\publish</PublishUrl>
|
||||
<WebPublishMethod>FileSystem</WebPublishMethod>
|
||||
<_TargetId>Folder</_TargetId>
|
||||
<SiteUrlToLaunchAfterPublish />
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<ProjectGuid>5a7ab539-1a6f-4903-ab52-62bcd0bfd7b9</ProjectGuid>
|
||||
<SelfContained>false</SelfContained>
|
||||
</PropertyGroup>
|
||||
</Project>
|
@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||
-->
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<_PublishTargetUrl>C:\Users\tuckerc\FabApprovalWorkerService\FabApprovalWorkerService\bin\Staging\net8.0\win-x64\publish</_PublishTargetUrl>
|
||||
<History>True|2024-03-21T23:38:09.4228384Z;True|2024-03-21T16:26:02.7031397-07:00;True|2024-03-21T16:23:46.2132963-07:00;True|2024-03-21T16:20:02.0161963-07:00;True|2024-03-21T15:31:17.0705590-07:00;True|2024-03-21T15:29:34.9689685-07:00;True|2024-03-21T14:40:14.0617291-07:00;True|2024-03-21T14:35:10.2219988-07:00;True|2024-03-21T14:33:07.2736782-07:00;True|2024-03-21T11:42:09.3198117-07:00;True|2024-03-21T11:23:29.1905112-07:00;True|2024-03-21T11:09:26.6417724-07:00;</History>
|
||||
<LastFailureDetails />
|
||||
</PropertyGroup>
|
||||
</Project>
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
30
FabApprovalWorkerService/Services/DbConnectionService.cs
Normal file
30
FabApprovalWorkerService/Services/DbConnectionService.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,3 +0,0 @@
|
||||
using FabApprovalWorkerService.Models;
|
||||
|
||||
namespace FabApprovalWorkerService.Services;
|
@ -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) {
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
@ -5,11 +5,14 @@ create table Approval (
|
||||
IssueID integer not null,
|
||||
UserID integer not null,
|
||||
ItemStatus integer default 0,
|
||||
Delegated integer default 0
|
||||
Delegated integer default 0,
|
||||
SubRoleId integer not null
|
||||
);
|
||||
|
||||
insert into Approval (IssueID, UserID)
|
||||
values (1, 15),
|
||||
(2, 34),
|
||||
(3, 2),
|
||||
(4, 19);
|
||||
insert into Approval (IssueID, UserID, Delegated, SubRoleId)
|
||||
values (1, 15, 0, 0),
|
||||
(2, 34, 0, 0),
|
||||
(3, 2, 0, 0),
|
||||
(4, 19, 0, 0),
|
||||
(5, 3, 1, 5),
|
||||
(6, 4, 1, 2);
|
@ -6,4 +6,8 @@ create table OOODelegatedRoles (
|
||||
DelegatedSubRoleID integer not null,
|
||||
InsertTimeStamp text not null,
|
||||
Active integer default 0
|
||||
);
|
||||
);
|
||||
|
||||
insert into OOODelegatedRoles (UserID, DelegatedSubRoleID, InsertTimeStamp, Active)
|
||||
values (1, 5, '2024-03-20 04:01:00', 1),
|
||||
(2, 2, '2024-03-20 04:00:00', 1);
|
@ -7,8 +7,10 @@ create table UserSubRole (
|
||||
Delegated integer default 0
|
||||
);
|
||||
|
||||
insert into UserSubRole (UserID, SubRoleID)
|
||||
values (15, 1),
|
||||
(34, 19),
|
||||
(2, 5),
|
||||
(19, 3);
|
||||
insert into UserSubRole (UserID, SubRoleID, Delegated)
|
||||
values (15, 1, 0),
|
||||
(34, 19, 0),
|
||||
(2, 5, 0),
|
||||
(19, 3, 0),
|
||||
(3, 5, 1),
|
||||
(4, 2, 1);
|
@ -23,51 +23,51 @@ create table Users (
|
||||
IsActive INTEGER default 1
|
||||
);
|
||||
|
||||
insert into Users (LoginID, FirstName, LastName, Email)
|
||||
values ('AsRa', 'Ra', 'As', 'email'),
|
||||
('AuTr', 'Tr', 'Au', 'email'),
|
||||
('AyNi', 'Ni', 'Ay', 'email'),
|
||||
('BaGr', 'Gr', 'Ba', 'email'),
|
||||
('BaGu', 'Gu', 'Ba', 'email'),
|
||||
('BeTo', 'To', 'Be', 'email'),
|
||||
('BeBr', 'Br', 'Be', 'email'),
|
||||
('BrKy', 'Ky', 'Br', 'email'),
|
||||
('CaSh', 'Sh', 'Ca', 'email'),
|
||||
('CaRe', 'Re', 'Ca', 'email'),
|
||||
('CaSt', 'St', 'Ca', 'email'),
|
||||
('ClNi', 'Ni', 'Cl', 'email'),
|
||||
('DaMi', 'Mi', 'Da', 'email'),
|
||||
('FuJe', 'Je', 'Fu', 'email'),
|
||||
('GaAl', 'Al', 'Ga', 'email'),
|
||||
('GoAs', 'As', 'Go', 'email'),
|
||||
('GoRu', 'Ru', 'Go', 'email'),
|
||||
('GoOr', 'Or', 'Go', 'email'),
|
||||
('HaAn', 'An', 'Ha', 'email'),
|
||||
('HaPa', 'Pa', 'Ha', 'email'),
|
||||
('HoJu', 'Ju', 'Ho', 'email'),
|
||||
('HoDe', 'De', 'Ho', 'email'),
|
||||
('HoVi', 'Vi', 'Ho', 'email'),
|
||||
('InCa', 'Ca', 'In', 'email'),
|
||||
('JaMi', 'Mi', 'Ja', 'email'),
|
||||
('LeTh', 'Th', 'Le', 'email'),
|
||||
('LeHa', 'Ha', 'Le', 'email'),
|
||||
('LoAn', 'An', 'Lo', 'email'),
|
||||
('LoCh', 'Ch', 'Lo', 'email'),
|
||||
('LuDa', 'Da', 'Lu', 'email'),
|
||||
('MaBr', 'Br', 'Ma', 'email'),
|
||||
('MaDa', 'Da', 'Ma', 'email'),
|
||||
('MaDo', 'Do', 'Ma', 'email'),
|
||||
('McJu', 'Ju', 'Mc', 'email'),
|
||||
('MeGi', 'Gi', 'Me', 'email'),
|
||||
('MiSh', 'Sh', 'Mi', 'email'),
|
||||
('MoBa', 'Ba', 'Mo', 'email'),
|
||||
('MuTi', 'Ti', 'Mu', 'email'),
|
||||
('OtMa', 'Ma', 'Ot', 'email'),
|
||||
('PeAl', 'Al', 'Pe', 'email'),
|
||||
('RiCy', 'Cy', 'Ri', 'email'),
|
||||
('RoAp', 'Ap', 'Ro', 'email'),
|
||||
('SoAb', 'Ab', 'So', 'email'),
|
||||
('VaMi', 'Mi', 'Va', 'email'),
|
||||
('VuTh', 'Th', 'Va', 'email'),
|
||||
('WeWi', 'Wi', 'We', 'email'),
|
||||
('ZaNi', 'Ni', 'Za', 'email');
|
||||
insert into Users (LoginID, FirstName, LastName, Email, OOO, OOOStartDate, OOOExpirationDate, DelegatedTo)
|
||||
values ('AsRa', 'Ra', 'As', 'email', 1, '2024-01-01 00:00:00', '2024-02-01 00:00:00', 3),
|
||||
('AuTr', 'Tr', 'Au', 'email', 1, '2024-01-01 00:00:00', '2024-02-01 00:00:00', 4),
|
||||
('AyNi', 'Ni', 'Ay', 'email', 0, '', '', 0),
|
||||
('BaGr', 'Gr', 'Ba', 'email', 0, '', '', 0),
|
||||
('BaGu', 'Gu', 'Ba', 'email', 0, '', '', 0),
|
||||
('BeTo', 'To', 'Be', 'email', 0, '', '', 0),
|
||||
('BeBr', 'Br', 'Be', 'email', 0, '', '', 0),
|
||||
('BrKy', 'Ky', 'Br', 'email', 0, '', '', 0),
|
||||
('CaSh', 'Sh', 'Ca', 'email', 0, '', '', 0),
|
||||
('CaRe', 'Re', 'Ca', 'email', 0, '', '', 0),
|
||||
('CaSt', 'St', 'Ca', 'email', 0, '', '', 0),
|
||||
('ClNi', 'Ni', 'Cl', 'email', 0, '', '', 0),
|
||||
('DaMi', 'Mi', 'Da', 'email', 0, '', '', 0),
|
||||
('FuJe', 'Je', 'Fu', 'email', 0, '', '', 0),
|
||||
('GaAl', 'Al', 'Ga', 'email', 0, '', '', 0),
|
||||
('GoAs', 'As', 'Go', 'email', 0, '', '', 0),
|
||||
('GoRu', 'Ru', 'Go', 'email', 0, '', '', 0),
|
||||
('GoOr', 'Or', 'Go', 'email', 0, '', '', 0),
|
||||
('HaAn', 'An', 'Ha', 'email', 0, '', '', 0),
|
||||
('HaPa', 'Pa', 'Ha', 'email', 0, '', '', 0),
|
||||
('HoJu', 'Ju', 'Ho', 'email', 0, '', '', 0),
|
||||
('HoDe', 'De', 'Ho', 'email', 0, '', '', 0),
|
||||
('HoVi', 'Vi', 'Ho', 'email', 0, '', '', 0),
|
||||
('InCa', 'Ca', 'In', 'email', 0, '', '', 0),
|
||||
('JaMi', 'Mi', 'Ja', 'email', 0, '', '', 0),
|
||||
('LeTh', 'Th', 'Le', 'email', 0, '', '', 0),
|
||||
('LeHa', 'Ha', 'Le', 'email', 0, '', '', 0),
|
||||
('LoAn', 'An', 'Lo', 'email', 0, '', '', 0),
|
||||
('LoCh', 'Ch', 'Lo', 'email', 0, '', '', 0),
|
||||
('LuDa', 'Da', 'Lu', 'email', 0, '', '', 0),
|
||||
('MaBr', 'Br', 'Ma', 'email', 0, '', '', 0),
|
||||
('MaDa', 'Da', 'Ma', 'email', 0, '', '', 0),
|
||||
('MaDo', 'Do', 'Ma', 'email', 0, '', '', 0),
|
||||
('McJu', 'Ju', 'Mc', 'email', 0, '', '', 0),
|
||||
('MeGi', 'Gi', 'Me', 'email', 0, '', '', 0),
|
||||
('MiSh', 'Sh', 'Mi', 'email', 0, '', '', 0),
|
||||
('MoBa', 'Ba', 'Mo', 'email', 0, '', '', 0),
|
||||
('MuTi', 'Ti', 'Mu', 'email', 0, '', '', 0),
|
||||
('OtMa', 'Ma', 'Ot', 'email', 0, '', '', 0),
|
||||
('PeAl', 'Al', 'Pe', 'email', 0, '', '', 0),
|
||||
('RiCy', 'Cy', 'Ri', 'email', 0, '', '', 0),
|
||||
('RoAp', 'Ap', 'Ro', 'email', 0, '', '', 0),
|
||||
('SoAb', 'Ab', 'So', 'email', 0, '', '', 0),
|
||||
('VaMi', 'Mi', 'Va', 'email', 0, '', '', 0),
|
||||
('VuTh', 'Th', 'Va', 'email', 0, '', '', 0),
|
||||
('WeWi', 'Wi', 'We', 'email', 0, '', '', 0),
|
||||
('ZaNi', 'Ni', 'Za', 'email', 0, '', '', 0);
|
79
FabApprovalWorkerService/Workers/ExpiredOOOStatusWorker.cs
Normal file
79
FabApprovalWorkerService/Workers/ExpiredOOOStatusWorker.cs
Normal file
@ -0,0 +1,79 @@
|
||||
using FabApprovalWorkerService.Models;
|
||||
using FabApprovalWorkerService.Services;
|
||||
|
||||
using Quartz;
|
||||
|
||||
using System.Text;
|
||||
|
||||
namespace FabApprovalWorkerService.Workers;
|
||||
|
||||
public sealed class ExpiredOOOStatusWorker : IJob {
|
||||
private readonly ILogger<ExpiredOOOStatusWorker> _logger;
|
||||
private readonly IMonInWorkerClient _monInClient;
|
||||
private readonly IUserService _userService;
|
||||
|
||||
public ExpiredOOOStatusWorker(ILogger<ExpiredOOOStatusWorker> logger,
|
||||
IMonInWorkerClient monInClient,
|
||||
IUserService userService) {
|
||||
_logger = logger;
|
||||
if (_logger is null)
|
||||
throw new ArgumentNullException("ILogger not injected");
|
||||
|
||||
_monInClient = monInClient;
|
||||
if (_monInClient is null) {
|
||||
throw new ArgumentNullException("IMonInWorkerClient not injected");
|
||||
}
|
||||
|
||||
_userService = userService;
|
||||
if (_userService is null)
|
||||
throw new ArgumentNullException("IUserService not injected");
|
||||
}
|
||||
|
||||
public async Task Execute(IJobExecutionContext context) {
|
||||
DateTime start = DateTime.Now;
|
||||
bool isInternalError = false;
|
||||
StringBuilder errorMessage = new();
|
||||
string metricName = "ExpiredOOOStatusWorker";
|
||||
|
||||
try {
|
||||
_logger.LogInformation("Attempting to remove OOO status for users with OOO expired earlier than now");
|
||||
|
||||
List<User> expiredOOOUsers = await _userService.GetAllExpiredOOOUsersAsync();
|
||||
|
||||
foreach (User user in expiredOOOUsers) {
|
||||
bool approvalsRemoved = await _userService.RemoveDelegatedApprovalsForUser(user.UserID, user.DelegatedTo);
|
||||
bool subRolesRemoved = await _userService.RemoveDelegatedUserSubRoles(user.UserID, user.DelegatedTo);
|
||||
bool rolesRemoved = await _userService.RemoveDelegatedRoles(user.UserID);
|
||||
bool oooFlagRemoved = await _userService.RemoveOOOFlagForUser(user.UserID);
|
||||
|
||||
if (approvalsRemoved && subRolesRemoved && rolesRemoved && oooFlagRemoved) {
|
||||
_logger.LogInformation("Successfully removed OOO status for users {id}", user.UserID);
|
||||
} else {
|
||||
StringBuilder errMsgBuilder = new();
|
||||
errMsgBuilder.Append($"An error occurred when attempting to remove OOO status for user {user.UserID}. ");
|
||||
errMsgBuilder.Append($"Approvals removed: {approvalsRemoved}, ");
|
||||
errMsgBuilder.Append($"sub roles removed: {subRolesRemoved}, ");
|
||||
errMsgBuilder.Append($"roles removed: {rolesRemoved}, ");
|
||||
errMsgBuilder.Append($"OOO flag removed: {oooFlagRemoved}");
|
||||
throw new Exception(errMsgBuilder.ToString());
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
StringBuilder errMsgBuilder = new();
|
||||
errMsgBuilder.Append("An exception occurred when attempting to remove OOO status for users with OOO expired ");
|
||||
errMsgBuilder.Append($"earlier than now. Exception: {ex.Message}");
|
||||
_logger.LogError(errMsgBuilder.ToString());
|
||||
isInternalError = true;
|
||||
} finally {
|
||||
DateTime end = DateTime.Now;
|
||||
double latencyInMS = (end - start).TotalMilliseconds;
|
||||
_monInClient.PostAverage(metricName + "Latency", latencyInMS);
|
||||
|
||||
if (isInternalError) {
|
||||
_monInClient.PostStatus(metricName, StatusValue.Critical);
|
||||
} else {
|
||||
_monInClient.PostStatus(metricName, StatusValue.Ok);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -47,7 +47,7 @@ public sealed class PendingOOOStatusWorker : IJob {
|
||||
if (!userAlreadyOOO.Result && !delegateAlreadyADelegate.Result) {
|
||||
List<Task> enableOOOTasks = new();
|
||||
enableOOOTasks.Add(_userService.InsertDelegatedRoles(oooTemp.OOOUserID));
|
||||
enableOOOTasks.Add(_userService.UpdateUserSubRoles(oooTemp.OOOUserID, oooTemp.DelegatedTo));
|
||||
enableOOOTasks.Add(_userService.DelegateUserSubRoles(oooTemp.OOOUserID, oooTemp.DelegatedTo));
|
||||
enableOOOTasks.Add(_userService.DelegateApprovalsForUser(oooTemp.OOOUserID, oooTemp.DelegatedTo));
|
||||
Task enableOOOTasksResult = Task.WhenAll(enableOOOTasks);
|
||||
|
||||
@ -63,8 +63,10 @@ public sealed class PendingOOOStatusWorker : IJob {
|
||||
|
||||
_logger.LogInformation("Successfully set OOO status for users pending earlier than now");
|
||||
} catch (Exception ex) {
|
||||
_logger.LogError("An exception occurred when attempting to set OOO status for users pending earlier than now. Exception: {ex}",
|
||||
ex.StackTrace);
|
||||
StringBuilder errMsgBuilder = new();
|
||||
errMsgBuilder.Append("An exception occurred when attempting to set OOO status for users ");
|
||||
errMsgBuilder.Append($"pending earlier than now. Exception: {ex.Message}");
|
||||
_logger.LogError(errMsgBuilder.ToString());
|
||||
isInternalError = true;
|
||||
} finally {
|
||||
DateTime end = DateTime.Now;
|
||||
|
@ -1,12 +1,6 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"Default": "Data Source=D:\\FabApprovalWorkerService\\LocalDb.db"
|
||||
"Default": "Data Source=MESTSV02EC.infineon.com\\TEST1,50572;Integrated Security=False;Initial Catalog=FabApprovalSystem;User ID=fab_approval_admin_test;Password=Fab_approval_admin_test2023!;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False; Min Pool Size=15"
|
||||
},
|
||||
"MonIn": {
|
||||
"resource": "FAB_APPROVAL_WORKER_SERVICE_MES_OP_FE_TEST",
|
||||
|
@ -1,11 +1,6 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"Development": "Data Source=D:\\FabApprovalWorkerService\\LocalDb.db",
|
||||
"Default": "Data Source=MESTSV02EC.infineon.com\\TEST1,50572;Integrated Security=False;Initial Catalog=FabApprovalSystem;User ID=fab_approval_admin_test;Password=Fab_approval_admin_test2023!;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False; Min Pool Size=15"
|
||||
},
|
||||
"MonIn": {
|
||||
|
32
FabApprovalWorkerService/nLog.Staging.config
Normal file
32
FabApprovalWorkerService/nLog.Staging.config
Normal file
@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
autoReload="true">
|
||||
|
||||
<extensions>
|
||||
<add assembly="NLog.Web.AspNetCore"/>
|
||||
</extensions>
|
||||
|
||||
<targets>
|
||||
<target name="asyncFile" xsi:type="AsyncWrapper">
|
||||
<target
|
||||
name="appLog"
|
||||
xsi:type="File"
|
||||
fileName="d:\logs\FabApprovalWorkerService\log.txt"
|
||||
archiveFilename="d:\logs\FabApprovalWorkerService\archive\log-${shortdate}.txt"
|
||||
maxArchiveFiles="15"
|
||||
archiveEvery="Day"
|
||||
/>
|
||||
<target
|
||||
name="consoleLog"
|
||||
xsi:type="Console"
|
||||
/>
|
||||
</target>
|
||||
</targets>
|
||||
|
||||
<rules>
|
||||
<logger name="Microsoft.*" finalMinLevel="Warn" />
|
||||
<logger name="System.Net.Http.HttpClient.*" finalMinLevel="Warn" />
|
||||
<logger name="*" minlevel="Debug" writeTo="consoleLog, appLog"/>
|
||||
</rules>
|
||||
</nlog>
|
Reference in New Issue
Block a user