This commit is contained in:
Zeeshaun
2026-03-17 09:53:09 -05:00
parent cdcba54aa4
commit 1a0702a79a
590 changed files with 62058 additions and 0 deletions
@@ -0,0 +1,58 @@
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Extensions;
public static class ActivityExtensions
{
public static StateChangeRequirement RequiredToChangeState(this Activity activity, ActivityState targetState)
{
return activity.State switch
{
ActivityState.Accepted => targetState switch
{
ActivityState.Accepted => StateChangeRequirement.AdminOrPermission,
ActivityState.ManualReview => StateChangeRequirement.AdminOrPermission,
ActivityState.PendingReferral when activity.Type == ActivityType.Referral => StateChangeRequirement.AdminOrPermission,
ActivityState.PendingTransfer => StateChangeRequirement.AdminOrPermission,
ActivityState.Rejected => StateChangeRequirement.AdminOrPermission,
_ => StateChangeRequirement.NotAllowed
},
ActivityState.Created => targetState switch
{
ActivityState.Accepted => StateChangeRequirement.SystemOnly,
ActivityState.ManualReview => StateChangeRequirement.SystemOnly,
ActivityState.PendingReferral => StateChangeRequirement.SystemOnly,
ActivityState.Rejected => StateChangeRequirement.SystemOnly,
_ => StateChangeRequirement.NotAllowed
},
ActivityState.ManualReview => targetState switch
{
ActivityState.Accepted => StateChangeRequirement.AdminOrPermission,
ActivityState.Rejected => StateChangeRequirement.Hierarchical,
_ => StateChangeRequirement.SystemOnly
},
ActivityState.PendingReferral => targetState switch
{
ActivityState.Accepted => StateChangeRequirement.AdminOrPermission,
ActivityState.Transferred => StateChangeRequirement.Hierarchical,
_ => StateChangeRequirement.NotAllowed
},
ActivityState.PendingTransfer => targetState switch
{
ActivityState.Accepted => StateChangeRequirement.AdminOrPermission,
ActivityState.Transferred => StateChangeRequirement.Hierarchical,
_ => StateChangeRequirement.NotAllowed
},
ActivityState.Rejected => targetState switch
{
ActivityState.Accepted => StateChangeRequirement.AdminOrPermission,
ActivityState.ManualReview => StateChangeRequirement.AdminOrPermission,
ActivityState.PendingReferral when activity.Type == ActivityType.Referral => StateChangeRequirement.AdminOrPermission,
_ => StateChangeRequirement.NotAllowed
},
ActivityState.Transferred => StateChangeRequirement.NotAllowed,
_ => StateChangeRequirement.NotAllowed
};
}
}
@@ -0,0 +1,56 @@
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Extensions;
public static class EntityFrameworkExtensions
{
public static IOrderedQueryable OrderBy<TSource>(this IQueryable query, string propertyName)
{
var entityType = typeof(TSource);
var propertyInfo = entityType.GetProperty(propertyName);
ParameterExpression arg = Expression.Parameter(entityType, "x");
MemberExpression property = Expression.Property(arg, propertyName);
var selector = Expression.Lambda(property, new ParameterExpression[] { arg });
var enumarableType = typeof(System.Linq.Queryable);
var method = enumarableType.GetMethods()
.Where(m => m.Name == "OrderBy" && m.IsGenericMethodDefinition)
.Where(m =>
{
var parameters = m.GetParameters().ToList();
return parameters.Count == 2;
}).Single();
MethodInfo genericMethod = method.MakeGenericMethod(entityType, propertyInfo.PropertyType);
var newQuery = (IOrderedQueryable)genericMethod.Invoke(genericMethod, new object[] { query, selector });
return newQuery;
}
public static IOrderedQueryable OrderByDescending<TSource>(this IQueryable query, string propertyName)
{
var entityType = typeof(TSource);
var propertyInfo = entityType.GetProperty(propertyName);
ParameterExpression arg = Expression.Parameter(entityType, "x");
MemberExpression property = Expression.Property(arg, propertyName);
var selector = Expression.Lambda(property, new ParameterExpression[] { arg });
var enumarableType = typeof(System.Linq.Queryable);
var method = enumarableType.GetMethods()
.Where(m => m.Name == "OrderByDescending" && m.IsGenericMethodDefinition)
.Where(m =>
{
var parameters = m.GetParameters().ToList();
return parameters.Count == 2;
}).Single();
MethodInfo genericMethod = method.MakeGenericMethod(entityType, propertyInfo.PropertyType);
var newQuery = (IOrderedQueryable)genericMethod.Invoke(genericMethod, new object[] { query, selector });
return newQuery;
}
}
@@ -0,0 +1,37 @@
using LCU.Library.Internal.IncentiveApiModels.Common;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Extensions;
public static class ObjectExtensions
{
public static IEnumerable<PropertyValueVariance> GetPropertyValueVariances<T>(this T objectInstanceOne, T objectInstanceTwo)
{
var propertyValueVariances = new List<PropertyValueVariance>();
var propertyInfoCollection = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(property => property.GetCustomAttributes().Any(attribute => attribute is UpdateAllowed));
foreach (var propertyInfo in propertyInfoCollection)
{
if (!Equals(propertyInfo.GetValue(objectInstanceOne), propertyInfo.GetValue(objectInstanceTwo)))
{
propertyValueVariances.Add(new PropertyValueVariance
{
ComparedProperty = propertyInfo.Name,
PropertyValueOne = GetPropertyValueOrDefaultString(objectInstanceOne, propertyInfo),
PropertyValueTwo = GetPropertyValueOrDefaultString(objectInstanceTwo, propertyInfo),
});
}
}
return propertyValueVariances;
}
private static string GetPropertyValueOrDefaultString<T>(this T queryObject, PropertyInfo propertyInfo)
{
var propertyValue = propertyInfo.GetValue(queryObject);
return propertyValue != null ? propertyValue.ToString() : "NULL";
}
}
@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Title>LCU.API.Internal.Operations.IncentiveApiLib</Title>
<AssemblyVersion>1.2.3</AssemblyVersion>
<FileVersion>1.2.3</FileVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CsvHelper" Version="27.2.1" />
<PackageReference Include="LCU.Api.Internal.FTPLib" Version="2.1.0" />
<PackageReference Include="LCU.Library.Internal.CoreApiWrapperModel" Version="2.20.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.20" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.20">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.20" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.20" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="TimeZoneConverter" Version="6.1.0" />
</ItemGroup>
<ItemGroup>
<Compile Remove="obj\**" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Remove="obj\**" />
</ItemGroup>
<ItemGroup>
<None Remove="obj\**" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LCU.Library.Internal.IncentiveApiModels\LCU.Library.Internal.IncentiveApiModels.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,760 @@
using System;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using LCU.Library.Internal.IncentiveApiModels.Common;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
public class ApplicationDbContext : DbContext, IApplicationDbContext
{
private readonly ICurrentUserService _currentUserService;
private readonly IDateTime _dateTime;
public ApplicationDbContext(
DbContextOptions options,
ICurrentUserService currentUserService,
IDateTime dateTime
) : base(options)
{
_currentUserService = currentUserService;
_dateTime = dateTime;
}
public DbSet<Goal> Goals { get; set; }
public DbSet<GoalChange> GoalChanges { get; set; }
public DbSet<Activity> Activities { get; set; }
public DbSet<ActivityDetail> ActivityDetails { get; set; }
public DbSet<ActivityStateChange> ActivityStateChanges { get; set; }
public DbSet<ActivityDetailUpdate> ActivityDetailUpdates { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<AppUser> AppUsers { get; set; }
public DbSet<UserDepartment> DepartmentAssignments { get; set; }
public DbSet<Commission> Commissions { get; set; }
public DbSet<ProcessorHistoryRecord> ProcessorRunHistory { get; set; }
public DbSet<UserPermission> UserPermissions { get; set; }
public DbSet<PayoutLineItem> PayoutLineItems { get; set; }
public DbSet<UserAssignment> UserAssignments { get; set; }
public DbSet<RoleMapping> RoleMappings { get; set; }
public DbSet<ActivityTransferAction> ActivityTransferActions { get; set; }
public DbSet<DeadActivity> DeadActivities { get; set; }
public DbSet<DepartmentLineItem> DepartmentLineItems { get; set; }
public DbSet<UserDepartmentHistory> UserDepartmentHistories { get; set; }
public DbSet<UserPermissionHistory> UserPermissionHistories { get; set; }
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
var currentUser = _currentUserService.GetCurrentUser();
var currentAppUser = ChangeTracker.Context.Set<AppUser>().FirstOrDefault(x => x.AdEmail == currentUser.Email);
var currentUserGuid = currentAppUser?.Id ?? Guid.Empty;
foreach (var entry in ChangeTracker.Entries<AuditCreate>())
{
if (entry.State == EntityState.Added)
{
entry.Entity.CreatedByType = currentUser.UserType();
entry.Entity.CreatedBy = currentUser.UserName();
entry.Entity.CreatedByAppUserId = currentUserGuid;
entry.Entity.Created = _dateTime.Now;
}
}
foreach (var entry in ChangeTracker.Entries<Auditable>())
{
if (entry.State == EntityState.Modified || entry.State == EntityState.Added)
{
entry.Entity.LastUpdatedByType = currentUser.UserType();
entry.Entity.LastUpdatedBy = currentUser.UserName();
entry.Entity.LastUpdatedByAppUserId = currentUserGuid;
entry.Entity.LastUpdated = _dateTime.Now;
}
}
return base.SaveChangesAsync(cancellationToken);
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ActivityPayoutLineItem>()
.ToTable("ActivityPayouts")
.HasKey(apli => new { apli.ActivityId, apli.PayoutLineItemId });
builder.Entity<ActivityPayoutLineItem>()
.HasOne(bg => bg.Activity)
.WithMany(b => b.ActivityPayouts)
.HasForeignKey(bg => bg.ActivityId);
builder.Entity<ActivityPayoutLineItem>()
.HasOne(bg => bg.PayoutLineItem)
.WithMany(g => g.ActivityPayouts)
.HasForeignKey(bg => bg.PayoutLineItemId);
builder.Entity<Activity>().ToTable("Activity");
builder.Entity<Activity>().HasKey(p => p.Id);
builder.Entity<Activity>()
.Property(e => e.Product)
.IsRequired()
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, Product.Unknown));
builder.Entity<Activity>()
.Property(e => e.Type)
.IsRequired()
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, ActivityType.Unknown));
builder.Entity<Activity>()
.Property(e => e.SourceSystem)
.IsRequired()
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, SystemType.Unknown));
builder.Entity<Activity>().Property(e => e.SourceId).IsRequired();
builder.Entity<Activity>().Property(e => e.SourceCreated).IsRequired();
builder.Entity<Activity>()
.HasOne(e => e.Detail)
.WithOne(b => b.Activity)
.HasForeignKey<ActivityDetail>(b => b.ActivityRef)
.IsRequired();
builder.Entity<Activity>()
.HasMany(e => e.MetaData)
.WithOne(b => b.Activity)
.HasForeignKey(b => b.ActivityRef);
builder.Entity<Activity>().Property(e => e.DepartmentId).IsRequired();
builder.Entity<Activity>().Property(e => e.EmployeeId).IsRequired();
builder.Entity<Activity>().Property(e => e.EmployeeEmail);
builder.Entity<Activity>().Property(e => e.MatchingActivityId).HasDefaultValue(0);
builder.Entity<Activity>().Property(e => e.MatchingDpAccessoryActivityId).HasDefaultValue(0);
builder.Entity<Activity>().Property(e => e.MatchingGapInsuranceActivityId).HasDefaultValue(0);
builder.Entity<Activity>().Property(e => e.Accepted).IsRequired();
builder.Entity<Activity>()
.Property(e => e.State)
.IsRequired()
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, ActivityState.Unknown));
builder.Entity<Activity>().HasIndex(e => e.Accepted);
builder.Entity<Activity>().HasIndex(e => new { e.Accepted, e.Id });
builder.Entity<ActivityDetail>().ToTable("ActivityDetail");
builder.Entity<ActivityDetail>().HasKey(p => p.Id);
builder.Entity<ActivityDetail>().HasIndex(p => new { p.ActivityRef, p.Id });
builder.Entity<ActivityDetail>().Property(p => p.SubAccountNumber).HasDefaultValue("");
builder.Entity<ActivityMetaData>().ToTable("ActivityMetaData");
builder.Entity<ActivityMetaData>().HasKey(p => p.Id);
builder.Entity<ActivityMetaData>().Property(p => p.MetaData);
builder.Entity<ActivityMetaData>()
.Property(p => p.MetaDataType)
.IsRequired()
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, MetaDataType.Unknown));
builder.Entity<ActivityMetaData>().HasIndex(p => new { p.ActivityRef, p.Id });
builder.Entity<Goal>().ToTable("Goals");
builder.Entity<Goal>().HasKey(p => p.Id);
builder.Entity<Goal>()
.Property(e => e.Product)
.IsRequired()
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, Product.Unknown));
builder.Entity<Goal>().Property(e => e.StartDate).IsRequired();
builder.Entity<Goal>().Property(e => e.EndDate).IsRequired();
builder.Entity<Goal>().Property(e => e.EmployeeId);
builder.Entity<Goal>().Property(e => e.DepartmentId);
builder.Entity<Goal>().Property(e => e.Value).IsRequired();
builder.Entity<Goal>().HasIndex(e => new { e.DepartmentId, e.StartDate, e.EndDate });
builder.Entity<Goal>().HasIndex(e => new { e.DepartmentId, e.StartDate, e.EndDate, e.Id });
builder.Entity<GoalChange>().ToTable("GoalChanges");
builder.Entity<GoalChange>().HasKey(p => p.Id);
builder.Entity<GoalChange>()
.Property(e => e.Product)
.IsRequired()
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, Product.Unknown));
builder.Entity<GoalChange>().Property(e => e.StartDate).IsRequired();
builder.Entity<GoalChange>().Property(e => e.EndDate).IsRequired();
builder.Entity<GoalChange>().Property(e => e.Value).IsRequired();
builder.Entity<Department>().ToTable("Departments");
builder.Entity<Department>().HasKey(p => p.Id);
builder.Entity<Department>().HasIndex(e => e.DepartmentName).IsUnique();
builder.Entity<Department>().Property(e => e.BusinessLineCode).IsRequired();
builder.Entity<Department>().Property(e => e.RegionCode);
builder.Entity<Department>().Property(e => e.DayforceDepartmentName).IsRequired();
builder.Entity<Department>().Property(e => e.DayForceGlCode).IsRequired();
builder.Entity<Department>().Property(e => e.DnaOrgNbr).IsRequired();
builder.Entity<Department>()
.Property(e => e.State)
.IsRequired()
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, DepartmentState.Unknown));
builder.Entity<AppUser>().ToTable("AppUser");
builder.Entity<AppUser>().HasKey(e => e.Id);
builder.Entity<AppUser>().Property(e => e.HomeDepartment).IsRequired();
builder.Entity<AppUser>().Property(e => e.FullName).IsRequired();
builder.Entity<AppUser>().Property(e => e.ManagerKey);
builder.Entity<AppUser>().Property(e => e.Terminated);
builder.Entity<AppUser>()
.Property(e => e.Role)
.HasConversion(
x => x.Name,
x => Role.DetermineRoleOrDefault(x)
)
.IsRequired();
builder.Entity<AppUser>().Property(e => e.BaseRole).IsRequired();
builder.Entity<AppUser>().HasMany(e => e.AdditionalPermissions).WithOne(e => e.AppUser);
builder.Entity<UserPermission>().ToTable("UserPermissions");
builder.Entity<UserPermission>().HasKey(e => e.Id);
builder.Entity<UserPermission>()
.HasOne(e => e.AppUser)
.WithMany(e => e.AdditionalPermissions)
.IsRequired();
builder.Entity<UserPermission>()
.Property(e => e.Permission)
.IsRequired()
.HasConversion(
x => x.Code,
x => Permission.GetAllPermissions(false).FirstOrDefault(perm => perm.Code.Equals(x)) ?? Permission.Unknown);
builder.Entity<UserDepartment>().ToTable("DeptAssignments");
builder.Entity<UserDepartment>().HasKey(p => p.Id);
builder.Entity<UserDepartment>().Property(e => e.StartDate).IsRequired();
builder.Entity<UserDepartment>().Property(e => e.EndDate);
builder.Entity<UserDepartment>().Property(e => e.Note);
builder.Entity<UserDepartment>().Property(e => e.SlidingPayout).HasColumnType("DECIMAL(5,2)").IsRequired().HasDefaultValue(0);
builder.Entity<UserDepartment>().Property(e => e.IsHome).IsRequired();
builder.Entity<UserDepartment>()
.HasOne(p => p.Employee)
.WithMany(b => b.Departments)
.IsRequired();
builder.Entity<UserDepartment>()
.HasOne(p => p.Department)
.WithMany(b => b.Assignments)
.IsRequired();
builder.Entity<UserDepartment>()
.Property(e => e.Role)
.HasConversion(
x => x.Name,
x => Role.DetermineRoleOrDefault(x)
)
.IsRequired();
builder.Entity<ActivityStateChange>().ToTable("ActivityStateChanges");
builder.Entity<ActivityStateChange>().HasKey(p => p.Id);
builder.Entity<ActivityStateChange>()
.HasOne<Activity>()
.WithMany()
.HasForeignKey(p => p.ActivityId)
.IsRequired();
builder.Entity<ActivityStateChange>()
.Property(e => e.State)
.IsRequired()
.HasConversion(
x => x.ToString(),
x => ConvertEnumOrDefault(x, ActivityState.Unknown))
.IsRequired();
builder.Entity<ActivityStateChange>().Property(e => e.AcceptedDate);
builder.Entity<ActivityStateChange>().Property(e => e.Note);
builder.Entity<ActivityDetailUpdate>().ToTable("ActivityDetailUpdates");
builder.Entity<ActivityDetailUpdate>().HasKey(p => p.Id);
builder.Entity<ActivityDetailUpdate>().HasOne<ActivityDetail>().WithMany().HasForeignKey(p => p.ActivityDetailId).IsRequired();
builder.Entity<ActivityDetailUpdate>().Property(e => e.Note);
builder.Entity<Commission>().ToTable("Commissions");
builder.Entity<Commission>().HasKey(p => p.Id);
builder.Entity<Commission>()
.Property(p => p.Product)
.IsRequired()
.HasConversion(
x => x.ToString(),
x => ConvertEnumOrDefault(x, Product.Unknown)
)
.IsRequired();
builder.Entity<Commission>().Property(p => p.RatePerProduct).IsRequired();
builder.Entity<Commission>()
.Property(p => p.Role)
.IsRequired()
.HasConversion(
x => x.Name,
x => Role.DetermineRoleOrDefault(x)
)
.IsRequired();
builder.Entity<Commission>().HasIndex(p => p.Role);
builder.Entity<ProcessorHistoryRecord>().ToTable("ProcessorRunHistory");
builder.Entity<ProcessorHistoryRecord>().HasKey(p => p.Process);
builder.Entity<ProcessorHistoryRecord>()
.Property(e => e.Process)
.HasConversion(
x => x.ToString(),
x => ConvertEnumOrDefault(x, Process.Unknown))
.IsRequired();
builder.Entity<ProcessorHistoryRecord>().Property(e => e.LastSuccessfulRunTime);
builder.Entity<ProcessorHistoryRecord>().Property(e => e.LastProcessedRecordId);
builder.Entity<ProcessorHistoryRecord>().Property(e => e.LastProcessedRecordTimestamp);
builder.Entity<PayoutLineItem>().ToTable("PayoutLineItems");
builder.Entity<PayoutLineItem>().HasKey(p => p.Id);
builder.Entity<PayoutLineItem>()
.Property(p => p.Product)
.IsRequired()
.HasConversion(
x => x.ToString(),
x => ConvertEnumOrDefault(x, Product.Unknown));
builder.Entity<PayoutLineItem>()
.Property(p => p.Role)
.IsRequired()
.HasConversion(
x => x.Name,
x => Role.DetermineRoleOrDefault(x)
);
builder.Entity<PayoutLineItem>().Property(p => p.EmployeeId).IsRequired();
builder.Entity<PayoutLineItem>().Property(p => p.DepartmentId).IsRequired();
builder.Entity<PayoutLineItem>().Property(p => p.ActivityPeriod).IsRequired();
builder.Entity<PayoutLineItem>().Property(p => p.ActivityTotal).HasColumnType("DECIMAL(12,2)").IsRequired();
builder.Entity<PayoutLineItem>().Property(p => p.PayoutTotal).HasColumnType("DECIMAL(12,2)").IsRequired();
builder.Entity<PayoutLineItem>().Property(p => p.SlidingPayout).HasColumnType("DECIMAL(5,2)").IsRequired();
builder.Entity<UserAssignment>().ToTable("UserAssignments").HasKey(p => p.Id);
builder.Entity<UserAssignment>()
.Property(p => p.Type)
.IsRequired()
.HasConversion(
x => x.ToString(),
x => ConvertEnumOrDefault(x, AssignmentType.Unknown));
builder.Entity<UserAssignment>().Property(p => p.Key).IsRequired();
builder.Entity<UserAssignment>().HasOne(p => p.AppUser).WithMany(p => p.Assignments).IsRequired();
builder.Entity<ActivityTransferAction>().ToTable("ActivityTransferActions").HasKey(p => p.Id);
builder.Entity<ActivityTransferAction>()
.Property(p => p.ActivityStateBeforeTransfer)
.IsRequired()
.HasConversion(
x => x.ToString(),
x => ConvertEnumOrDefault(x, ActivityState.Unknown)
);
builder.Entity<ActivityTransferAction>().Property(p => p.RequestedActivityId).IsRequired();
builder.Entity<ActivityTransferAction>()
.Property(p => p.State)
.IsRequired()
.HasConversion(
x => x.ToString(),
x => ConvertEnumOrDefault(x, ActivityTransferState.Unknown)
);
builder.Entity<ActivityTransferAction>().Property(p => p.NewActivityId);
builder.Entity<ActivityTransferAction>().Property(p => p.NewActivityDepartmentId).IsRequired();
builder.Entity<ActivityTransferAction>().Property(p => p.NewActivityEmployeeId).IsRequired();
builder.Entity<ActivityTransferAction>().Property(p => p.RequestedDepartmentApproved);
builder.Entity<ActivityTransferAction>().Property(p => p.RequestedDepartmentApprover);
builder.Entity<ActivityTransferAction>().Property(p => p.NewDepartmentApproved);
builder.Entity<ActivityTransferAction>().Property(p => p.NewDepartmentApprover);
builder.Entity<DeadActivity>().ToTable("DeadActivity");
builder.Entity<DeadActivity>().HasKey(p => p.Id);
builder.Entity<DeadActivity>()
.Property(e => e.Product)
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, Product.Unknown));
builder.Entity<DeadActivity>()
.Property(e => e.Reason)
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, DeadActivityReason.Unknown))
.IsRequired();
builder.Entity<DeadActivity>().Property(e => e.ReasonNote);
builder.Entity<DeadActivity>()
.Property(e => e.Type)
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, ActivityType.Unknown));
builder.Entity<DeadActivity>()
.Property(e => e.SourceSystem)
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, SystemType.Unknown));
builder.Entity<DeadActivity>().Property(e => e.SourceId);
builder.Entity<DeadActivity>().Property(e => e.SourceCreated);
builder.Entity<DeadActivity>()
.HasOne(e => e.DeadDetail)
.WithOne(b => b.DeadActivity)
.HasForeignKey<DeadActivityDetail>(b => b.DeadActivityRef);
builder.Entity<DeadActivity>().Property(e => e.DepartmentId);
builder.Entity<DeadActivity>().Property(e => e.EmployeeId);
builder.Entity<DeadActivity>().Property(e => e.EmployeeEmail);
builder.Entity<DeadActivity>().Property(e => e.Accepted);
builder.Entity<DeadActivity>()
.Property(e => e.State)
.HasConversion(x => x.ToString(),
x => ConvertEnumOrDefault(x, ActivityState.Unknown));
builder.Entity<DeadActivityDetail>().ToTable("DeadActivityDetail");
builder.Entity<DeadActivityDetail>().HasKey(p => p.Id);
builder.Entity<DepartmentLineItem>().ToTable("DepartmentLineItems");
builder.Entity<DepartmentLineItem>().HasKey(p => p.Id);
builder.Entity<DepartmentLineItem>().Property(p => p.PayoutTotal).HasColumnType("DECIMAL(12,2)").IsRequired();
builder.Entity<DepartmentLineItem>().Property(p => p.PayoutPercentage).HasColumnType("DECIMAL(5,2)").IsRequired();
builder.Entity<UserDepartmentHistory>().ToTable("UserDepartmentHistory");
builder.Entity<UserDepartmentHistory>().HasKey(p => p.Id);
builder.Entity<UserPermissionHistory>().ToTable("UserPermissionHistory");
builder.Entity<UserPermissionHistory>().HasKey(p => p.Id);
builder.Entity<RoleMapping>().ToTable("RoleMappings");
builder.Entity<RoleMapping>().HasKey(r => r.Id);
builder.Entity<RoleMapping>().Property(r => r.Id);
builder.Entity<RoleMapping>()
.Property(r => r.ApplicationRole)
.HasConversion(
x => x.Name,
x => Role.DetermineRoleOrDefault(x)
)
.IsRequired();
builder.Entity<RoleMapping>().Property(r => r.BusinessRole);
}
private static T ConvertEnumOrDefault<T>(string value, T defaultValue)
{
try
{
return (T)Enum.Parse(typeof(T), value);
}
catch (Exception)
{
return defaultValue;
}
}
public async Task SeedRoleMappingData()
{
try
{
if (RoleMappings.Any())
{
return;
}
RoleMappings.AddRange(new List<RoleMapping>
{
new() { ApplicationRole = Role.Teller, BusinessRole = "ACH REPRESENTATIVE" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "ACH SUPERVISOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "ADMIN ASSISTANT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "ADMIN ASST BUS LEND" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "APPLICATION SUP SPEC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "APPLICATIONS SUPPORT MANAGER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "ASSOCIATE COUNSEL - COMPLIANCE" },
new() { ApplicationRole = Role.ABM, BusinessRole = "ASST BRANCH MANAGER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "ASST MGR IND LENDING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "AVP / MANAGER, CARD OPERATIONS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "AVP LOAN SERVICING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "AVP FACILITIES & PURCHASING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "AVP, BUSINESS LENDING OPERATIONS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "AVP, CARD PRODUCT MGMT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "AVP, COLLECTIONS" },
new() { ApplicationRole = Role.Manager, BusinessRole = "AVP, DIGITAL & ONLINE SERVICING" },
new() { ApplicationRole = Role.Manager, BusinessRole = "AVP, MEMBER SERVICE" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "AVP/ACCOUNTING" },
new() { ApplicationRole = Role.BM, BusinessRole = "AVP/BRANCH MANAGER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "AVP/BUSINESS LENDING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "AVP/FACILITIES" },
new() { ApplicationRole = Role.Manager, BusinessRole = "AVP/MANAGER OPS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "AVP/MANAGER, CARD OPERATIONS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "AVP/MARKETING" },
new() { ApplicationRole = Role.Manager, BusinessRole = "AVP/MGR CONS LEN MSC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "AVP/MTG OPERATIONS" },
new() { ApplicationRole = Role.Manager, BusinessRole = "AVP/MTG SALES" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "BENEFITS ANALYST" },
new() { ApplicationRole = Role.BM, BusinessRole = "BRANCH MANAGER" },
new() { ApplicationRole = Role.BM, BusinessRole = "BRANCH MANAGER - CORE PROJECT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "BRANCH ONBOARDING COORDINATOR" },
new() { ApplicationRole = Role.BOM, BusinessRole = "BRANCH OP MANAGER" },
new() { ApplicationRole = Role.BusinessLineManager, BusinessRole = "BRANCH SUPPORT SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "BSA ASSOCIATE" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "BSA LEAD" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "BSA MANAGER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "BUS CREDIT ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "BUS LN DOC & CLOSING SPEC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "BUS LN SERVICING SPEC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "BUSINESS ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "BUSINESS INTELLIGENCE ENGINEER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CARD PROJECT ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CASH MANAGEMENT SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CFO" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CHIEF INFORMATION & RISK OFFICER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CHIEF PEOPLE OFFICER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CIO" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CL PROC MANAGER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CL PROC SUPERVISOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CLERK" },
new() { ApplicationRole = Role.LIC, BusinessRole = "CLIENT SRVC ASST-LIC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CLO" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CLV SUPERVISOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLL SPEC-BANKRUPTCY" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLL SPEC-CRED BUREA" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLL SPEC-FRAUD" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLL SPEC-LOSS MIT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLL SPEC-PROBATE" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLL SPEC-RECOVERY" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLL SPEC-REO FORE" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLL SPEC-REPOS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLL SPEC-SKIP TRACE" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLLECT BUS ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLLECTION CLERK" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLLECTIONS MANAGEMENT SYSTEM ADMINISTRATOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COLLECTOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COMMS SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COMPENSATION MANAGER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COMPLIANCE ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COMPLIANCE MANAGER - FAIR LENDING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COMPLIANCE MGR-ADVISORY" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COMPLIANCE OFFICER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COMPLIANCE SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "COMPLIANCE TRAINER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CONS LN PROC AUD CLE" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CONS LN PROCESSOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CONS LN COORDINATOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CONS LN VAULT CLERK" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CREDIT CARD MEMBER SERVICE REP" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CREDIT OPERATIONS COORDINATOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "CXO" },
new() { ApplicationRole = Role.Developer, BusinessRole = "DATA ARCHITECT" },
new() { ApplicationRole = Role.Developer, BusinessRole = "DATA ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "DEALER RELATION MGR" },
new() { ApplicationRole = Role.Developer, BusinessRole = "DEV OPS ENGINEER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "DESKTOP & FIELD SUPPORT SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "DIGITAL PROGRAM MANAGER" },
new() { ApplicationRole = Role.MSR, BusinessRole = "DIGITAL REPRESENTATIVE" },
new() { ApplicationRole = Role.MSR, BusinessRole = "DIGITAL REPRESENTATIVE (BILINGUAL)" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "DIR FIN PLAN & ANALY" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "DIR MGMNT REPORTING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "DIR SECURITY/FRAUD" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "DIRECTOR COMMUNITY RELATIONS & EVENTS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "DIRECTOR INV & TREAS" },
new() { ApplicationRole = Role.Manager, BusinessRole = "DIRECTOR MEMBER RELATIONSHIPS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "ENHANCED DUE DILIGEN" },
new() { ApplicationRole = Role.Developer, BusinessRole = "ENTERPRISE ARCHITECT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "ENTERPRISE RISK MGMT ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "ENTERPRISE RISK MGR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "EVP" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "EXECUTIVE ASSISTANT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "FACILITIES CLERK" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "FACILITIES SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "FINANCIAL ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "FINANCIAL OPERATIONS ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "FRAUD PREV ASSOCIATE - DEBIT CARDS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "FRAUD PREVENTION SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "GRAPHIC DESIGNER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "HR ADVISOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "HR BUSINESS PARTNER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "HR CONSULTANT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "HR COORDINATOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "IND LN/LS CLERK" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "IND LN/LS OFFICER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "IND LN/LS OFFICER N TRNG" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "IND LN/LS OFFICER PM" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "IND LN/LS PROC SUPV" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "IND LN/LS OFFICER N PM" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "IND LOAN PROC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "IND LOAN UNDERWRITER PM" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "INF SECURITY ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "INF SECURITY OFFICER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "INFRAST & OPER MGR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "INFRASTRUCTURE SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "INFRASTRUCTURE SUPPORT SPECIALIST - SHAREPOINT & O365" },
new() { ApplicationRole = Role.Mortgage, BusinessRole = "INTERNET MLO" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "INTERNAL COMM & ENGMNT SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "INV/SECURITY" },
new() { ApplicationRole = Role.OpsHelpDesk, BusinessRole = "IRA ADMINISTRATOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "IT DELIVERY MANAGER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "IT HELPDESK OPS SUP" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "IT HELPDESK/OPS I" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "IT HELPDESK/OPS II" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "ITEM PROCESSING CLK" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "LEAD COLLECT CLERK" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "LEAD IT DESK FIELD" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "LEAD PROCESS CLERK" },
new() { ApplicationRole = Role.Teller, BusinessRole = "LEAD TELLER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "LEGAL ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MAIL PROCESSING CLERK" },
new() { ApplicationRole = Role.ManagementTrainee, BusinessRole = "MANAGEMENT TRAINEE" },
new() { ApplicationRole = Role.Manager, BusinessRole = "MANAGER MSC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MANAGER, HUMAN RESOURCES" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MANAGER, INTERNAL AUDIT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MANAGER MTG SERVICING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MANAGER, TALENT ACQUISITION" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MARKETING ASSISTANT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MARKETING COORDINATOR, CONTENT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MARKETING COORDINATOR, CREATIVE" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MARKETING TRAFFIC & PROD MGR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MEMBER EXPERIENCE ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MEMBER EXP ANALYST" },
new() { ApplicationRole = Role.MSCTeamLead, BusinessRole = "MEMBER SERVICE ONBOARDING COORDINATOR" },
new() { ApplicationRole = Role.MSR, BusinessRole = "MEMBER SERVICE REP" },
new() { ApplicationRole = Role.MSR, BusinessRole = "MEMBER SERVICE REP (BILINGUAL)" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MGR BUS LEND CR OPS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MGR CONSUMER LOAN UNDERWRITING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MGR INDIRECT LOAN UNDERWRITING" },
new() { ApplicationRole = Role.Manager, BusinessRole = "MGR MEMBER SVS CTR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MORTGAGE CLOSING SUPERVISOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MORTGAGE DISCLOSURE DESK REPRESENTATIVE" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MORTGAGE QUALITY ASSURANCE SPECIALST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MRKTNG BUS ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MTG CLOSING CLERK" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MTG CLOSING COORDTR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MTG LN SERV SUPV" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MTG LN SV SPECIALIST" },
new() { ApplicationRole = Role.Mortgage, BusinessRole = "MTG LOAN ORIGINATOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MTG LOAN PROCESSOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MTG LOAN UNDERWRITER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MTG PROCESSING CLERK" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MTG PROCESSING SUP" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MTG SERVICING REP" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "MTG UNDERWRITING SUP" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "NET SUPP SPECIALIST" },
new() { ApplicationRole = Role.MSR, BusinessRole = "ONLINE EXPERIENCE SPECIALIST" },
new() { ApplicationRole = Role.MSR, BusinessRole = "ONLINE EXPERIENCE SPECIALIST (BILINGUAL)" },
new() { ApplicationRole = Role.OpsHelpDesk, BusinessRole = "OP HELP DESK REP" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "OPERATIONS MANAGER" },
new() { ApplicationRole = Role.Admin, BusinessRole = "OPERATIONS QUALITY CONTROL ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "OPERATIONS SUPP MGR" },
new() { ApplicationRole = Role.OpsHelpDesk, BusinessRole = "OPERATIONS SUPP SPEC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "ORG CHANGE/DEV LD" },
new() { ApplicationRole = Role.MSR, BusinessRole = "OUTBOUND MEMBER RELATION SPCL" },
new() { ApplicationRole = Role.MSR, BusinessRole = "OUTBOUND MEMBER RELATION SPCL (BILINGUAL)" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "PAYROLL & HRIS ADMINISTRATOR" },
new() { ApplicationRole = Role.PFO, BusinessRole = "PERS FIN OFFICER" },
new() { ApplicationRole = Role.PFO, BusinessRole = "PERS FIN OFFICER - MSC" },
new() { ApplicationRole = Role.PFO, BusinessRole = "PERS FIN OFFICER - MSC (BILINGUAL)" },
new() { ApplicationRole = Role.PFO, BusinessRole = "PFO IN TRAINING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "PHYSICAL SECURITY MANAGER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "PORT MGR BUS LENDING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "PRESIDENT/CEO" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "PROCESS ENGINEER MANAGER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "PRODUCT MANAGER, DIGITAL BANKING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "PRODUCT MANAGER, RETAIL DEPOSITS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "PROJECT MANAGER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "PURCH SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "PURCHASING ASSISTANT" },
new() { ApplicationRole = Role.MSCTeamLead, BusinessRole = "QUALITY ASSUR SPCLST" },
new() { ApplicationRole = Role.MSCTeamLead, BusinessRole = "QUALITY ASSURANCE SPECIALIST - MSC" },
new() { ApplicationRole = Role.Developer, BusinessRole = "QUALITY ASSURANCE ANALYST" },
new() { ApplicationRole = Role.Teller, BusinessRole = "RECEPTIONIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "RECRUITER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SECURITY SERVICES" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SOC MEDIA SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SOFT ENG/DATA" },
new() { ApplicationRole = Role.Developer, BusinessRole = "SOFTWARE ENG" },
new() { ApplicationRole = Role.Developer, BusinessRole = "SOFTWARE ENGINEERING MANAGER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR ADMIN ASSISTANT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR BSA ASSOC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR BUS CRED ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR. BUSINESS ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR BUS LN DOC & CLOSING SPEC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR COMPENSATION ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR COMPLIANCE ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR CONS LN PROCESSOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR CONS LN UNDERWRITER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR DATABASE ADMINISTRATOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR ENHANCED DUE DILIGENCE ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR FIN ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR IND LN PROC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR IND LN/LS OFFICER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR IND LN/LS OFFICER PM" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR IND LOAN UNDERWRITER PM" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR IND LOAN UNDERWRITER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR INFRAS SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR INTERNAL AUDITOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR INV/SECURITY" },
new() { ApplicationRole = Role.LIC, BusinessRole = "SR INVESTMENT REP" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR LEADERSHIP DEV ADVISOR" },
new() { ApplicationRole = Role.MSR, BusinessRole = "SR MEMBER SERV REP" },
new() { ApplicationRole = Role.MSR, BusinessRole = "SR MEMBER SERV REP (BILINGUAL)" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR MTG LOAN PROCESSOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR MORTGAGE CLOSING COORDINATOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR MORTGAGE SERVICES SYSTEMS ADMINISTRATOR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR MTG LOAN UNDERWRITER" },
new() { ApplicationRole = Role.PFO, BusinessRole = "SR ORG CHANGE & COMMUNICATIONS ADVISOR" },
new() { ApplicationRole = Role.PFO, BusinessRole = "SR PERS FIN OFFICER" },
new() { ApplicationRole = Role.PFO, BusinessRole = "SR PERS FIN OFFICER - MSC" },
new() { ApplicationRole = Role.Developer, BusinessRole = "SR SOFTWARE ENG" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR STAFF ACCOUNTANT" },
new() { ApplicationRole = Role.Teller, BusinessRole = "SR TELLER II (FLOATER)" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR BUSINESS ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SR THIRD PARTY MANAGEMENT ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "STAFF ACCOUNTANT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "STAFF COUNSEL" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "STAFF INT AUDITOR" },
new() { ApplicationRole = Role.Manager, BusinessRole = "SUPERVISOR, MORTGAGE LENDING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SUPVR COLLECTIONS" },
new() { ApplicationRole = Role.BusinessLineManager, BusinessRole = "SVP BR STRATEGY & DE" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SVP BUSINESS LENDING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SVP DIGITAL STRATEGY" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SVP HR TRNG COMMUNIC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "SVP LEGAL, RISK & COMPLIANCE" },
new() { ApplicationRole = Role.Manager, BusinessRole = "SVP MORTGAGE SERVICES" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TALENT ACQUISITION SPECIALIST" },
new() { ApplicationRole = Role.MSCTeamLead, BusinessRole = "TEAM LDR - MSC LOANS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TEAM LDR-CLP" },
new() { ApplicationRole = Role.MSCTeamLead, BusinessRole = "TEAM LDR-CONS LN-MSC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TEAM LDR-IND LNDG" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TEAM LDR-IND LNDG PM" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TEAM LDR-INDIRECT LOAN PM" },
new() { ApplicationRole = Role.MSCTeamLead, BusinessRole = "TEAM LDR-MSC" },
new() { ApplicationRole = Role.MSCTeamLead, BusinessRole = "TEAM LDR-MSC (BILINGUAL)" },
new() { ApplicationRole = Role.LIC, BusinessRole = "TEAM LEAD - CLIENT SERVICES ASSISTANTS" },
new() { ApplicationRole = Role.Mortgage, BusinessRole = "TEAM LEAD - MTG SERVICING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TEAM LEAD-COLLECTION" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TEAM LEADER - CARD SERVICES" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TECHNICAL WRITER" },
new() { ApplicationRole = Role.Teller, BusinessRole = "TELLER I" },
new() { ApplicationRole = Role.Teller, BusinessRole = "TELLER I (CO-OP)" },
new() { ApplicationRole = Role.Teller, BusinessRole = "TELLER I (FLOATER)" },
new() { ApplicationRole = Role.Teller, BusinessRole = "TELLER II" },
new() { ApplicationRole = Role.Teller, BusinessRole = "TELLER II (FLOATER)" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "THIRD PARTY MANAGEMENT ANALYST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TITLE CLERK" },
new() { ApplicationRole = Role.MSCTeamLead, BusinessRole = "TM LDR DIGITAL BANK" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TRAINER-MSC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TRAINER-PROF DEV/CHNG" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TRNG ONBD SPECIALIST" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "TRNG OPER SPECIALIST" },
new() { ApplicationRole = Role.UniversalSpecialistPFO, BusinessRole = "UNIVERSAL SPECIALIST" },
new() { ApplicationRole = Role.UniversalSpecialistTeller, BusinessRole = "UNIVERSAL SPECIALIST (FLOATER)" },
new() { ApplicationRole = Role.RegionalManager, BusinessRole = "VP BR SALES & SRVC" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP BUSINESS LENDING TEAM LEAD" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP CARD SERVICES" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP COLLECTIONS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP COMM DEVELOPMENT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP CONSUMER LENDING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP CONTROLLER" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP HUMAN RESOURCES" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP IND LENDING" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP INTERNAL AUDIT" },
new() { ApplicationRole = Role.LIC, BusinessRole = "VP LANDMARK INV CTR" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP MARKETING" },
new() { ApplicationRole = Role.BusinessLineManager, BusinessRole = "VP MEMBER SERVICE CENTER" },
new() { ApplicationRole = Role.Mortgage, BusinessRole = "VP MORTGAGE" },
new() { ApplicationRole = Role.Manager, BusinessRole = "VP MORTGAGE SALES" },
new() { ApplicationRole = Role.Admin, BusinessRole = "VP OPERATIONS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP ORGANIZATIONAL CHANGE MANAGEMENT & COMMUNICATIONS" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP PROJ MGMNT" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP SOFTWARE ENG & DA" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "VP TRAINING & DEV" },
new() { ApplicationRole = Role.UNKNOWN_ROLE, BusinessRole = "WEBSITE CONTENT SPECIALIST" }
});
await SaveChangesAsync();
}
catch
{
return;
}
}
}
@@ -0,0 +1,772 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Results;
using Microsoft.EntityFrameworkCore;
using Serilog;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
public class ApplicationDbIntegrityService : IApplicationDbIntegrityService
{
private readonly ApplicationDbContext _applicationDbContext;
private const string DataIntegrityFailureMessage = "AppUserId maintenance was required, the system was unable to carry out all of this maintenance in an automated fashion and this must be looked into immediately";
private const string DataIntegrityPartialSuccessMessage = "AppUserId maintenance was required, it was carried out in an automated fashion but this should not have been required and needs to be looked into";
private const string DataIntegritySuccessMessage = "Data integrity audit finished successfully, no maintenance was required";
public ApplicationDbIntegrityService(ApplicationDbContext applicationDbContext)
{
_applicationDbContext = applicationDbContext;
}
public async Task<bool> AppUserIdIntegrityMaintenanceSucceeded(CancellationToken cancellationToken)
{
try
{
EnsureAuditCreateAndUpdateAppUserIds();
Log.Information("ApplicationDbIntegrity: RunDataIntegrityAudit method Started");
var allMaintenanceResults = new List<DataIntegrityAuditResult>
{
await DetermineActivityMaintenanceAuditResult(),
await DetermineActivityTransferActionMaintenanceAuditResult(),
await DetermineDeadActivityMaintenanceAuditResult(),
await DetermineGoalMaintenanceAuditResult(),
await DetermineGoalChangeMaintenanceAuditResult()
};
Log.Information("ApplicationDbIntegrity: RunDataIntegrityAudit method Ended");
var overallMaintenanceResult = await DetermineOverallDataIntegrityAuditResult(allMaintenanceResults);
if (!overallMaintenanceResult.MaintenanceAutomationFailed && !overallMaintenanceResult.MaintenanceWasRequired)
{
Log.Information(DataIntegritySuccessMessage);
return true;
}
if (!overallMaintenanceResult.MaintenanceAutomationFailed && overallMaintenanceResult.MaintenanceWasRequired)
{
Log.Information(DataIntegrityPartialSuccessMessage);
throw new Exception(DataIntegrityPartialSuccessMessage);
}
if (!overallMaintenanceResult.MaintenanceAutomationFailed && overallMaintenanceResult.MaintenanceWasRequired)
{
Log.Information(DataIntegrityFailureMessage);
throw new Exception(DataIntegrityFailureMessage);
}
return false;
}
catch (Exception ex)
{
Log.Error(ex, $"Failed to execute AppUserId integrity checks, Error: {ex.Message}");
return false;
}
}
private async Task<DataIntegrityAuditResult> DetermineOverallDataIntegrityAuditResult(List<DataIntegrityAuditResult> dataIntegrityAuditResults)
{
return await Task.FromResult(
new DataIntegrityAuditResult
{
MaintenanceAutomationFailed = dataIntegrityAuditResults.Any(x => x.MaintenanceAutomationFailed),
MaintenanceWasRequired = dataIntegrityAuditResults.Any(x => x.MaintenanceWasRequired)
});
}
private async Task<DataIntegrityAuditResult> DetermineActivityMaintenanceAuditResult()
{
var dataIntegrityAuditResult = new DataIntegrityAuditResult();
var targetEmployeeIds = _applicationDbContext.Activities.Where(x => x.EmployeeId != null && x.AppUserId == Guid.Empty)
.Select(x => x.EmployeeId)
.Distinct();
if (!targetEmployeeIds.Any())
{
return dataIntegrityAuditResult;
}
dataIntegrityAuditResult.MaintenanceWasRequired = true;
Log.Warning("Found Activity records with empty AppUserIds, this should not happen and needs to be investigated");
foreach (var targetEmployeeId in targetEmployeeIds)
{
try
{
var appUsers = _applicationDbContext.AppUsers.Where(x => x.EmployeeId == targetEmployeeId);
if (appUsers.Count() != 1)
{
Log.Information($"{appUsers.Count()} returned from AppUser lookup on {targetEmployeeId} during DetermineActivityMaintenanceAuditResult, " +
$"unable to perform automatic maintenance this needs to be addressed manually");
dataIntegrityAuditResult.MaintenanceAutomationFailed = true;
continue;
}
var appUser = await appUsers.FirstAsync();
foreach (var item in _applicationDbContext.Activities.Where(x => x.EmployeeId == appUser.EmployeeId
&& x.AppUserId == Guid.Empty))
{
item.AppUserId = appUser.Id;
}
}
catch (Exception ex)
{
dataIntegrityAuditResult.MaintenanceAutomationFailed = true;
Log.Error(ex, ex.Message);
}
}
return dataIntegrityAuditResult;
}
private async Task<DataIntegrityAuditResult> DetermineActivityTransferActionMaintenanceAuditResult()
{
var dataIntegrityAuditResult = new DataIntegrityAuditResult();
var targetEmployeeIds = _applicationDbContext.ActivityTransferActions.Where(x => x.NewActivityEmployeeId != null && x.NewAppUserId == Guid.Empty)
.Select(x => x.NewActivityEmployeeId)
.Distinct();
if (!targetEmployeeIds.Any())
{
return dataIntegrityAuditResult;
}
dataIntegrityAuditResult.MaintenanceWasRequired = true;
Log.Information("Found ActivityTransferAction records with empty AppUserIds, this should not happen and needs to be investigated");
foreach (var targetEmployeeId in targetEmployeeIds)
{
try
{
var appUsers = _applicationDbContext.AppUsers.Where(x => x.EmployeeId == targetEmployeeId);
if (appUsers.Count() != 1)
{
Log.Information($"{appUsers.Count()} returned from AppUser lookup on {targetEmployeeId} during DetermineActivityTransferActionMaintenanceAuditResult, " +
$"unable to perform automatic maintenance this needs to be addressed manually");
dataIntegrityAuditResult.MaintenanceAutomationFailed = true;
continue;
}
var appUser = await appUsers.FirstAsync();
foreach (var item in _applicationDbContext.ActivityTransferActions.Where(x => x.NewActivityEmployeeId == appUser.EmployeeId
&& x.NewAppUserId == Guid.Empty))
{
item.NewAppUserId = appUser.Id;
}
}
catch (Exception ex)
{
dataIntegrityAuditResult.MaintenanceAutomationFailed = true;
Log.Error(ex, ex.Message);
}
}
return dataIntegrityAuditResult;
}
private void EnsureAuditCreateAndUpdateAppUserIds()
{
Log.Information("ApplicationDbIntegrity: EnsureAuditCreateAndUpdateAppUserIds method Started");
foreach (var appUser in _applicationDbContext.AppUsers)
{
try
{
SyncIdsWithDb(appUser, true).GetAwaiter().GetResult();
}
catch (Exception ex)
{
Log.Error(ex, ex.Message);
}
}
Log.Information("ApplicationDbIntegrity: EnsureAuditCreateAndUpdateAppUserIds method Ended");
}
private async Task<DataIntegrityAuditResult> DetermineDeadActivityMaintenanceAuditResult()
{
var dataIntegrityAuditResult = new DataIntegrityAuditResult();
var targetEmployeeIds = _applicationDbContext.DeadActivities.Where(x => x.EmployeeId != null && x.AppUserId == Guid.Empty)
.Select(x => x.EmployeeId)
.Distinct();
if (!targetEmployeeIds.Any())
{
return dataIntegrityAuditResult;
}
dataIntegrityAuditResult.MaintenanceWasRequired = true;
Log.Information("Found DeadActivity records with empty AppUserIds, this should not happen and needs to be investigated");
foreach (var targetEmployeeId in targetEmployeeIds)
{
try
{
var appUsers = _applicationDbContext.AppUsers.Where(x => x.EmployeeId == targetEmployeeId);
if (appUsers.Count() != 1)
{
Log.Information($"{appUsers.Count()} returned from AppUser lookup on {targetEmployeeId} during DetermineDeadActivityMaintenanceAuditResult, " +
$"unable to perform automatic maintenance this needs to be addressed manually");
dataIntegrityAuditResult.MaintenanceAutomationFailed = true;
continue;
}
var appUser = await appUsers.FirstAsync();
foreach (var item in _applicationDbContext.DeadActivities.Where(x => x.EmployeeId == appUser.EmployeeId
&& x.AppUserId == Guid.Empty))
{
item.AppUserId = appUser.Id;
}
}
catch (Exception ex)
{
dataIntegrityAuditResult.MaintenanceAutomationFailed = true;
Log.Error(ex, ex.Message);
}
}
return dataIntegrityAuditResult;
}
private async Task<DataIntegrityAuditResult> DetermineGoalMaintenanceAuditResult()
{
var dataIntegrityAuditResult = new DataIntegrityAuditResult();
var targetEmployeeIds = _applicationDbContext.Goals.Where(x => x.EmployeeId != null && x.AppUserId == Guid.Empty).Select(x => x.EmployeeId).Distinct();
if (!targetEmployeeIds.Any())
{
return dataIntegrityAuditResult;
}
dataIntegrityAuditResult.MaintenanceWasRequired = true;
Log.Information("Found Goal records with empty AppUserIds, this should not happen and needs to be investigated");
foreach (var targetEmployeeId in targetEmployeeIds)
{
try
{
var appUsers = _applicationDbContext.AppUsers.Where(x => x.EmployeeId == targetEmployeeId);
if (appUsers.Count() != 1)
{
Log.Information($"{appUsers.Count()} returned from AppUser lookup on {targetEmployeeId} during DetermineGoalMaintenanceAuditResult, " +
$"unable to perform automatic maintenance this needs to be addressed manually");
dataIntegrityAuditResult.MaintenanceAutomationFailed = true;
continue;
}
var appUser = await appUsers.FirstAsync();
foreach (var item in _applicationDbContext.Goals.Where(x => x.EmployeeId == appUser.EmployeeId
&& x.AppUserId == Guid.Empty))
{
item.AppUserId = appUser.Id;
}
}
catch (Exception ex)
{
dataIntegrityAuditResult.MaintenanceAutomationFailed = true;
Log.Error(ex, ex.Message);
}
}
return dataIntegrityAuditResult;
}
private async Task<DataIntegrityAuditResult> DetermineGoalChangeMaintenanceAuditResult()
{
var dataIntegrityAuditResult = new DataIntegrityAuditResult();
var targetEmployeeIds = _applicationDbContext.GoalChanges.Where(x => x.PersonId != null && x.AppUserId == Guid.Empty)
.Select(x => x.PersonId)
.Distinct();
if (!targetEmployeeIds.Any())
{
return dataIntegrityAuditResult;
}
dataIntegrityAuditResult.MaintenanceWasRequired = true;
Log.Information("Found GoalChange records with empty AppUserIds, this should not happen and needs to be investigated");
foreach (var targetEmployeeId in targetEmployeeIds)
{
try
{
var appUsers = _applicationDbContext.AppUsers.Where(x => x.EmployeeId == targetEmployeeId);
if (appUsers.Count() != 1)
{
Log.Information($"{appUsers.Count()} returned from AppUser lookup on {targetEmployeeId} during DetermineGoalChangeMaintenanceAuditResult, " +
$"unable to perform automatic maintenance this needs to be addressed manually");
dataIntegrityAuditResult.MaintenanceAutomationFailed = true;
continue;
}
var appUser = await appUsers.FirstAsync();
foreach (var item in _applicationDbContext.GoalChanges.Where(x => x.PersonId == appUser.EmployeeId
&& x.AppUserId == Guid.Empty))
{
item.AppUserId = appUser.Id;
}
}
catch (Exception ex)
{
dataIntegrityAuditResult.MaintenanceAutomationFailed = true;
Log.Error(ex, ex.Message);
}
}
return dataIntegrityAuditResult;
}
public async Task<bool> SyncAppUserUpdate(AppUser appUser)
{
try
{
foreach (var item in _applicationDbContext.Activities.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.Activities.Where(x => x.LastUpdatedByAppUserId == appUser.Id))
{
item.LastUpdatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.Activities.Where(x => x.AppUserId == appUser.Id))
{
item.EmployeeEmail = appUser.AdEmail;
item.EmployeeId = appUser.EmployeeId;
}
foreach (var item in _applicationDbContext.ActivityDetailUpdates.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.ActivityStateChanges.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.ActivityTransferActions.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.ActivityTransferActions.Where(x => x.LastUpdatedByAppUserId == appUser.Id))
{
item.LastUpdatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.AppUsers.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.AppUsers.Where(x => x.LastUpdatedByAppUserId == appUser.Id))
{
item.LastUpdatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.Commissions.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.Commissions.Where(x => x.LastUpdatedByAppUserId == appUser.Id))
{
item.LastUpdatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.DeadActivities.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.DeadActivities.Where(x => x.LastUpdatedByAppUserId == appUser.Id))
{
item.LastUpdatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.DeadActivities.Where(x => x.AppUserId == appUser.Id))
{
item.EmployeeEmail = appUser.AdEmail;
item.EmployeeId = appUser.EmployeeId;
}
foreach (var item in _applicationDbContext.DepartmentAssignments.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.DepartmentAssignments.Where(x => x.LastUpdatedByAppUserId == appUser.Id))
{
item.LastUpdatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.DepartmentLineItems.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.DepartmentLineItems.Where(x => x.LastUpdatedByAppUserId == appUser.Id))
{
item.LastUpdatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.Departments.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.Departments.Where(x => x.LastUpdatedByAppUserId == appUser.Id))
{
item.LastUpdatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.GoalChanges.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.GoalChanges.Where(x => x.AppUserId == appUser.Id))
{
item.PersonId = appUser.EmployeeId;
}
foreach (var item in _applicationDbContext.Goals.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.Goals.Where(x => x.LastUpdatedByAppUserId == appUser.Id))
{
item.LastUpdatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.Goals.Where(x => x.AppUserId == appUser.Id))
{
item.EmployeeId = appUser.EmployeeId;
}
foreach (var item in _applicationDbContext.PayoutLineItems.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.PayoutLineItems.Where(x => x.AppUserId == appUser.Id))
{
item.EmployeeId = appUser.EmployeeId;
}
foreach (var item in _applicationDbContext.RoleMappings.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.RoleMappings.Where(x => x.LastUpdatedByAppUserId == appUser.Id))
{
item.LastUpdatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.UserDepartmentHistories.Where(x => x.CreatedByAppUserId == appUser.Id)
)
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.UserPermissionHistories.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
foreach (var item in _applicationDbContext.UserPermissionHistories.Where(x => x.AppUserId == appUser.Id))
{
item.EmployeeId = int.Parse(appUser.EmployeeId);
}
foreach (var item in _applicationDbContext.UserPermissions.Where(x => x.CreatedByAppUserId == appUser.Id))
{
item.CreatedBy = appUser.AppUserFullNameInFromContextFormat();
}
await _applicationDbContext.SaveChangesAsync();
return true;
}
catch (Exception ex)
{
Log.Error(ex, ex.Message);
}
return false;
}
public async Task<bool> SyncIdsWithDb(AppUser appUser, bool limitScopeToAuditCreateAndUpdate = false)
{
try
{
Log.Information($"ApplicationDbIntegrity: SyncIdsWithDb for User {appUser.FullName} Started");
foreach (var item in _applicationDbContext.Activities.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.LastUpdatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.Activities.Where(x => x.LastUpdatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.LastUpdatedByAppUserId == Guid.Empty))
{
item.LastUpdatedByAppUserId = appUser.Id;
}
if (!limitScopeToAuditCreateAndUpdate)
{
foreach (var item in _applicationDbContext.Activities.Where(x => x.EmployeeEmail == appUser.AdEmail
&& x.EmployeeId == appUser.EmployeeId
&& x.AppUserId == Guid.Empty))
{
item.AppUserId = appUser.Id;
}
}
foreach (var item in _applicationDbContext.ActivityDetailUpdates.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.ActivityStateChanges.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.ActivityTransferActions.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.ActivityTransferActions.Where(x => x.LastUpdatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.LastUpdatedByAppUserId == Guid.Empty))
{
item.LastUpdatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.AppUsers.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.AppUsers.Where(x => x.LastUpdatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.LastUpdatedByAppUserId == Guid.Empty))
{
item.LastUpdatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.Commissions.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.Commissions.Where(x => x.LastUpdatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.LastUpdatedByAppUserId == Guid.Empty))
{
item.LastUpdatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.DeadActivities.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.DeadActivities.Where(x => x.LastUpdatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.LastUpdatedByAppUserId == Guid.Empty))
{
item.LastUpdatedByAppUserId = appUser.Id;
}
if (!limitScopeToAuditCreateAndUpdate)
{
foreach (var item in _applicationDbContext.DeadActivities.Where(x => x.EmployeeEmail == appUser.AdEmail
&& x.EmployeeId == appUser.EmployeeId
&& x.AppUserId == Guid.Empty))
{
item.AppUserId = appUser.Id;
}
}
foreach (var item in _applicationDbContext.DepartmentAssignments.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.DepartmentAssignments.Where(x => x.LastUpdatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.LastUpdatedByAppUserId == Guid.Empty))
{
item.LastUpdatedByAppUserId = appUser.Id;
}
if (!limitScopeToAuditCreateAndUpdate)
{
foreach (var item in _applicationDbContext.DepartmentAssignments.Where(x => x.Employee.AdEmail == appUser.AdEmail
&& x.Employee.EmployeeId == appUser.EmployeeId
&& x.AppUserId == Guid.Empty))
{
item.AppUserId = appUser.Id;
}
}
foreach (var item in _applicationDbContext.DepartmentLineItems.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.DepartmentLineItems.Where(x => x.LastUpdatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.LastUpdatedByAppUserId == Guid.Empty))
{
item.LastUpdatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.Departments.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.Departments.Where(x => x.LastUpdatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.LastUpdatedByAppUserId == Guid.Empty))
{
item.LastUpdatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.GoalChanges.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
if (!limitScopeToAuditCreateAndUpdate)
{
foreach (var item in _applicationDbContext.GoalChanges.Where(x => x.PersonId == appUser.EmployeeId
&& x.AppUserId == Guid.Empty))
{
item.AppUserId = appUser.Id;
}
}
foreach (var item in _applicationDbContext.Goals.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.Goals.Where(x => x.LastUpdatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.LastUpdatedByAppUserId == Guid.Empty))
{
item.LastUpdatedByAppUserId = appUser.Id;
}
if (!limitScopeToAuditCreateAndUpdate)
{
foreach (var item in _applicationDbContext.Goals.Where(x => x.EmployeeId == appUser.EmployeeId
&& x.AppUserId == Guid.Empty))
{
item.AppUserId = appUser.Id;
}
}
foreach (var item in _applicationDbContext.PayoutLineItems.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
if (!limitScopeToAuditCreateAndUpdate)
{
foreach (var item in _applicationDbContext.PayoutLineItems.Where(x => x.EmployeeId == appUser.EmployeeId
&& x.AppUserId == Guid.Empty))
{
item.AppUserId = appUser.Id;
}
}
foreach (var item in _applicationDbContext.RoleMappings.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.RoleMappings.Where(x => x.LastUpdatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.LastUpdatedByAppUserId == Guid.Empty))
{
item.LastUpdatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.UserDepartmentHistories.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
foreach (var item in _applicationDbContext.UserPermissionHistories.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
if (!limitScopeToAuditCreateAndUpdate)
{
foreach (var item in _applicationDbContext.UserPermissionHistories.Where(x => x.EmployeeId.ToString() == appUser.EmployeeId
&& x.AppUserId == Guid.Empty))
{
item.AppUserId = appUser.Id;
}
}
foreach (var item in _applicationDbContext.UserPermissions.Where(x => x.CreatedBy == appUser.AppUserFullNameInFromContextFormat()
&& x.CreatedByAppUserId == Guid.Empty))
{
item.CreatedByAppUserId = appUser.Id;
}
if (!limitScopeToAuditCreateAndUpdate)
{
foreach (var item in _applicationDbContext.UserPermissions.Where(x => x.AppUser.AdEmail == appUser.AdEmail
&& x.AppUser.EmployeeId == appUser.EmployeeId
&& x.AppUserId == Guid.Empty))
{
item.AppUserId = appUser.Id;
}
}
await _applicationDbContext.SaveChangesAsync();
return true;
}
catch (Exception ex)
{
Log.Error(ex, ex.Message);
}
return false;
}
}
@@ -0,0 +1,59 @@
using System;
using System.Linq;
using System.Security.Claims;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using Microsoft.AspNetCore.Http;
using Serilog;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
public class CurrentUserService : ICurrentUserService
{
protected readonly IHttpContextAccessor HttpContextAccessor;
public CurrentUserService(IHttpContextAccessor httpContextAccessor)
{
HttpContextAccessor = httpContextAccessor;
}
public ApplicationUser GetCurrentUser()
{
try
{
if (HttpContextAccessor != null && HttpContextAccessor.HttpContext != null)
{
var userClaimsPrincipal = HttpContextAccessor.HttpContext.User;
var parsedApplicationUser = new ApplicationUser
{
FirstName = userClaimsPrincipal.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.GivenName)?.Value,
LastName = userClaimsPrincipal.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Surname)?.Value,
Email = userClaimsPrincipal.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Upn)?.Value,
Roles = userClaimsPrincipal.Claims.Where((claim) => claim.Type == ClaimTypes.Role).Select((claim) => claim?.Value).ToArray(),
IsSystem = false,
};
Log.Debug($"ApplicationUser: {parsedApplicationUser.Email} successfully parsed from HttpContext");
return parsedApplicationUser;
}
Log.Debug("HttpContextAccessor or HttpContext are null, returning default System ApplicationUser");
return DefaultSystemApplicationUser();
}
catch (Exception ex)
{
Log.Error(ex, ex.Message);
return DefaultSystemApplicationUser();
}
}
private ApplicationUser DefaultSystemApplicationUser()
{
return new ApplicationUser()
{
FirstName = "Incentive",
LastName = "Manager",
Email = "",
Roles = new[] { Role.UNKNOWN_ROLE.Name },
IsSystem = true
};
}
}
@@ -0,0 +1,83 @@
using System;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
public class DateTimeService : IDateTime
{
public DateTime Now => DateTime.Now;
public DateTime UTCNow => DateTime.UtcNow;
public DateTime ConvertDnaUnspecifiedTimeToUtc(DateTime dateTime) {
var dnaAssumedTimeZone = TimeZoneConverter.TZConvert.GetTimeZoneInfo("America/Chicago");
return TimeZoneInfo.ConvertTime(dateTime, dnaAssumedTimeZone, TimeZoneInfo.Utc);
}
public DateTime? CSTWindowsNow
{
get
{
try
{
var centralTimeZone = TimeZoneConverter.TZConvert.GetTimeZoneInfo("Central Standard Time");
return TimeZoneInfo.ConvertTimeFromUtc(UTCNow, centralTimeZone);
}
catch (Exception)
{
return null;
}
}
}
public DateTime? CSTLinuxNow
{
get
{
try
{
var centralTimeZone = TimeZoneConverter.TZConvert.GetTimeZoneInfo("America/Chicago");
return TimeZoneInfo.ConvertTimeFromUtc(UTCNow, centralTimeZone);
}
catch (Exception)
{
return null;
}
}
}
public DateTime ConvertDateTimeFromCSTToUTCLinux(string dateTimeString)
{
var date = DateTime.Parse(dateTimeString);
return TimeZoneInfo.ConvertTime(date, TimeZoneConverter.TZConvert.GetTimeZoneInfo("America/Chicago"), TimeZoneInfo.Utc);
}
public DateTime ConvertDateTimeFromCSTToUTCWindows(string dateTimeString)
{
var date = DateTime.Parse(dateTimeString);
return TimeZoneInfo.ConvertTime(date, TimeZoneConverter.TZConvert.GetTimeZoneInfo("Central Standard Time"), TimeZoneInfo.Utc);
}
public DateTime getNextBonusPeriod(DateTime today)
{
var seedDate = new DateTime(2021, 10, 01);
while (seedDate.Date <= today.Date || PayPeriodInMonth(seedDate) != 2)
{
seedDate = seedDate.AddDays(14);
}
return seedDate;
}
private int PayPeriodInMonth(DateTime input)
{
var period = 1;
var previousPayDay = input.AddDays(-14);
if (previousPayDay.Month == input.Month)
{
period = 2;
}
previousPayDay = previousPayDay.AddDays(-14);
if (previousPayDay.Month == input.Month)
{
period = 3;
}
return period;
}
}
@@ -0,0 +1,32 @@
using System.Threading;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
public interface IApplicationDbContext
{
DbSet<Goal> Goals { get; set; }
DbSet<GoalChange> GoalChanges { get; set; }
DbSet<Activity> Activities { get; set; }
DbSet<ActivityDetail> ActivityDetails { get; set; }
DbSet<ActivityStateChange> ActivityStateChanges { get; set; }
DbSet<ActivityDetailUpdate> ActivityDetailUpdates { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<AppUser> AppUsers { get; set; }
public DbSet<UserDepartment> DepartmentAssignments { get; set; }
public DbSet<RoleMapping> RoleMappings { get; set; }
DbSet<Commission> Commissions { get; set; }
public DbSet<ProcessorHistoryRecord> ProcessorRunHistory { get; set; }
public DbSet<UserPermission> UserPermissions { get; set; }
public DbSet<PayoutLineItem> PayoutLineItems { get; set; }
public DbSet<UserAssignment> UserAssignments { get; set; }
public DbSet<ActivityTransferAction> ActivityTransferActions { get; set; }
public DbSet<DeadActivity> DeadActivities { get; set; }
public DbSet<DepartmentLineItem> DepartmentLineItems { get; set; }
public DbSet<UserDepartmentHistory> UserDepartmentHistories { get; set; }
public DbSet<UserPermissionHistory> UserPermissionHistories { get; set; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken());
public Task SeedRoleMappingData();
}
@@ -0,0 +1,12 @@
using System.Threading;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
public interface IApplicationDbIntegrityService
{
Task<bool> AppUserIdIntegrityMaintenanceSucceeded(CancellationToken cancellationToken);
Task<bool> SyncAppUserUpdate(AppUser appUser);
Task<bool> SyncIdsWithDb(AppUser appUser, bool limitScopeToAuditCreateAndUpdate = false);
}
@@ -0,0 +1,8 @@
using LCU.Library.Internal.IncentiveApiModels.Entities;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
public interface ICurrentUserService
{
ApplicationUser GetCurrentUser();
}
@@ -0,0 +1,14 @@
using System;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
public interface IDateTime
{
DateTime Now { get; }
DateTime UTCNow { get; }
DateTime? CSTLinuxNow { get; }
DateTime? CSTWindowsNow { get; }
DateTime ConvertDateTimeFromCSTToUTCWindows(string dateTimeString);
DateTime ConvertDateTimeFromCSTToUTCLinux(string dateTimeString);
DateTime getNextBonusPeriod(DateTime today);
}
@@ -0,0 +1,36 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class AccountingRepository : BaseRepository, IAccountingRepository
{
public AccountingRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<AccountingSummary> SaveAccountingSummaryAsync(AccountingSummary summary)
{
await _context.DepartmentLineItems.AddRangeAsync(summary.DepartmentPayouts);
return summary;
}
public async Task<AccountingSummary> GetAccountingSummaryAsync(DateTime payoutPeriod)
{
var rows = await _context.DepartmentLineItems.Where(x => x.PayoutMonth.Date == payoutPeriod.Date).ToListAsync();
if (rows != null && rows.Any())
{
var summary = new AccountingSummary(payoutPeriod);
summary.DepartmentPayouts = rows;
summary.Total = summary.DepartmentPayouts.Sum(x => x.PayoutTotal);
return summary;
}
return null;
}
}
@@ -0,0 +1,26 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class ActivityChangeRepository : BaseRepository, IActivityChangeRepository
{
public ActivityChangeRepository(ApplicationDbContext context) : base(context)
{
}
public async Task<ActivityStateChange> SaveActivityStateChange(ActivityStateChange stateChange)
{
await _context.ActivityStateChanges.AddAsync(stateChange);
return stateChange;
}
public async Task<List<ActivityStateChange>> GetActivityChangesByActivityId(int activityId)
{
return await _context.ActivityStateChanges.Where(x => x.ActivityId == activityId).ToListAsync();
}
}
@@ -0,0 +1,31 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class ActivityDetailUpdateRepository : BaseRepository, IActivityDetailUpdateRepository
{
public ActivityDetailUpdateRepository(ApplicationDbContext context) : base(context)
{
}
public async Task<ActivityDetail> GetActivityDetailById(int activityDetailId)
{
return await _context.ActivityDetails.FindAsync(activityDetailId);
}
public async Task<ActivityDetailUpdate> SaveActivityDetailUpdate(ActivityDetailUpdate activityDetailUpdate)
{
await _context.ActivityDetailUpdates.AddAsync(activityDetailUpdate);
return activityDetailUpdate;
}
public async Task<List<ActivityDetailUpdate>> GetActivityDetailUpdatesByActivityDetailId(int activityDetailId)
{
return await _context.ActivityDetailUpdates.Where(x => x.ActivityDetailId == activityDetailId).ToListAsync();
}
}
@@ -0,0 +1,566 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using LCU.API.Internal.Operations.IncentiveApiLib.Extensions;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using LCU.Library.Internal.IncentiveApiModels.Common;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class ActivityRepository : BaseRepository, IActivityRepository
{
public ActivityRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<int> SaveActivityAsync(Activity activity)
{
await _context.Activities.AddAsync(activity);
return activity.Id;
}
public async Task SaveActivityRangeAsync(List<Activity> activities)
{
await _context.Activities.AddRangeAsync(activities);
}
public void UpdateActivityRangeAsync(List<Activity> activities)
{
var existing = activities.Where(x => _context.Activities.Contains(x));
_context.Activities.UpdateRange(activities);
}
public async Task<IReadOnlyCollection<Activity>> GetActivitiesAsync()
{
return await _context.Activities
.Include(activity => activity.Detail)
.Include(activity => activity.MetaData)
.OrderBy(t => t.Id)
.ToListAsync();
}
public async Task<PagedResult<Activity>> GetActivitiesAsync(int page, int limit)
{
var results = new PagedResult<Activity>();
var skip = (page - 1) * limit;
var activities = _context.Activities
.Include(activity => activity.Detail)
.Include(activity => activity.MetaData)
.OrderByDescending(t => t.Created);
results.Total = activities.Count();
results.Items = await activities.Skip(skip).Take(limit).ToListAsync();
return results;
}
public async Task<IReadOnlyCollection<Activity>> FindUnmatchedReferrals()
{
var activities = _context.Activities.Include(activity => activity.Detail).Include(activity => activity.MetaData);
IQueryable<Activity> querySet = activities
.Where(x => x.Type == ActivityType.Referral
&& x.State == ActivityState.PendingReferral)
.OrderByDescending(t => t.LastUpdated);
return await querySet.ToListAsync();
}
public async Task<IReadOnlyCollection<Activity>> FindPendingEStatementsReferrals()
{
var activities = _context.Activities.Include(activity => activity.Detail).Include(activity => activity.MetaData);
IQueryable<Activity> querySet = activities
.Where(x => x.Type == ActivityType.Referral
&& x.State == ActivityState.PendingReferral
&& x.Product == Product.eStatement
&& string.IsNullOrEmpty(x.Detail.AccountNumber))
.OrderByDescending(t => t.LastUpdated);
return await querySet.ToListAsync();
}
public async Task<Activity> FindUnmatchedSaleForReferral(Activity referral)
{
var activities = _context.Activities
.Include(activity => activity.Detail)
.Include(activity => activity.MetaData);
var matchOnMetaData = string.IsNullOrEmpty(referral.Detail.SubjectOrgNbr) && string.IsNullOrEmpty(referral.Detail.SubjectPersonNbr);
var matchedActivities = matchOnMetaData
? await activities.Where(MetaDataMatchPredicate(referral)).ToListAsync()
: await activities.Where(PersonDataMatchPredicate(referral)).ToListAsync();
if (matchOnMetaData && matchedActivities.Any())
{
matchedActivities = matchedActivities.Where(x =>
ListsContainMatchingItem(
x.MetaData.Where(e => e.MetaDataType == MetaDataType.Email).Select(e => e.MetaData).ToList(),
referral.MetaData.Where(r => r.MetaDataType == MetaDataType.Email).Select(e => e.MetaData).ToList()
)
||
ListsContainMatchingItem(
x.MetaData.Where(e => e.MetaDataType == MetaDataType.Phone).Select(e => e.MetaData).ToList(),
referral.MetaData.Where(r => r.MetaDataType == MetaDataType.Phone).Select(e => e.MetaData).ToList()
)
)
.ToList();
}
var matchingSaleActivityIds = matchedActivities.Select(x => x.Id);
var activityIDsAssociatedToStateChange = _context.ActivityStateChanges
.Where(change => matchingSaleActivityIds.Contains(change.ActivityMatchId))
.Select(x => x.ActivityMatchId);
var activityIDsNotAssociatedToStateChange = matchingSaleActivityIds.Except(activityIDsAssociatedToStateChange);
return matchedActivities.Where(x => activityIDsNotAssociatedToStateChange.Contains(x.Id))
.OrderByDescending(t => t.LastUpdated)
.FirstOrDefault();
}
public EStatementDeliveryMethod FindDeliveryMethodForEStatement(Activity referral, List<EStatementDeliveryMethod> deliveryMethods)
{
var matchedMethods = new List<EStatementDeliveryMethod>();
var nullReferralOrgNumber = "0";
var matchableDeliveryMethods = deliveryMethods.Where(x => x.ActivityDateTime.Date >= referral.SourceCreated.Date).ToList();
matchedMethods.AddRange(matchableDeliveryMethods.Where(x => x.PersonNumber == referral.Detail.SubjectPersonNbr
|| x.OrganizationNumber == (referral.Detail.SubjectOrgNbr ?? nullReferralOrgNumber)
&& x.OrganizationNumber != nullReferralOrgNumber
&& referral.Detail.SubjectOrgNbr != nullReferralOrgNumber));
matchedMethods.AddRange(matchableDeliveryMethods.Where(x =>
ListsContainMatchingItem(
x.MetaData.Where(e => e.MetaDataType == MetaDataType.Email).Select(e => e.MetaData).ToList(),
referral.MetaData.Where(r => r.MetaDataType == MetaDataType.Email).Select(e => e.MetaData).ToList()
)
||
ListsContainMatchingItem(
x.MetaData.Where(e => e.MetaDataType == MetaDataType.Phone).Select(e => e.MetaData).ToList(),
referral.MetaData.Where(r => r.MetaDataType == MetaDataType.Phone).Select(e => e.MetaData).ToList()
)
)
.ToList());
var matchedMethod = matchedMethods.OrderByDescending(a => a.ActivityDateTime).FirstOrDefault();
if (matchedMethod != null)
{
deliveryMethods.Remove(matchedMethod);
}
return matchedMethod;
}
private static Expression<Func<Activity, bool>> MetaDataMatchPredicate(Activity referral)
{
return x => (x.Type == ActivityType.Sale || x.Type == ActivityType.Other)
&& x.Product == referral.Product
&& x.MetaData != null && referral.MetaData != null
&& x.State == ActivityState.Accepted
&& x.SourceCreated.Date >= referral.SourceCreated.Date;
}
private static bool ListsContainMatchingItem(IReadOnlyList<string> list1, IReadOnlyList<string> list2)
{
if ((list1?.Any() ?? false) && (list2?.Any() ?? false))
{
return list1.Any(x => list2.Any(t => string.Equals(t, x, StringComparison.CurrentCultureIgnoreCase)));
}
return false;
}
private static Expression<Func<Activity, bool>> PersonDataMatchPredicate(Activity referral)
{
return x => (x.Type == ActivityType.Sale || x.Type == ActivityType.Other)
&& x.Product == referral.Product
&& x.Detail.SubjectPersonNbr == referral.Detail.SubjectPersonNbr
&& x.Detail.SubjectOrgNbr == referral.Detail.SubjectOrgNbr
&& x.State == ActivityState.Accepted
&& x.SourceCreated.Date >= referral.SourceCreated.Date;
}
public async Task<Activity> FindDuplicateSaleAsync(Activity queryActivity)
{
if (queryActivity.Detail == null || queryActivity.Type != ActivityType.Sale)
{
return null;
}
var activities = _context.Activities
.Include(activity => activity.Detail)
.Include(activity => activity.MetaData);
IQueryable<Activity> querySet = activities
.Where(x => x.Id != queryActivity.Id
&& x.Product == queryActivity.Product
&& x.Type == queryActivity.Type
&& x.Detail.AccountNumber == queryActivity.Detail.AccountNumber
&& x.Detail.SubAccountNumber == queryActivity.Detail.SubAccountNumber
&& x.Detail.SubjectOrgNbr == queryActivity.Detail.SubjectOrgNbr
&& x.Detail.SubjectPersonNbr == queryActivity.Detail.SubjectPersonNbr
&& (
queryActivity.SourceId == null
|| x.SourceId == queryActivity.SourceId)
)
.OrderByDescending(t => t.LastUpdated);
return await querySet.FirstOrDefaultAsync();
}
public async Task<Activity> FindDuplicateReferralAsync(Activity queryActivity)
{
if (queryActivity.Detail == null || queryActivity.Type != ActivityType.Referral)
{
return null;
}
var activities = _context.Activities
.Include(activity => activity.Detail);
IQueryable<Activity> querySet = activities
.Where(x => x.Id != queryActivity.Id
&& x.Type == queryActivity.Type && x.Product == queryActivity.Product
&& x.Detail.SubjectPersonNbr != null && queryActivity.Detail.SubjectPersonNbr != null
&& x.Detail.SubjectOrgNbr != null && queryActivity.Detail.SubjectOrgNbr != null
&& x.Detail.SubjectPersonNbr == queryActivity.Detail.SubjectPersonNbr
&& x.Detail.SubjectOrgNbr == queryActivity.Detail.SubjectOrgNbr
)
.OrderByDescending(t => t.LastUpdated);
return await querySet.FirstOrDefaultAsync();
}
public async Task<Activity> FindActivityForStateUpdate(Activity queryActivity)
{
if (queryActivity.Detail == null)
{
return null;
}
var activities = _context.Activities
.Include(activity => activity.Detail)
.Include(activity => activity.MetaData);
IQueryable<Activity> querySet = activities
.Where(x => x.EmployeeEmail == queryActivity.EmployeeEmail
&& x.EmployeeId == queryActivity.EmployeeId
&& x.DepartmentId == queryActivity.DepartmentId
&& x.Product == queryActivity.Product
&& x.SourceCreated.Date == queryActivity.SourceCreated.Date
&& x.SourceSystem == queryActivity.SourceSystem
&& x.Type == queryActivity.Type
&& x.Detail.AccountNumber == queryActivity.Detail.AccountNumber
&& x.Detail.SubAccountNumber == queryActivity.Detail.SubAccountNumber
)
.OrderByDescending(t => t.LastUpdated);
var returnedItems = await querySet.ToListAsync();
Func<Activity, bool> activityStateCondition = x => x.State != queryActivity.State;
var returnItem = returnedItems.Count(activityStateCondition) > 1
? returnedItems.FirstOrDefault(activityStateCondition)
: returnedItems.FirstOrDefault();
return returnItem;
}
public async Task<Activity> FindActivityForDetailUpdate(Activity queryActivity)
{
if (queryActivity.Detail == null)
{
return null;
}
var returnedItems = await GetActivityForDetailUpdate(queryActivity);
if (returnedItems.Count == 0)
{
returnedItems = await GetActivityForDetailUpdate(queryActivity, false);
}
if (returnedItems.Count == 0)
{
return null;
}
Func<Activity, bool> activityStatePredicate = x => x.State == ActivityState.Accepted;
var returnItem = returnedItems.Count(activityStatePredicate) >= 1
? returnedItems.FirstOrDefault(activityStatePredicate)
: returnedItems.FirstOrDefault();
return returnItem;
}
private async Task<List<Activity>> GetActivityForDetailUpdate(Activity queryActivity, bool filterOnSubAccountNumber = true)
{
var activities = _context.Activities
.Include(activity => activity.Detail)
.Include(activity => activity.MetaData);
IQueryable<Activity> querySet = activities
.Where(x => x.EmployeeEmail == queryActivity.EmployeeEmail
&& x.EmployeeId == queryActivity.EmployeeId
&& x.DepartmentId == queryActivity.DepartmentId
&& x.Product == queryActivity.Product
&& x.SourceSystem == queryActivity.SourceSystem
&& x.Type == queryActivity.Type
&& x.Detail.AccountNumber == queryActivity.Detail.AccountNumber
)
.OrderByDescending(t => t.LastUpdated);
if (filterOnSubAccountNumber)
{
return await querySet.Where(x => x.Detail.SubAccountNumber == queryActivity.Detail.SubAccountNumber).ToListAsync();
}
return await querySet.Where(x => x.State == ActivityState.Accepted).ToListAsync();
}
public async Task<PagedResult<Activity>> GetPagedFilteredActivities(ActivityFilter filter)
{
var results = new PagedResult<Activity>();
var skip = (filter.Page - 1) * filter.Limit;
var activities = _context.Activities.Include(activity => activity.Detail).Include(activity => activity.MetaData);
IQueryable<Activity> querySet = activities;
if (filter.Product != null && filter.Product.Any())
{
var products = filter.Product;
querySet = querySet.Where(x => products.Contains(x.Product));
}
if (filter.Type != null && filter.Type.Any())
{
var types = filter.Type;
querySet = querySet.Where(x => types.Contains(x.Type));
}
if (filter.State != null && filter.State.Any())
{
var states = filter.State;
querySet = querySet.Where(x => states.Contains(x.State));
}
if (filter.DateLow != null)
{
querySet = querySet.Where(x => x.Accepted.Date >= filter.DateLow);
}
if (filter.DateHigh != null)
{
querySet = querySet.Where(x => x.Accepted.Date <= filter.DateHigh);
}
if (filter.DepartmentId != 0)
{
querySet = querySet.Where(x => x.DepartmentId == filter.DepartmentId);
}
if (!string.IsNullOrWhiteSpace(filter.EmployeeId))
{
querySet = querySet.Where(x => x.EmployeeId == filter.EmployeeId);
}
if (!string.IsNullOrWhiteSpace(filter.Query))
{
var query = filter.Query.ToLower().Trim();
querySet = querySet.Where(x =>
x.Detail.MemberName.ToLower().Contains(query)
|| x.Detail.AccountNumber.ToLower().Contains(query)
|| x.Detail.SubjectPersonNbr.ToLower().Contains(query)
|| x.Detail.SubjectOrgNbr.ToLower().Contains(query)
|| x.SourceId.ToLower() == query
|| query == x.Id.ToString());
}
querySet = SortQuerySet(querySet, filter);
results.Total = querySet.Count();
results.Items = await querySet.Skip(skip).Take(filter.Limit).ToListAsync();
return results;
}
public async Task<List<Activity>> GetAllActivitiesWithPayoutsForEmployee(string employeeId)
{
return await _context.Activities.Include(activity => activity.ActivityPayouts).Where(x => x.EmployeeId == employeeId).ToListAsync();
}
private IQueryable<Activity> SortQuerySet(IQueryable<Activity> querySet, ActivityFilter filter)
{
if (string.IsNullOrWhiteSpace(filter.SortBy))
{
return querySet
.OrderByDescending(t => t.Accepted);
}
if (filter.SortDescending.HasValue && filter.SortDescending.Value)
{
return (IQueryable<Activity>)querySet.OrderByDescending<Activity>(filter.SortBy);
}
return (IQueryable<Activity>)querySet.OrderBy<Activity>(filter.SortBy);
}
public async Task<Activity> GetActivityById(int activityId)
{
return await _context.Activities.FindAsync(activityId);
}
public async Task<ICollection<Activity>> FindEmployeeActivityByMonthRange(AppUser appUser, MonthRange monthRange)
{
return await _context.Activities
.Include(activity => activity.Detail)
.Include(activity => activity.MetaData)
.Where(x => x.Accepted.Date >= monthRange.StartTime.Date &&
x.Accepted.Date <= monthRange.EndTime.Date &&
appUser.EmployeeId == x.EmployeeId)
.ToListAsync();
}
public async Task<ICollection<Activity>> FindDepartmentActivityByMonthRange(int departmentId, MonthRange monthRange)
{
return await _context.Activities
.Include(activity => activity.Detail)
.Include(activity => activity.MetaData)
.Where(x => x.Accepted.Date >= monthRange.StartTime.Date &&
x.Accepted.Date <= monthRange.EndTime.Date &&
x.DepartmentId == departmentId)
.ToListAsync();
}
public async Task<Activity> GetActivityIncludingPayouts(int activityId)
{
return await _context.Activities
.Include(activity => activity.Detail)
.Include(activity => activity.MetaData)
.Include(activity => activity.ActivityPayouts)
.ThenInclude(payouts => payouts.PayoutLineItem)
.FirstOrDefaultAsync(x => x.Id == activityId);
}
public async Task<List<Activity>> GetActivitiesBySourceId(List<string> sourceIds)
{
return await _context.Activities.Where(x => sourceIds.Contains(x.SourceId)).ToListAsync();
}
public async Task<Activity> FindDuplicateReferralBySourceIdAsync(Activity queryActivity)
{
if (queryActivity.Detail == null || queryActivity.Type != ActivityType.Referral)
{
return null;
}
var activities = _context.Activities
.Include(activity => activity.Detail)
.Include(activity => activity.MetaData);
IQueryable<Activity> querySet = activities
.Where(x => x.Id != queryActivity.Id
&& x.Type == queryActivity.Type
&& x.Product == queryActivity.Product
&& x.SourceId == queryActivity.SourceId)
.OrderByDescending(t => t.LastUpdated);
return await querySet.FirstOrDefaultAsync();
}
public async Task<List<Activity>> FindById(
List<int> ids,
bool withDetail = true,
bool withTracking = true
)
{
if (!ids.Any())
{
return new List<Activity>();
}
var query = withTracking
? _context.Activities
: _context.Activities.AsNoTracking();
if (withDetail)
{
query = query.Include(activity => activity.Detail);
}
query = query.Where(activity => ids.Contains(activity.Id));
return await query.ToListAsync();
}
public async Task<List<Activity>> FindLatestBySourceId(
List<string> sourceIds,
bool withDetail = true,
bool withTracking = true
)
{
if (!sourceIds.Any())
{
return new List<Activity>();
}
var query = withTracking
? _context.Activities
: _context.Activities.AsNoTracking();
if (withDetail)
{
query = query.Include(activity => activity.Detail);
}
return (await query
.Where(activity => sourceIds.Contains(activity.SourceId))
.GroupBy(activity => activity.SourceId)
.Select(group => group.OrderBy(activity => activity.Created).FirstOrDefault())
.ToListAsync())
.Where(activity => activity != null)
.ToList();
}
public async Task<List<Activity>> FindGapInsuranceEligible(
MonthRange monthRange,
bool withTracking = true
)
{
var query = withTracking
? _context.Activities
: _context.Activities.AsNoTracking();
return await query
.Include(activity => activity.Detail)
.Where(activity =>
activity.Detail != null &&
activity.Detail.IsGapInsuranceEligible &&
activity.Accepted.Date >= monthRange.StartTime.Date &&
activity.Accepted.Date <= monthRange.EndTime.Date)
.ToListAsync();
}
public async Task<List<Activity>> GetFilteredActivities(
MonthRange monthRange,
Product product,
ActivityState activityState,
bool withTracking = true
)
{
var querySet = withTracking
? _context.Activities
: _context.Activities.AsNoTracking();
return await querySet
.Include(activity => activity.Detail)
.Where(
activity =>
activity.Accepted.Date >= monthRange.StartTime.Date &&
activity.Accepted.Date <= monthRange.EndTime.Date &&
activity.Product == product &&
activity.State == activityState
)
.ToListAsync();
}
}
@@ -0,0 +1,46 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class ActivityTransferActionRepository : BaseRepository, IActivityTransferActionRepository
{
public ActivityTransferActionRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<int> SaveTransferAsync(ActivityTransferAction activityTransferAction)
{
await _context.ActivityTransferActions.AddAsync(activityTransferAction);
return activityTransferAction.Id;
}
public async Task<ActivityTransferAction> GetTransferActionById(int id)
{
return await _context.ActivityTransferActions
.Include(x => x.RequestedActivity)
.FirstOrDefaultAsync(x => x.Id == id);
}
public async Task<ActivityTransferAction> GetRequestedTransferActionByActivityId(int requestedActivityId)
{
return await _context.ActivityTransferActions
.FirstOrDefaultAsync(x => x.RequestedActivityId == requestedActivityId
&& x.State == ActivityTransferState.Requested);
}
public async Task<IReadOnlyCollection<ActivityTransferAction>> GetActiveTransfersForStateAsync(
ActivityState state)
{
return await _context.ActivityTransferActions
.Include(x => x.RequestedActivity)
.Where(x => x.ActivityStateBeforeTransfer == state
&& x.State == ActivityTransferState.Requested)
.ToListAsync();
}
}
@@ -0,0 +1,13 @@
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public abstract class BaseRepository
{
protected readonly IApplicationDbContext _context;
protected BaseRepository(IApplicationDbContext context)
{
_context = context;
}
}
@@ -0,0 +1,42 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class CommissionRepository : BaseRepository, ICommissionRepository
{
public CommissionRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<Commission> FindExistingCommission(int id)
{
return await _context.Commissions.FindAsync(id);
}
public async Task<Commission> FindExistingCommission(Role role, Product product)
{
return await _context.Commissions.FirstOrDefaultAsync(x => x.Role == role &&
x.Product == product);
}
public async Task<IReadOnlyCollection<Commission>> GetCommissionsAsync()
{
return await _context.Commissions.ToListAsync();
}
public async Task SaveCommission(Commission commission)
{
await _context.Commissions.AddAsync(commission);
}
public async Task<IList<Commission>> FindProductCommissions(Role employeeRole)
{
return await _context.Commissions.AsNoTracking().Where(x => x.Role == employeeRole).ToListAsync();
}
}
@@ -0,0 +1,142 @@
using LCU.API.Internal.Operations.IncentiveApiLib.Extensions;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using LCU.Library.Internal.IncentiveApiModels.Common;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class DeadActivityRepository : BaseRepository, IDeadActivityRepository
{
public DeadActivityRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<DeadActivity> SaveDeadActivity(DeadActivity newDeadActivity)
{
await _context.DeadActivities.AddAsync(newDeadActivity);
return newDeadActivity;
}
public async Task<List<DeadActivity>> SaveDeadActivityRange(List<DeadActivity> newActivities)
{
await _context.DeadActivities.AddRangeAsync(newActivities);
return newActivities;
}
public async Task<List<DeadActivity>> GetDeadActivitiesBySourceIds(List<string> sourceIds)
{
return await _context.DeadActivities.Include(x => x.DeadDetail).Where(x => sourceIds.Contains(x.SourceId)).ToListAsync();
}
public async Task<List<DeadActivity>> GetAllDeadActivities()
{
return await _context.DeadActivities.Include(x => x.DeadDetail).ToListAsync();
}
public async Task<DeadActivity> GetDeadActivityById(int activityId)
{
return await _context.DeadActivities
.Include(x => x.DeadDetail)
.FirstOrDefaultAsync(x => x.Id == activityId);
}
public async Task<PagedResult<DeadActivity>> GetPagedDeadActivities(int page, int limit)
{
var results = new PagedResult<DeadActivity>();
var skip = (page - 1) * limit;
var deadActivities = _context.DeadActivities
.Include(activity => activity.DeadDetail)
.OrderByDescending(t => t.Created);
results.Total = deadActivities.Count();
results.Items = await deadActivities.Skip(skip).Take(limit).ToListAsync();
return results;
}
public async Task<PagedResult<DeadActivity>> GetFilteredDeadActivities(DeadActivityFilter filter)
{
var results = new PagedResult<DeadActivity>();
var skip = (filter.Page - 1) * filter.Limit;
var activities = _context
.DeadActivities.Include(activity => activity.DeadDetail)
.Where(activity => activity.LivingActivityId == null);
IQueryable<DeadActivity> querySet = activities;
if (filter.Product != null && filter.Product.Any())
{
var products = filter.Product;
querySet = querySet.Where(x => products.Contains((Product)x.Product));
}
if (filter.Type != null && filter.Type.Any())
{
var types = filter.Type;
querySet = querySet.Where(x => types.Contains((ActivityType)x.Type));
}
if (filter.State != null && filter.State.Any())
{
var states = filter.State;
querySet = querySet.Where(x => states.Contains((ActivityState)x.State));
}
if (filter.DateLow != null)
{
querySet = querySet.Where(x => x.Accepted >= filter.DateLow);
}
if (filter.DateHigh != null)
{
querySet = querySet.Where(x => x.Accepted <= filter.DateHigh);
}
if (filter.DepartmentId != 0)
{
querySet = querySet.Where(x => x.DepartmentId == filter.DepartmentId);
}
if (!string.IsNullOrWhiteSpace(filter.EmployeeId))
{
querySet = querySet.Where(x => x.EmployeeId == filter.EmployeeId);
}
if (!string.IsNullOrWhiteSpace(filter.Query))
{
var query = filter.Query.ToLower().Trim();
querySet = querySet.Where(x =>
(x.DeadDetail.MemberName ?? "").ToLower().Contains(query)
|| (x.DeadDetail.AccountNumber ?? "").ToLower().Contains(query)
|| (x.DeadDetail.SubAccountNumber ?? "").ToLower().Contains(query)
|| (x.DeadDetail.SubjectPersonNbr ?? "").ToLower().Contains(query)
|| (x.DeadDetail.SubjectOrgNbr ?? "").ToLower().Contains(query)
|| (x.SourceId ?? "").ToLower() == query
|| query == x.Id.ToString());
}
querySet = SortQuerySet(querySet, filter);
results.Total = querySet.Count();
results.Items = await querySet.Skip(skip).Take(filter.Limit).ToListAsync();
return results;
}
private IQueryable<DeadActivity> SortQuerySet(IQueryable<DeadActivity> querySet, ActivityFilter filter)
{
if (string.IsNullOrWhiteSpace(filter.SortBy))
{
return querySet
.OrderByDescending(t => t.Accepted);
}
if (filter.SortDescending.HasValue && filter.SortDescending.Value)
{
return (IQueryable<DeadActivity>)querySet.OrderByDescending<DeadActivity>(filter.SortBy);
}
return (IQueryable<DeadActivity>)querySet.OrderBy<DeadActivity>(filter.SortBy);
}
}
@@ -0,0 +1,173 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using Microsoft.EntityFrameworkCore;
using Serilog;
using LCU.Library.Internal.IncentiveApiModels.Common;
using LCU.Library.Internal.IncentiveApiModels.Results;
using LCU.Library.Internal.IncentiveApiModels.Requests;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class DepartmentRepository : BaseRepository, IDepartmentRepository
{
private const string BranchStr = "branch";
public DepartmentRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<IReadOnlyCollection<Department>> GetAllDepartmentsAsync()
{
return await _context.Departments.OrderBy(x => x.DepartmentName).ToListAsync();
}
public async Task<Department> FindDepartmentByIdAsync(int id)
{
return await _context.Departments.FindAsync(id);
}
public async Task<Department> SaveDepartmentAsync(Department department)
{
await _context.Departments.AddAsync(department);
return department;
}
public async Task<Department> FindOrCreateDepartment(ActiveEmployeeResult employee)
{
var departmentName = DetermineDepartmentName(employee.OrgUnit);
var orgCode = employee.OrgCode.ToLower();
var businessLine = BusinessLine.TryLookup(employee.OrgUnit);
var department = await _context.Departments.FirstOrDefaultAsync(x =>
x.DayForceGlCode.ToLower() == orgCode || x.DepartmentName.ToLower() == departmentName.ToLower());
if (department == null)
{
department = new Department()
{
BusinessLineCode = businessLine.Code,
State = DepartmentState.Active,
DepartmentName = departmentName,
DayforceDepartmentName = employee.OrgUnit,
DayForceGlCode = employee.OrgCode,
DnaOrgNbr = employee.GetDnaOrgCode()
};
await SaveDepartmentAsync(department);
}
department.DepartmentName = departmentName;
return department;
}
public static string DetermineDepartmentName(string employeeOrgUnit)
{
if (string.IsNullOrWhiteSpace(employeeOrgUnit))
{
return null;
}
if (employeeOrgUnit.Contains("-"))
{
var unitNames = employeeOrgUnit.Split("-");
var leftHalf = unitNames.First().Trim();
var rightHalf = unitNames.ElementAt(1).Trim();
if (string.Equals(rightHalf, BranchStr, StringComparison.CurrentCultureIgnoreCase))
{
return leftHalf;
}
return rightHalf;
}
return employeeOrgUnit.Trim();
}
public async Task<List<AppUser>> FindDepartmentAssignments(DepartmentPersonnelSearchRequest searchRequest)
{
var userDepartments = await _context.DepartmentAssignments
.Include(x => x.Employee)
.ThenInclude(x => x.AdditionalPermissions)
.Where(x => x.DepartmentId == searchRequest.DepartmentId)
.ToListAsync();
var range = new MonthRange(searchRequest.Year, searchRequest.Month);
var usersInRange = userDepartments
.Where(x =>
x.StartDate.Date <= range.EndTime.Date &&
(x.EndDate == null || x.EndDate.Value.Date >= range.StartTime.Date));
var users = usersInRange.Where(x => searchRequest.IncludeAllPersonnel ||
x.Role.Permissions.Any(p =>
p == Permission.HaveSalesGoals) ||
x.Employee.AdditionalPermissions.Any(p =>
p.Permission == Permission.HaveSalesGoals));
return users.Select(x => x.Employee).ToList();
}
public async Task<Department> FindUserHomeDepartment(AppUser appUser)
{
try
{
var userDepartment = await _context.DepartmentAssignments.Include(x => x.Department)
.Where(x => x.IsHome == true && x.EndDate == null
&& x.Employee.EmployeeId.Equals(appUser.EmployeeId)).SingleOrDefaultAsync();
return userDepartment?.Department;
}
catch (Exception ex)
{
Log.Error(ex,
$"Error Finding User Home Department. User with EmployeeId {appUser.EmployeeId} may have no or multiple home assignments.");
return null;
}
}
public async Task<Department> FindDepartmentByBranchName(string name)
{
return await _context.Departments.SingleOrDefaultAsync(x => x.DepartmentName.ToLower() == name.ToLower());
}
public async Task<Department> GetDepartmentByDayforceGlCode(int glCode)
{
return await _context.Departments.AsNoTracking().FirstOrDefaultAsync(x => x.DayForceGlCode == glCode.ToString());
}
public async Task<IReadOnlyCollection<Department>> FindDepartmentsByRegionAsync(Region region)
{
return await _context.Departments
.Where(x => x.RegionCode == region.Code)
.OrderBy(x => x.DepartmentName)
.ToListAsync();
}
public async Task<IReadOnlyCollection<Department>> FindDepartmentsByBusinessLineAsync(BusinessLine businessLine)
{
return await _context.Departments
.Where(x => x.BusinessLineCode == businessLine.Code)
.OrderBy(x => x.DepartmentName)
.ToListAsync();
}
public async Task<IReadOnlyCollection<UserDepartment>> FindCurrentDepartmentAssignments(int departmentId)
{
return await FindDepartmentAssignmentsForRange(departmentId, new MonthRange());
}
public async Task<IReadOnlyCollection<UserDepartment>> FindDepartmentAssignmentsForRange(int departmentId,
MonthRange monthRange)
{
return await _context.DepartmentAssignments
.AsNoTracking()
.Include(assignment => assignment.Employee)
.Where(assignment => assignment.DepartmentId == departmentId &&
assignment.StartDate.Date <= monthRange.EndTime.Date &&
(assignment.EndDate == null ||
assignment.EndDate.Value.Date >= monthRange.StartTime.Date))
.ToListAsync();
}
}
@@ -0,0 +1,28 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class GoalChangeRepository : BaseRepository, IGoalChangeRepository
{
public GoalChangeRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<int> SaveGoalChangeAsync(GoalChange goalChange)
{
await _context.GoalChanges.AddAsync(goalChange);
return goalChange.Id;
}
public async Task<IReadOnlyCollection<GoalChange>> GetGoalChangesAsync()
{
return await _context.GoalChanges
.OrderBy(t => t.Id)
.ToListAsync();
}
}
@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using Microsoft.EntityFrameworkCore;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using LCU.Library.Internal.IncentiveApiModels.Common;
using LCU.Library.Internal.IncentiveApiModels.Requests;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class GoalRepository : BaseRepository, IGoalRepository
{
public GoalRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<int> SaveGoalAsync(Goal goalChange)
{
await _context.Goals.AddAsync(goalChange);
return goalChange.Id;
}
public async Task<IReadOnlyCollection<Goal>> GetGoalsAsync(GoalSearchRequest goalSearchRequest)
{
var result = _context.Goals.AsQueryable();
if (goalSearchRequest != null)
{
if (goalSearchRequest.departmentId.HasValue)
{
result = result.Where(x => x.DepartmentId == goalSearchRequest.departmentId);
}
if (goalSearchRequest.DateRange != null && goalSearchRequest.DateRange.ValidFromRange)
{
var fromDate = goalSearchRequest.DateRange.StartTime;
result = result.Where(x => x.StartDate.Date >= fromDate.Date);
}
if (goalSearchRequest.DateRange != null && goalSearchRequest.DateRange.ValidToRange)
{
var toDate = goalSearchRequest.DateRange.EndTime;
result = result.Where(x => x.EndDate.Date <= toDate.Date);
}
if (goalSearchRequest.IncludePersonnel)
{
result = result.Where(x => x.EmployeeId != null);
}
else
{
result = result.Where(x => x.EmployeeId == null);
}
}
return await result.OrderBy(t => t.Id).ToListAsync();
}
public async Task<Goal> FindExistingGoal(GoalChange goalChange)
{
return await _context.Goals.FirstOrDefaultAsync(x => x.Product == goalChange.Product &&
x.StartDate.Date == goalChange.StartDate.Date &&
x.EndDate.Date == goalChange.EndDate.Date &&
x.DepartmentId == goalChange.DepartmentId &&
x.EmployeeId == goalChange.PersonId);
}
public async Task<ICollection<Goal>> FindDepartmentGoals(int departmentId, DateTime start, DateTime end)
{
return await _context.Goals.Where(x => x.StartDate.Date >= start.Date &&
x.EndDate.Date <= end.Date &&
x.EmployeeId == null &&
x.DepartmentId == departmentId).ToListAsync();
}
public async Task<ICollection<Goal>> FindAnnualDepartmentGoals(int departmentId, int year)
{
return await _context.Goals.Where(x => x.StartDate.Year == year &&
x.EndDate.Year == year &&
x.EmployeeId == null &&
x.DepartmentId == departmentId).ToListAsync();
}
public async Task<ICollection<Goal>> FindPersonnelGoals(int departmentId, List<AppUser> users, DateTime start,
DateTime end)
{
var employeeIds = users.Select(user => user.EmployeeId).ToList();
return await _context.Goals.Where(x => x.StartDate.Date == start.Date &&
x.EndDate.Date == end.Date &&
x.DepartmentId == departmentId &&
employeeIds.Contains(x.EmployeeId)).ToListAsync();
}
public async Task<ICollection<Goal>> FindMonthlyPersonnelGoals(int departmentId, List<AppUser> users, int year,
int month)
{
var employeeIds = users.Select(user => user.EmployeeId).ToList();
return await _context.Goals.Where(x => x.StartDate.Year == year && x.StartDate.Month == month &&
x.EndDate.Year == year && x.EndDate.Month == month &&
x.DepartmentId == departmentId &&
employeeIds.Contains(x.EmployeeId)).ToListAsync();
}
public async Task<ICollection<Goal>> FindPersonnelGoalsByMonthRange(int departmentId, List<AppUser> users, MonthRange monthRange)
{
var employeeIds = users.Select(user => user.EmployeeId).ToList();
return await _context.Goals.AsNoTracking().Where(x => x.StartDate.Date >= monthRange.StartTime.Date &&
x.EndDate.Date <= monthRange.EndTime.Date &&
x.DepartmentId == departmentId &&
employeeIds.Contains(x.EmployeeId)).ToListAsync();
}
public async Task<ICollection<Goal>> FindPersonnelGoalsByMonthRange(int departmentId, List<string> employeeIds, MonthRange monthRange)
{
return await _context.Goals.Where(x => x.StartDate.Date >= monthRange.StartTime.Date &&
x.EndDate.Date <= monthRange.EndTime.Date &&
x.DepartmentId == departmentId &&
employeeIds.Contains(x.EmployeeId)).ToListAsync();
}
public async Task<ICollection<Goal>> FindDepartmentGoalsByMonthRange(int departmentId, MonthRange monthRange)
{
return await _context.Goals.AsNoTracking().Where(x => x.StartDate.Date >= monthRange.StartTime.Date &&
x.EndDate.Date <= monthRange.EndTime.Date &&
x.EmployeeId == null &&
x.DepartmentId == departmentId).ToListAsync();
}
}
@@ -0,0 +1,11 @@
using System;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IAccountingRepository
{
Task<AccountingSummary> SaveAccountingSummaryAsync(AccountingSummary summary);
Task<AccountingSummary> GetAccountingSummaryAsync(DateTime payoutPeriod);
}
@@ -0,0 +1,11 @@
using LCU.Library.Internal.IncentiveApiModels.Entities;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IActivityChangeRepository
{
public Task<ActivityStateChange> SaveActivityStateChange(ActivityStateChange stateChange);
public Task<List<ActivityStateChange>> GetActivityChangesByActivityId(int activityId);
}
@@ -0,0 +1,12 @@
using LCU.Library.Internal.IncentiveApiModels.Entities;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IActivityDetailUpdateRepository
{
Task<ActivityDetailUpdate> SaveActivityDetailUpdate(ActivityDetailUpdate activityDetailUpdate);
Task<List<ActivityDetailUpdate>> GetActivityDetailUpdatesByActivityDetailId(int activityDetailId);
Task<ActivityDetail> GetActivityDetailById(int activityDetailId);
}
@@ -0,0 +1,36 @@
using LCU.Library.Internal.IncentiveApiModels.Common;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IActivityRepository
{
Task<int> SaveActivityAsync(Activity activity);
Task SaveActivityRangeAsync(List<Activity> activities);
Task<IReadOnlyCollection<Activity>> GetActivitiesAsync();
Task<PagedResult<Activity>> GetActivitiesAsync(int page, int limit);
Task<PagedResult<Activity>> GetPagedFilteredActivities(ActivityFilter filter);
Task<Activity> GetActivityById(int activityId);
Task<ICollection<Activity>> FindEmployeeActivityByMonthRange(AppUser appUser, MonthRange monthRange);
Task<ICollection<Activity>> FindDepartmentActivityByMonthRange(int departmentId, MonthRange monthRange);
Task<Activity> GetActivityIncludingPayouts(int activityId);
Task<IReadOnlyCollection<Activity>> FindUnmatchedReferrals();
Task<IReadOnlyCollection<Activity>> FindPendingEStatementsReferrals();
Task<Activity> FindUnmatchedSaleForReferral(Activity referral);
EStatementDeliveryMethod FindDeliveryMethodForEStatement(Activity referral, List<EStatementDeliveryMethod> eStatementActivities);
Task<Activity> FindDuplicateSaleAsync(Activity activity);
Task<Activity> FindDuplicateReferralAsync(Activity activity);
Task<Activity> FindActivityForStateUpdate(Activity activity);
Task<Activity> FindActivityForDetailUpdate(Activity activity);
public void UpdateActivityRangeAsync(List<Activity> activities);
Task<List<Activity>> GetActivitiesBySourceId(List<string> sourceId);
Task<List<Activity>> GetAllActivitiesWithPayoutsForEmployee(string employeeId);
Task<Activity> FindDuplicateReferralBySourceIdAsync(Activity activity);
Task<List<Activity>> FindById(List<int> ids, bool withDetail = true, bool withTracking = true);
Task<List<Activity>> FindLatestBySourceId(List<string> sourceIds, bool withDetail = true, bool withTracking = true);
Task<List<Activity>> FindGapInsuranceEligible(MonthRange monthRange, bool withTracking = true);
Task<List<Activity>> GetFilteredActivities(MonthRange monthRange, Product product, ActivityState activityState, bool withTracking = true);
}
@@ -0,0 +1,14 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IActivityTransferActionRepository
{
Task<int> SaveTransferAsync(ActivityTransferAction activityTransferAction);
Task<ActivityTransferAction> GetTransferActionById(int id);
Task<ActivityTransferAction> GetRequestedTransferActionByActivityId(int requestedActivityId);
Task<IReadOnlyCollection<ActivityTransferAction>> GetActiveTransfersForStateAsync(ActivityState state);
}
@@ -0,0 +1,15 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface ICommissionRepository
{
Task<Commission> FindExistingCommission(int id);
Task<Commission> FindExistingCommission(Role role, Product product);
Task<IReadOnlyCollection<Commission>> GetCommissionsAsync();
Task SaveCommission(Commission commission);
Task<IList<Commission>> FindProductCommissions(Role employeeRole);
}
@@ -0,0 +1,18 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Common;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IDeadActivityRepository
{
public Task<DeadActivity> SaveDeadActivity(DeadActivity newActivity);
public Task<List<DeadActivity>> SaveDeadActivityRange(List<DeadActivity> newActivities);
public Task<List<DeadActivity>> GetAllDeadActivities();
public Task<DeadActivity> GetDeadActivityById(int activityId);
public Task<PagedResult<DeadActivity>> GetPagedDeadActivities(int page, int limit);
public Task<List<DeadActivity>> GetDeadActivitiesBySourceIds(List<string> sourceIds);
public Task<PagedResult<DeadActivity>> GetFilteredDeadActivities(DeadActivityFilter filter);
}
@@ -0,0 +1,24 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Common;
using LCU.Library.Internal.IncentiveApiModels.Results;
using LCU.Library.Internal.IncentiveApiModels.Requests;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IDepartmentRepository
{
Task<IReadOnlyCollection<Department>> GetAllDepartmentsAsync();
Task<Department> FindDepartmentByIdAsync(int id);
Task<Department> SaveDepartmentAsync(Department department);
Task<Department> FindOrCreateDepartment(ActiveEmployeeResult employee);
Task<List<AppUser>> FindDepartmentAssignments(DepartmentPersonnelSearchRequest searchRequest);
Task<Department> FindUserHomeDepartment(AppUser appUser);
Task<Department> FindDepartmentByBranchName(string name);
Task<IReadOnlyCollection<Department>> FindDepartmentsByRegionAsync(Region region);
Task<IReadOnlyCollection<UserDepartment>> FindCurrentDepartmentAssignments(int departmentId);
Task<Department> GetDepartmentByDayforceGlCode(int glCode);
Task<IReadOnlyCollection<UserDepartment>> FindDepartmentAssignmentsForRange(int departmentId, MonthRange monthRange);
Task<IReadOnlyCollection<Department>> FindDepartmentsByBusinessLineAsync(BusinessLine businessLine);
}
@@ -0,0 +1,11 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IGoalChangeRepository
{
Task<int> SaveGoalChangeAsync(GoalChange goalChange);
Task<IReadOnlyCollection<GoalChange>> GetGoalChangesAsync();
}
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Common;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Requests;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IGoalRepository
{
Task<int> SaveGoalAsync(Goal goalChange);
Task<IReadOnlyCollection<Goal>> GetGoalsAsync(GoalSearchRequest goalSearchRequest);
Task<Goal> FindExistingGoal(GoalChange goalChange);
Task<ICollection<Goal>> FindDepartmentGoals(int departmentId, DateTime start, DateTime end);
Task<ICollection<Goal>> FindAnnualDepartmentGoals(int departmentId, int year);
Task<ICollection<Goal>> FindPersonnelGoals(int departmentId, List<AppUser> users, DateTime start, DateTime end);
Task<ICollection<Goal>> FindMonthlyPersonnelGoals(int departmentId, List<AppUser> users, int year, int month);
Task<ICollection<Goal>> FindPersonnelGoalsByMonthRange(int departmentId, List<AppUser> users, MonthRange monthRange);
Task<ICollection<Goal>> FindPersonnelGoalsByMonthRange(int departmentId, List<string> employeeIds, MonthRange monthRange);
Task<ICollection<Goal>> FindDepartmentGoalsByMonthRange(int departmentId, MonthRange monthRange);
}
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IPayoutRepository
{
Task<int> SavePayoutLineItemAsync(PayoutLineItem lineItem);
Task SavePayoutLineItemRangeAsync(IReadOnlyCollection<PayoutLineItem> lineItems);
Task<IReadOnlyCollection<PayoutLineItem>> GetPayoutLineItemsForPeriodAsync(DateTime forPeriod);
Task<PayoutLineItem> GetPayoutLineItemById(int payoutId);
Task<IReadOnlyCollection<PayoutLineItem>> GetEmployeePayoutsForPeriod(AppUser appUser, DateTime forPeriod);
}
@@ -0,0 +1,13 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IProcessorHistoryRepository
{
public Task<Process> SaveProcessorRunHistory(ProcessorHistoryRecord newHistoryRecord);
public Task<ProcessorHistoryRecord> GetProcessorRunHistory(Process process);
public Task<List<ProcessorHistoryRecord>> GetAllProcessorRunHistory();
}
@@ -0,0 +1,16 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IRoleMappingRepository
{
Task<ICollection<RoleMapping>> GetAllRoleMappingsAsync();
Task<RoleMapping> GetRoleMappingByIdAsync(int id);
Task<int> UpdateRoleMapping(RoleMapping roleMapping);
Task<int> SaveRoleMappingAsync(RoleMapping roleMapping);
Task SaveRoleMappingRangeAsync(IEnumerable<RoleMapping> newRoleMappings);
Task SaveNewRoleMappingRangeAsync(IEnumerable<RoleMapping> newRoleMappings);
Role FindMatchingRoleFromBusinessRole(string queryRole);
}
@@ -0,0 +1,8 @@
using System.Threading.Tasks;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IUnitOfWork
{
Task CompleteAsync();
}
@@ -0,0 +1,13 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IUserAssignmentRepository
{
Task<ICollection<UserAssignment>> GetAllUserAssignmentsAsync();
Task<UserAssignment> FindExistingAssignmentAsync(AssignmentType assignmentType, string key);
Task<UserAssignment> IsUserAssigned(AssignmentType assignmentType, AppUser appUser);
}
@@ -0,0 +1,12 @@
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Requests;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IUserDepartmentHistoryRepository
{
Task<List<UserDepartmentHistory>> SaveUserDepartmentUpdate(UserDepartment currentUserDepartment, DepartmentUpdateRequest departmentUpdateRequest);
Task<List<UserPermissionHistory>> GetUserDepartmentHistory(int employeeId);
}
@@ -0,0 +1,12 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IUserPermissionHistoryRepository
{
Task<List<UserPermissionHistory>> SaveUserPermissionsInsertion(IEnumerable<UserPermission> newPermissions);
Task<List<UserPermissionHistory>> SaveUserPermissionsDeletion(IEnumerable<UserPermission> newPermissions);
Task<List<UserPermissionHistory>> GetUserPermissionHistory(int employeeId);
}
@@ -0,0 +1,25 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Common;
using LCU.Library.Internal.IncentiveApiModels.Requests;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public interface IUserRepository
{
Task<ICollection<AppUser>> GetAllUsersAsync();
Task<ICollection<AppUser>> GetAllUsersToPayoutAsync(MonthRange range);
Task<AppUser> FindUserByEmployeeIdAsync(string employeeId);
Task<AppUser> FindUserByAdEmailAsync(string adEmail);
Task<AppUser> FindActiveUserByEmployeeIdAsync(string employeeId);
Task<AppUser> FindActiveUserByAdEmailAsync(string adEmail);
Task<AppUser> FindUserAsync(string employeeId, string adEmail);
Task<ICollection<AppUser>> FindUsersByHomeDepartmentsAsync(List<string> homeDepartments);
Task<ICollection<AppUser>> FindUsersByBaseRolesAsync(List<string> baseRoles);
Task<AppUser> SaveUserAsync(AppUser newAppUser);
Task<ICollection<AppUser>> SaveUserRangeAsync(List<AppUser> newUsers);
Task<ICollection<AppUser>> SearchUsersAsync(UserSearchRequest userSearchRequest);
Task<IReadOnlyCollection<UserSummary>> GetAllUserSummariesAsync();
IReadOnlyCollection<UserSummary> GetTerminatedUsersAsync(MonthRange monthRange);
}
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class PayoutRepository : BaseRepository, IPayoutRepository
{
public PayoutRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<int> SavePayoutLineItemAsync(PayoutLineItem lineItem)
{
await _context.PayoutLineItems.AddAsync(lineItem);
return lineItem.Id;
}
public async Task SavePayoutLineItemRangeAsync(IReadOnlyCollection<PayoutLineItem> lineItems)
{
await _context.PayoutLineItems.AddRangeAsync(lineItems);
}
public async Task<IReadOnlyCollection<PayoutLineItem>> GetPayoutLineItemsForPeriodAsync(DateTime forPeriod)
{
var checkDate = new DateTime(forPeriod.Year, forPeriod.Month, 1);
return await _context.PayoutLineItems
.Where(p => p.ActivityPeriod.Date == checkDate.Date)
.OrderBy(t => t.Id)
.ToListAsync();
}
public async Task<PayoutLineItem> GetPayoutLineItemById(int payoutId)
{
return await _context.PayoutLineItems.FindAsync(payoutId);
}
public async Task<IReadOnlyCollection<PayoutLineItem>> GetEmployeePayoutsForPeriod(AppUser appUser, DateTime forPeriod)
{
var checkDate = new DateTime(forPeriod.Year, forPeriod.Month, 1);
return await _context.PayoutLineItems.AsNoTracking()
.Include(x => x.ActivityPayouts).ThenInclude(y => y.Activity)
.Where(p => p.ActivityPeriod.Date == checkDate.Date &&
p.EmployeeId == appUser.EmployeeId)
.OrderBy(t => t.Id)
.ToListAsync();
}
}
@@ -0,0 +1,62 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using Microsoft.EntityFrameworkCore;
using Serilog;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class ProcessorHistoryRepository : BaseRepository, IProcessorHistoryRepository
{
public ProcessorHistoryRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<Process> SaveProcessorRunHistory(ProcessorHistoryRecord newHistoryRecord)
{
var existingProcess = await _context.ProcessorRunHistory.FindAsync(newHistoryRecord.Process);
if (existingProcess == null)
{
await _context.ProcessorRunHistory.AddAsync(newHistoryRecord);
return newHistoryRecord.Process;
}
if (newHistoryRecord.LastSuccessfulRunTime < existingProcess.LastSuccessfulRunTime)
{
Log.Warning(
$"ProcessorHistoryRepository Saved over a record with older data." +
$"Old LastSuccess {existingProcess.LastSuccessfulRunTime} New LastSuccess: {newHistoryRecord.LastSuccessfulRunTime}");
}
if (newHistoryRecord.LastProcessedRecordTimestamp < existingProcess.LastProcessedRecordTimestamp)
{
Log.Warning(
$"ProcessorHistoryRepository Saved over a record with older data." +
$"Old LastProcessed {existingProcess.LastProcessedRecordTimestamp} New LastProcessed: {newHistoryRecord.LastProcessedRecordTimestamp}");
}
if (newHistoryRecord.LastProcessedRecordId < existingProcess.LastProcessedRecordId)
{
Log.Warning(
$"ProcessorHistoryRepository Saved over a record with older data." +
$"Old ID {existingProcess.LastProcessedRecordId} New ID: {newHistoryRecord.LastProcessedRecordId}");
}
existingProcess.LastProcessedRecordId = newHistoryRecord.LastProcessedRecordId;
existingProcess.LastProcessedRecordTimestamp = newHistoryRecord.LastProcessedRecordTimestamp;
existingProcess.LastSuccessfulRunTime = newHistoryRecord.LastSuccessfulRunTime;
return existingProcess.Process;
}
public async Task<ProcessorHistoryRecord> GetProcessorRunHistory(Process process)
{
return await _context.ProcessorRunHistory.FindAsync(process);
}
public async Task<List<ProcessorHistoryRecord>> GetAllProcessorRunHistory()
{
return await _context.ProcessorRunHistory.ToListAsync();
}
}
@@ -0,0 +1,65 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class RoleMappingRepository : BaseRepository, IRoleMappingRepository
{
public RoleMappingRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<ICollection<RoleMapping>> GetAllRoleMappingsAsync()
{
return await _context.RoleMappings.OrderBy(x => x.BusinessRole).ToListAsync();
}
public async Task<RoleMapping> GetRoleMappingByIdAsync(int id)
{
return await _context.RoleMappings.FirstOrDefaultAsync(x => x.Id == id);
}
public async Task<int> UpdateRoleMapping(RoleMapping roleMapping)
{
_context.RoleMappings.Update(roleMapping);
return roleMapping.Id;
}
public async Task<int> SaveRoleMappingAsync(RoleMapping roleMapping)
{
await _context.RoleMappings.AddAsync(roleMapping);
return roleMapping.Id;
}
public async Task SaveRoleMappingRangeAsync(IEnumerable<RoleMapping> roleMappings)
{
await _context.RoleMappings.AddRangeAsync(roleMappings);
}
public async Task SaveNewRoleMappingRangeAsync(IEnumerable<RoleMapping> roleMappings)
{
await _context.RoleMappings.AddRangeAsync(roleMappings);
}
public Role FindMatchingRoleFromBusinessRole(string queryRole)
{
if (string.IsNullOrWhiteSpace(queryRole))
{
return Role.MISSING_ROLE;
}
var returnRole = _context.RoleMappings.Where(x => x.BusinessRole.ToUpper() == queryRole.ToUpper()).FirstOrDefault()
?.ApplicationRole;
if (returnRole == null)
{
returnRole = Role.MISSING_ROLE;
}
return returnRole;
}
}
@@ -0,0 +1,19 @@
using System.Threading.Tasks;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class UnitOfWork : IUnitOfWork
{
private readonly ApplicationDbContext _context;
public UnitOfWork(ApplicationDbContext context)
{
_context = context;
}
public async Task CompleteAsync()
{
await _context.SaveChangesAsync();
}
}
@@ -0,0 +1,35 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class UserAssignmentRepository : BaseRepository, IUserAssignmentRepository
{
public UserAssignmentRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<ICollection<UserAssignment>> GetAllUserAssignmentsAsync()
{
return await _context.UserAssignments.Include(x => x.AppUser).ToListAsync();
}
public async Task<UserAssignment> FindExistingAssignmentAsync(AssignmentType assignmentType, string key)
{
return await _context.UserAssignments
.Include(x => x.AppUser)
.FirstOrDefaultAsync(x => x.Type == assignmentType && x.Key == key);
}
public async Task<UserAssignment> IsUserAssigned(AssignmentType assignmentType, AppUser appUser)
{
return await _context.UserAssignments
.Include(x => x.AppUser)
.FirstOrDefaultAsync(x => x.Type == assignmentType
&& x.AppUser.EmployeeId == appUser.EmployeeId);
}
}
@@ -0,0 +1,63 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Requests;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class UserDepartmentHistoryRepository : BaseRepository, IUserDepartmentHistoryRepository
{
public UserDepartmentHistoryRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<List<UserDepartmentHistory>> SaveUserDepartmentUpdate(UserDepartment currentUserDepartment, DepartmentUpdateRequest departmentUpdateRequest)
{
var userDepartmentHistoryUpdates = new List<UserDepartmentHistory>();
if (currentUserDepartment.Role.Name != departmentUpdateRequest.Role)
{
userDepartmentHistoryUpdates.Add(new UserDepartmentHistory
{
UserDepartmentId = currentUserDepartment.Id,
FieldName = "Role",
NewValue = departmentUpdateRequest.Role,
OldValue = currentUserDepartment.Role.Name
});
}
if (currentUserDepartment.SlidingPayout != departmentUpdateRequest.SlidingPayout)
{
userDepartmentHistoryUpdates.Add(new UserDepartmentHistory
{
UserDepartmentId = currentUserDepartment.Id,
FieldName = "SlidingPayout",
NewValue = departmentUpdateRequest.SlidingPayout.ToString(CultureInfo.InvariantCulture),
OldValue = currentUserDepartment.SlidingPayout.ToString(CultureInfo.InvariantCulture)
});
}
if (currentUserDepartment.EndDate?.Date != departmentUpdateRequest.EndDate?.Date)
{
userDepartmentHistoryUpdates.Add(new UserDepartmentHistory
{
UserDepartmentId = currentUserDepartment.Id,
FieldName = "EndDate",
NewValue = departmentUpdateRequest.EndDate.ToString(),
OldValue = currentUserDepartment.EndDate.ToString()
});
}
await _context.UserDepartmentHistories.AddRangeAsync(userDepartmentHistoryUpdates);
return userDepartmentHistoryUpdates;
}
public async Task<List<UserPermissionHistory>> GetUserDepartmentHistory(int employeeId)
{
return await _context.UserPermissionHistories.Where(history => history.EmployeeId == employeeId).ToListAsync();
}
}
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class UserPermissionHistoryRepository : BaseRepository, IUserPermissionHistoryRepository
{
public UserPermissionHistoryRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<List<UserPermissionHistory>> SaveUserPermissionsInsertion(IEnumerable<UserPermission> newPermissions)
{
var newPermissionHistory = newPermissions.Select(userPermission => new UserPermissionHistory
{
Id = 0,
Source = "Manual Assignment",
EmployeeId = Convert.ToInt32(userPermission.AppUser.EmployeeId),
Permission = userPermission.Permission.Code,
PermissionAdded = true
})
.ToList();
await _context.UserPermissionHistories.AddRangeAsync(newPermissionHistory);
return newPermissionHistory;
}
public async Task<List<UserPermissionHistory>> SaveUserPermissionsDeletion(IEnumerable<UserPermission> newPermissions)
{
var newPermissionHistory = newPermissions.Select(userPermission => new UserPermissionHistory
{
Id = 0,
Source = "Manual Assignment",
EmployeeId = Convert.ToInt32(userPermission.AppUser.EmployeeId),
Permission = userPermission.Permission.Code,
PermissionRemoved = true
})
.ToList();
await _context.UserPermissionHistories.AddRangeAsync(newPermissionHistory);
return newPermissionHistory;
}
public async Task<List<UserPermissionHistory>> GetUserPermissionHistory(int employeeId)
{
return await _context.UserPermissionHistories.Where(history => history.EmployeeId == employeeId).ToListAsync();
}
}
@@ -0,0 +1,223 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
using LCU.Library.Internal.IncentiveApiModels.Common;
using LCU.Library.Internal.IncentiveApiModels.Entities;
using LCU.Library.Internal.IncentiveApiModels.Enums;
using LCU.Library.Internal.IncentiveApiModels.Requests;
using Microsoft.EntityFrameworkCore;
namespace LCU.API.Internal.Operations.IncentiveApiLib.Repositories;
public class UserRepository : BaseRepository, IUserRepository
{
public UserRepository(IApplicationDbContext context) : base(context)
{
}
public async Task<IReadOnlyCollection<UserSummary>> GetAllUserSummariesAsync()
{
return await _context.AppUsers
.Select(x => new UserSummary()
{
EmployeeId = x.EmployeeId,
AdEmail = x.AdEmail,
FullName = x.FullName,
ManagerKey = x.ManagerKey,
Terminated = x.Terminated
})
.OrderBy(x => x.EmployeeId)
.ToListAsync();
}
public IReadOnlyCollection<UserSummary> GetTerminatedUsersAsync(MonthRange monthRange)
{
if (!monthRange.IsSingleMonth)
{
throw new ArgumentException("Can only request terminated employees for a single month");
}
return _context.AppUsers
.Where(x => x.Terminated != null
&& x.Terminated >= monthRange.StartTime
&& x.Terminated <= monthRange.EndTime)
.ToList()
.GroupJoin(_context.PayoutLineItems,
user => user.EmployeeId,
pli => pli.EmployeeId,
(x, pli) => new UserSummary()
{
EmployeeId = x.EmployeeId,
AdEmail = x.AdEmail,
FullName = x.FullName,
ManagerKey = x.ManagerKey,
Terminated = x.Terminated,
AssociatedPayouts = pli.ToList()
})
.OrderBy(x => x.EmployeeId)
.ToList();
}
public async Task<ICollection<AppUser>> GetAllUsersAsync()
{
return await _context.AppUsers
.Include(user => user.Departments)
.ThenInclude(userDept => userDept.Department)
.ToListAsync();
}
public async Task<ICollection<AppUser>> GetAllUsersToPayoutAsync(MonthRange range)
{
return await _context.AppUsers
.AsNoTracking()
.Include(user => user.Departments)
.ThenInclude(userDept => userDept.Department)
.Where(x => x.Terminated == null
&& x.Departments.Any(y => y.Department.State == DepartmentState.Active
&& y.StartDate.Date <= range.StartTime.Date
&& (y.EndDate == null || y.EndDate >= range.EndTime.Date)))
.Distinct()
.ToListAsync();
}
public async Task<AppUser> FindUserAsync(string employeeId, string adEmail)
{
if (!string.IsNullOrWhiteSpace(employeeId))
{
return await FindUserByEmployeeIdAsync(employeeId);
}
return await FindUserByAdEmailAsync(adEmail);
}
public async Task<AppUser> FindUserByEmployeeIdAsync(string employeeId)
{
return await _context.AppUsers
.Include(user => user.AdditionalPermissions)
.Include(user => user.Departments)
.ThenInclude(userDept => userDept.Department)
.Include(user => user.Assignments)
.Where(user => user.EmployeeId == employeeId)
.OrderByDescending(user => user.Terminated)
.FirstOrDefaultAsync();
}
public async Task<AppUser> FindUserByAdEmailAsync(string adEmail)
{
return await _context.AppUsers
.Include(user => user.AdditionalPermissions)
.Include(user => user.Departments)
.ThenInclude(userDept => userDept.Department)
.Include(user => user.Assignments)
.Where(user => user.AdEmail.ToLower() == adEmail.ToLower())
.OrderByDescending(user => user.Terminated)
.FirstOrDefaultAsync();
}
public async Task<AppUser> FindActiveUserByEmployeeIdAsync(string employeeId)
{
return await _context.AppUsers
.Include(user => user.AdditionalPermissions)
.Include(user => user.Departments)
.ThenInclude(userDept => userDept.Department)
.Include(user => user.Assignments)
.Where(user => user.EmployeeId == employeeId && user.Terminated == null)
.FirstOrDefaultAsync();
}
public async Task<AppUser> FindActiveUserByAdEmailAsync(string adEmail)
{
return await _context.AppUsers
.Include(user => user.AdditionalPermissions)
.Include(user => user.Departments)
.ThenInclude(userDept => userDept.Department)
.Include(user => user.Assignments)
.Where(user => user.AdEmail.ToLower() == adEmail.ToLower() && user.Terminated == null)
.FirstOrDefaultAsync();
}
public async Task<ICollection<AppUser>> FindUsersByHomeDepartmentsAsync(List<string> homeDepartments)
{
return await _context.AppUsers.Where(user => homeDepartments.Contains(user.HomeDepartment)).ToListAsync();
}
public async Task<ICollection<AppUser>> FindUsersByBaseRolesAsync(List<string> baseRoles)
{
return await _context.AppUsers.Where(user => baseRoles.Contains(user.BaseRole)).ToListAsync();
}
public async Task<AppUser> SaveUserAsync(AppUser newAppUser)
{
await _context.AppUsers.AddAsync(newAppUser);
return newAppUser;
}
public async Task<ICollection<AppUser>> SaveUserRangeAsync(List<AppUser> newUsers)
{
await _context.AppUsers.AddRangeAsync(newUsers);
return newUsers;
}
public async Task<ICollection<AppUser>> SearchUsersAsync(UserSearchRequest userSearchRequest)
{
var users = _context.AppUsers.Include(user => user.Departments).AsQueryable();
if (!string.IsNullOrWhiteSpace(userSearchRequest.Query))
{
var cleanQuery = userSearchRequest.Query.ToLower().Trim();
var emailQuery = BuildEmailQuery(cleanQuery);
users = users.Where(user => user.AdEmail.ToLower().Contains(cleanQuery) ||
user.AdEmail.ToLower().Contains(emailQuery) ||
user.FullName.ToLower().Contains(cleanQuery) ||
user.EmployeeId.ToLower().Contains(cleanQuery));
}
if (!string.IsNullOrWhiteSpace(userSearchRequest.FirstName))
{
users = users.Where(user => user.FullName.ToLower().Contains(userSearchRequest.FirstName.ToLower()));
}
if (!string.IsNullOrWhiteSpace(userSearchRequest.LastName))
{
users = users.Where(user => user.FullName.ToLower().Contains(userSearchRequest.LastName.ToLower()));
}
if (!string.IsNullOrWhiteSpace(userSearchRequest.MiddleInit))
{
users = users.Where(user => user.FullName.ToLower().EndsWith($" {userSearchRequest.MiddleInit.ToLower()}"));
}
if (!string.IsNullOrWhiteSpace(userSearchRequest.Role))
{
var foundRoles = Role.SearchRoles(userSearchRequest.Role);
users = users.Where(user => user.Departments.Any(dept => foundRoles.Contains(dept.Role)));
}
if (userSearchRequest.DnaOrgNbr != null)
{
users = users.Where(user => user.Departments.Any(dept => dept.Department.DnaOrgNbr == userSearchRequest.DnaOrgNbr));
}
return await users.ToListAsync();
}
private string BuildEmailQuery(string cleanQuery)
{
if (cleanQuery.Contains(","))
{
var transform = cleanQuery.Split(",");
if (transform?.Length == 2)
{
return transform[1].Trim() + transform[0].Trim();
}
}
else if (cleanQuery.Contains(" "))
{
return cleanQuery.Replace(" ", "");
}
return cleanQuery;
}
}