Skip to content

Commit

Permalink
Merge pull request #2124 from ytqsl/stories/EMBCESSMOD-5208
Browse files Browse the repository at this point in the history
various bug fixes
  • Loading branch information
ytqsl authored May 8, 2024
2 parents 8f600a8 + 97296fd commit ebe15c9
Show file tree
Hide file tree
Showing 15 changed files with 50 additions and 58 deletions.
4 changes: 2 additions & 2 deletions ess/src/API/EMBC.ESS/Engines/Supporting/Contract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,6 @@ public record CalculateSelfServeSupports(IEnumerable<SelfServeSupport> Supports,

public record GenerateSelfServeSupportsResponse(IEnumerable<SelfServeSupport> Supports) : GenerateResponse;

public record GenerateSelfServeSupports1(string EvacuationFileId, string RegistrantId, IEnumerable<SelfServeSupport> Supports, ETransferDetails ETransferDetails, DateTime SupportPeriodFrom, DateTime SupportPeriodTo) : GenerateRequest;
public record GenerateSelfServeETransferSupports(string EvacuationFileId, string RegistrantId, IEnumerable<SelfServeSupport> Supports, ETransferDetails ETransferDetails, DateTime SupportPeriodFrom, DateTime SupportPeriodTo) : GenerateRequest;

public record GenerateSelfServeSupports1Response(IEnumerable<Support> Supports) : GenerateResponse;
public record GenerateSelfServeETransferSupportsResponse(IEnumerable<Support> Supports) : GenerateResponse;
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ internal class SelfServeEtransferGenerator(IMapper mapper) : ISupportGenerationS
public Task<GenerateResponse> Generate(GenerateRequest request, CancellationToken ct) =>
request switch
{
GenerateSelfServeSupports1 r => Handle(r, ct),
GenerateSelfServeETransferSupports r => Handle(r, ct),

_ => throw new NotImplementedException($"{request.GetType().Name}")
};

private async Task<GenerateResponse> Handle(GenerateSelfServeSupports1 r, CancellationToken ct)
private async Task<GenerateResponse> Handle(GenerateSelfServeETransferSupports r, CancellationToken ct)
{
await Task.CompletedTask;
var supports = new List<Support>();
Expand Down Expand Up @@ -47,7 +47,7 @@ private async Task<GenerateResponse> Handle(GenerateSelfServeSupports1 r, Cancel
supports.Add(support);
}

return new GenerateSelfServeSupports1Response(supports);
return new GenerateSelfServeETransferSupportsResponse(supports);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,21 +75,21 @@ private async Task<SelfServeSupportEligibility> ValidateEligibility(ValidateSelf
await ctx.LoadPropertyAsync(task, nameof(era_task.era_era_task_era_selfservesupportlimits_Task), ct);

// calculate support eligibility period
var eligibleFrom = DateTimeOffset.Now;
var eligibleFrom = DateTimeOffset.UtcNow;
var eligibleTo = eligibleFrom.Add(SupportsPeriod);
if (eligibleTo > task.era_taskenddate) eligibleTo = task.era_taskenddate.Value;
if (eligibleTo > task.era_taskenddate) eligibleTo = task.era_taskenddate.Value.ToUniversalTime();

// check if requested supports include referrals
var requestedReferralSupports = MapReferralSupportTypesFromNeed(needsAssessment).ToArray();
if (requestedReferralSupports.Length > 0) return NotEligible("Evacuee requested referrals", taskNumber: taskNumber, referencedHomeAddressId: homeAddress.era_bcscaddressid);
if (requestedReferralSupports.Length > 0) return NotEligible("Evacuee requested referrals", taskNumber: taskNumber, referencedHomeAddressId: homeAddress.era_bcscaddressid, from: eligibleFrom, to: eligibleTo);

// check if requested e-transfer supports are enabled for self-serve
var requestedETransferSupports = MapETransferSupportTypesFromNeeds(needsAssessment).ToArray();
if (requestedETransferSupports.Length == 0) return NotEligible("Evacuee didn't identify any needs", taskNumber: taskNumber, referencedHomeAddressId: homeAddress.era_bcscaddressid);
if (requestedETransferSupports.Length == 0) return NotEligible("Evacuee didn't identify any needs", taskNumber: taskNumber, referencedHomeAddressId: homeAddress.era_bcscaddressid, from: eligibleFrom, to: eligibleTo);
var allowedSupports = (await ctx.era_selfservesupportlimitses
.Where(sl => sl._era_task_value == task.era_taskid).GetAllPagesAsync())
.Select(s => Enum.Parse<SupportType>(s.era_supporttypeoption.Value.ToString())).ToArray();
if (allowedSupports.Length == 0) return NotEligible("Task has no supports enabled for selfe serve", taskNumber: taskNumber, referencedHomeAddressId: homeAddress.era_bcscaddressid);
if (allowedSupports.Length == 0) return NotEligible("Task has no supports enabled for selfe serve", taskNumber: taskNumber, referencedHomeAddressId: homeAddress.era_bcscaddressid, from: eligibleFrom, to: eligibleTo);
if (!Array.TrueForAll(requestedETransferSupports, rs => allowedSupports.Contains(rs))) return NotEligible("Requested supports are not allowed", taskNumber: taskNumber, referencedHomeAddressId: homeAddress.era_bcscaddressid);

// add - duplicate check
Expand All @@ -106,7 +106,7 @@ private async Task<SelfServeSupportEligibility> ValidateEligibility(ValidateSelf
.Select(s => s.era_name)
.ToList();

if (supports.Any()) return NotEligible($"Duplicate supports found {string.Join(",", supports)}", taskNumber: taskNumber, referencedHomeAddressId: homeAddress.era_bcscaddressid);
if (supports.Any()) return NotEligible($"Duplicate supports found {string.Join(",", supports)}", taskNumber: taskNumber, referencedHomeAddressId: homeAddress.era_bcscaddressid, from: eligibleFrom, to: eligibleTo);
}

// return eligibility results
Expand Down Expand Up @@ -148,9 +148,11 @@ private static SupportType[] SimilarSupportTypes(SupportType type) =>
?.FirstOrDefault(p => p.Name == "ESS_TASK_NUMBER")?.Value;
}

private static SelfServeSupportEligibility NotEligible(string reason, string? taskNumber = null, Guid? referencedHomeAddressId = null) => new SelfServeSupportEligibility(false, reason, taskNumber, referencedHomeAddressId?.ToString(), null, null);
private static SelfServeSupportEligibility NotEligible(string reason, string? taskNumber = null, Guid? referencedHomeAddressId = null, DateTimeOffset? from = null, DateTimeOffset? to = null) =>
new SelfServeSupportEligibility(false, reason, taskNumber, referencedHomeAddressId?.ToString(), from, to);

private static SelfServeSupportEligibility Eligible(string taskNumber, Guid referencedHomeAddressId, DateTimeOffset From, DateTimeOffset To) => new SelfServeSupportEligibility(true, null, taskNumber, referencedHomeAddressId.ToString(), From, To);
private static SelfServeSupportEligibility Eligible(string taskNumber, Guid referencedHomeAddressId, DateTimeOffset from, DateTimeOffset to) =>
new SelfServeSupportEligibility(true, null, taskNumber, referencedHomeAddressId.ToString(), from, to);

private enum NeedTrueFalse
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public async Task<GenerateResponse> Generate(GenerateRequest request, Cancellati
GeneratePaymentsRequest r => await paymentGenerationStrategyFactory.Create().GeneratePayments(r),
GenerateSelfServeSupports r => await supportGenerationStrategyStragetyFactory.Create(SupportGenerationStrategyType.SelfServeDraft).Generate(r, ct),
CalculateSelfServeSupports r => await supportGenerationStrategyStragetyFactory.Create(SupportGenerationStrategyType.SelfServeDraft).Generate(r, ct),
GenerateSelfServeSupports1 r => await supportGenerationStrategyStragetyFactory.Create(SupportGenerationStrategyType.SelfServeETransfer).Generate(r, ct),
GenerateSelfServeETransferSupports r => await supportGenerationStrategyStragetyFactory.Create(SupportGenerationStrategyType.SelfServeETransfer).Generate(r, ct),
_ => throw new NotImplementedException(request.GetType().Name)
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ public async System.Threading.Tasks.Task Handle(ProcessSelfServeSupportsCommand
if (file == null) throw new NotFoundException("file not found", cmd.EvacuationFileId);
if (file.NeedsAssessment.EligibilityCheck == null || !file.NeedsAssessment.EligibilityCheck.Eligible) throw new BusinessLogicException($"File {cmd.EvacuationFileId} latest needs assessment doesn't have a valid eligibility check");

var supports = ((GenerateSelfServeSupports1Response)await supportingEngine.Generate(
new GenerateSelfServeSupports1(file.Id, file.PrimaryRegistrantId, cmd.Supports, cmd.ETransferDetails, file.NeedsAssessment.EligibilityCheck.From.Value, file.NeedsAssessment.EligibilityCheck.From.Value))).Supports;
var supports = ((GenerateSelfServeETransferSupportsResponse)await supportingEngine.Generate(
new GenerateSelfServeETransferSupports(file.Id, file.PrimaryRegistrantId, cmd.Supports, cmd.ETransferDetails, file.NeedsAssessment.EligibilityCheck.From.Value, file.NeedsAssessment.EligibilityCheck.From.Value))).Supports;
var validationResponse = (DigitalSupportsValidationResponse)await supportingEngine.Validate(new DigitalSupportsValidationRequest
{
FileId = cmd.EvacuationFileId,
Expand Down
9 changes: 0 additions & 9 deletions ess/src/API/EMBC.ESS/Managers/Events/EventsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,6 @@ public async Task<string> Handle(SubmitEvacuationFileCommand cmd)
if (evacuee == null) throw new NotFoundException($"Registrant not found '{file.PrimaryRegistrantId}'", file.PrimaryRegistrantId);
file.PrimaryRegistrantId = evacuee.Id;

if (!string.IsNullOrEmpty(file.Id))
{
var caseRecord = (await evacuationRepository.Query(new Resources.Evacuations.EvacuationFilesQuery { FileId = file.Id })).Items.SingleOrDefault();
var existingFile = mapper.Map<Resources.Evacuations.EvacuationFile>(caseRecord);

if (!string.IsNullOrEmpty(existingFile.TaskId) && !existingFile.TaskId.Equals(file.TaskId, StringComparison.Ordinal))
throw new BusinessLogicException($"The ESS Task Number cannot be modified or updated once it's been initially assigned.");
}

var caseId = (await evacuationRepository.Manage(new SubmitEvacuationFileNeedsAssessment { EvacuationFile = file })).Id;

var shouldEmailNotification = string.IsNullOrEmpty(file.Id) && !string.IsNullOrEmpty(evacuee.Email) && string.IsNullOrEmpty(file.ManualFileId);
Expand Down
1 change: 1 addition & 0 deletions ess/src/API/EMBC.ESS/Resources/Evacuations/Contract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ public record EvacuationAddress
public record NeedsAssessment
{
public string Id { get; set; }
public string? TaskNumber { get; set; }
public EvacuationAddress EvacuatedFrom { get; set; }
public DateTime CompletedOn { get; set; }
public string CompletedByTeamMemberId { get; set; }
Expand Down
35 changes: 21 additions & 14 deletions ess/src/API/EMBC.ESS/Resources/Evacuations/EvacuationRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,12 @@ public async Task<string> Create(EssContext essContext, EvacuationFile evacuatio
essContext.AddToera_evacuationfiles(file);
essContext.SetLink(file, nameof(era_evacuationfile.era_EvacuatedFromID), essContext.LookupJurisdictionByCode(file._era_evacuatedfromid_value?.ToString()));
AssignPrimaryRegistrant(essContext, file, primaryContact);
AssignToTask(essContext, file, evacuationFile.TaskId);
AddPets(essContext, file);

AddNeedsAssessment(essContext, file, file.era_CurrentNeedsAssessmentid);

AssignToTask(essContext, file, evacuationFile.TaskId);

await essContext.SaveChangesAsync(ct);

essContext.Detach(file);
Expand All @@ -107,29 +108,33 @@ public async Task<string> Create(EssContext essContext, EvacuationFile evacuatio

public async Task<string> Update(EssContext essContext, EvacuationFile evacuationFile, CancellationToken ct)
{
var currentFile = essContext.era_evacuationfiles
.Where(f => f.era_name == evacuationFile.Id).SingleOrDefault();
var currentFile = await essContext.era_evacuationfiles
.Expand(f => f.era_TaskId)
.Expand(f => f.era_era_evacuationfile_era_householdmember_EvacuationFileid)
.Expand(f => f.era_era_evacuationfile_era_animal_ESSFileid)
.Where(f => f.era_name == evacuationFile.Id)
.SingleOrDefaultAsync(ct);
if (currentFile == null) throw new ArgumentException($"Evacuation file {evacuationFile.Id} not found");
essContext.DetachAll();

await essContext.LoadPropertyAsync(currentFile, nameof(era_evacuationfile.era_era_evacuationfile_era_householdmember_EvacuationFileid), ct);
await essContext.LoadPropertyAsync(currentFile, nameof(era_evacuationfile.era_era_evacuationfile_era_animal_ESSFileid), ct);
VerifyEvacuationFileInvariants(evacuationFile, currentFile);

essContext.DetachAll();
RemovePets(essContext, currentFile);

var file = mapper.Map<era_evacuationfile>(evacuationFile);
file.era_evacuationfileid = currentFile.era_evacuationfileid;
file.era_TaskId = currentFile.era_TaskId;

essContext.AttachTo(nameof(essContext.era_evacuationfiles), file);
essContext.SetLink(file, nameof(era_evacuationfile.era_EvacuatedFromID), essContext.LookupJurisdictionByCode(file._era_evacuatedfromid_value?.ToString()));

essContext.UpdateObject(file);
AssignToTask(essContext, file, evacuationFile.TaskId);
AddPets(essContext, file);

AddNeedsAssessment(essContext, file, file.era_CurrentNeedsAssessmentid);

AssignToTask(essContext, file, evacuationFile.TaskId);

await essContext.SaveChangesAsync(ct);

essContext.DetachAll();
Expand Down Expand Up @@ -176,12 +181,13 @@ private static void AssignPrimaryRegistrant(EssContext essContext, era_evacuatio
essContext.SetLink(file, nameof(era_evacuationfile.era_Registrant), primaryContact);
}

private static void AssignToTask(EssContext essContext, era_evacuationfile file, string taskId)
private static void AssignToTask(EssContext essContext, era_evacuationfile file, string taskNumber)
{
if (string.IsNullOrEmpty(taskId)) return;
var task = essContext.era_tasks.Where(t => t.era_name == taskId).OrderByDescending(t => t.createdon).FirstOrDefault();
if (task == null) throw new ArgumentException($"Task {taskId} not found");
essContext.AddLink(task, nameof(era_task.era_era_task_era_evacuationfileId), file);
if (string.IsNullOrEmpty(taskNumber)) return;
var task = essContext.era_tasks.Where(t => t.era_name == taskNumber).OrderByDescending(t => t.createdon).FirstOrDefault();
if (task == null) throw new ArgumentException($"Task {taskNumber} not found");
if (file.era_TaskId == null) essContext.SetLink(file, nameof(era_evacuationfile.era_TaskId), task);
essContext.SetLink(file.era_CurrentNeedsAssessmentid, nameof(era_needassessment.era_TaskNumber), task);
}

private static void AssignHouseholdMember(EssContext essContext, era_evacuationfile file, era_householdmember member)
Expand All @@ -192,7 +198,6 @@ private static void AssignHouseholdMember(EssContext essContext, era_evacuationf
if (registrant == null) throw new ArgumentException($"Household member has registrant id {member._era_registrant_value} which was not found");
essContext.AddLink(registrant, nameof(contact.era_contact_era_householdmember_Registrantid), member);
}
essContext.AddLink(file, nameof(era_evacuationfile.era_era_evacuationfile_era_householdmember_EvacuationFileid), member);
essContext.SetLink(member, nameof(era_householdmember.era_EvacuationFileid), file);
}

Expand All @@ -206,7 +211,6 @@ private static void AddPets(EssContext essContext, era_evacuationfile file)
foreach (var pet in file.era_era_evacuationfile_era_animal_ESSFileid)
{
essContext.AddToera_animals(pet);
essContext.AddLink(file, nameof(era_evacuationfile.era_era_evacuationfile_era_animal_ESSFileid), pet);
essContext.SetLink(pet, nameof(era_animal.era_ESSFileid), file);
}
}
Expand Down Expand Up @@ -282,6 +286,7 @@ private static async Task ParallelLoadEvacuationFileAsync(EssContext ctx, era_ev
{
if (file.era_CurrentNeedsAssessmentid == null) await ctx.LoadPropertyAsync(file, nameof(era_evacuationfile.era_CurrentNeedsAssessmentid), ct);
ctx.AttachTo(nameof(EssContext.era_needassessments), file.era_CurrentNeedsAssessmentid);
if (file.era_CurrentNeedsAssessmentid.era_TaskNumber==null) await ctx.LoadPropertyAsync(file.era_CurrentNeedsAssessmentid, nameof(era_needassessment.era_TaskNumber), ct);
if (file.era_CurrentNeedsAssessmentid.era_EligibilityCheck==null) await ctx.LoadPropertyAsync(file.era_CurrentNeedsAssessmentid, nameof(era_needassessment.era_EligibilityCheck), ct);
if (file.era_CurrentNeedsAssessmentid.era_EligibilityCheck != null)
{
Expand Down Expand Up @@ -391,6 +396,7 @@ private static async Task<IEnumerable<era_evacuationfile>> QueryNeedsAssessments

var needsAssessmentQuery = ctx.era_needassessments
.Expand(n => n.era_EvacuationFile)
.Expand(n => n.era_TaskNumber)
.Where(n => n.statecode == (int)EntityState.Active);

if (!string.IsNullOrEmpty(query.NeedsAssessmentId)) needsAssessmentQuery = needsAssessmentQuery.Where(n => n.era_needassessmentid == Guid.Parse(query.NeedsAssessmentId));
Expand Down Expand Up @@ -488,6 +494,7 @@ private async Task<ManageEvacuationFileCommandResult> Handle(OptoutSelfServe c,
if (check != null)
{
check.era_selfserveoptout = true;
ctx.UpdateObject(check);
await ctx.SaveChangesAsync(ct);
}
return new ManageEvacuationFileCommandResult { Id = check?.era_eligibilitycheckid?.ToString() };
Expand Down
5 changes: 3 additions & 2 deletions ess/src/API/EMBC.ESS/Resources/Evacuations/Mappings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ public Mappings()

CreateMap<era_needassessment, NeedsAssessment>()
.ForMember(d => d.Id, opts => opts.MapFrom(s => s.era_needassessmentid))
.ForMember(d => d.TaskNumber, opts => opts.MapFrom(s => s.era_TaskNumber == null ? null : s.era_TaskNumber.era_name))
.ForMember(d => d.EvacuatedFrom, opts => opts.MapFrom(s => s))
.ForMember(d => d.CompletedByTeamMemberId, opts => opts.MapFrom(s => s._era_reviewedbyid_value))
.ForMember(d => d.CompletedOn, opts => opts.MapFrom(s => s.createdon.Value.UtcDateTime))
Expand Down Expand Up @@ -197,8 +198,8 @@ public Mappings()
CreateMap<era_eligibilitycheck, SelfServeEligibilityCheck>()
.ForMember(d => d.Eligible, opts => opts.MapFrom(s => s.era_iseligible == (int)Eligible.Yes))
.ForMember(d => d.TaskNumber, opts => opts.MapFrom(s => s.era_Task == null ? null : s.era_Task.era_name))
.ForMember(d => d.From, opts => opts.MapFrom(s => s.era_eligibilityperiodfrom.HasValue ? s.era_eligibilityperiodfrom.Value.DateTime : (DateTime?)null))
.ForMember(d => d.To, opts => opts.MapFrom(s => s.era_eligibilityperiodto.HasValue ? s.era_eligibilityperiodto.Value.DateTime : (DateTime?)null))
.ForMember(d => d.From, opts => opts.MapFrom(s => s.era_eligibilityperiodfrom.HasValue ? s.era_eligibilityperiodfrom.Value.DateTime.ToUniversalTime() : (DateTime?)null))
.ForMember(d => d.To, opts => opts.MapFrom(s => s.era_eligibilityperiodto.HasValue ? s.era_eligibilityperiodto.Value.DateTime.ToUniversalTime() : (DateTime?)null))
;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,20 +203,6 @@ public async Task Update_EvacuationFileMultiplePrimaryRegistrants_ThrowsError()
.Message.ShouldBe($"File {file.Id} can not have multiple primary registrant household members");
}

[Fact]
public async Task Update_EvacuationFileTask_ThrowsError()
{
var fileWithTask = await GetEvacuationFileById(TestData.EvacuationFileId);
fileWithTask.RelatedTask.Id = TestData.ActiveTaskId;
//update file to task
await manager.Handle(new SubmitEvacuationFileCommand { File = fileWithTask });

//update to a different task
fileWithTask.RelatedTask.Id = TestData.InactiveTaskId;
(await Should.ThrowAsync<Exception>(async () => await manager.Handle(new SubmitEvacuationFileCommand { File = fileWithTask })))
.Message.ShouldBe($"The ESS Task Number cannot be modified or updated once it's been initially assigned.");
}

[Fact]
public async Task CanUpdateEvacuation()
{
Expand Down
Loading

0 comments on commit ebe15c9

Please sign in to comment.