From c25859c70c5f6a792e20755d02a562a657c18ea0 Mon Sep 17 00:00:00 2001 From: Rex Lorenzo Date: Mon, 2 Nov 2026 21:23:59 -0800 Subject: [PATCH 1/4] VPR-244 feat(effort): set CAHFS report unit for 072200 on harvest - Instructors added by any harvest phase (CREST, non-CREST, clinical) get report unit CAHFS when they hold an AAUD job in dept 072200 - Existing term rows and manually added instructors are unchanged --- test/Effort/ClinicalImportServiceTests.cs | 72 +++++++++++++++- test/Effort/HarvestServiceTests.cs | 79 +++++++++++++++++ test/Effort/InstructorServiceTests.cs | 86 +++++++++++++++++++ web/Areas/Effort/Constants/EffortConstants.cs | 11 +++ .../Effort/Services/ClinicalImportService.cs | 44 +++++++++- .../Effort/Services/EffortAuditService.cs | 12 ++- .../Effort/Services/Harvest/HarvestContext.cs | 5 ++ .../Services/Harvest/HarvestPhaseBase.cs | 10 ++- .../Effort/Services/IEffortAuditService.cs | 2 +- .../Effort/Services/IInstructorService.cs | 15 ++++ .../Effort/Services/InstructorService.cs | 41 ++++++++- 11 files changed, 364 insertions(+), 13 deletions(-) diff --git a/test/Effort/ClinicalImportServiceTests.cs b/test/Effort/ClinicalImportServiceTests.cs index 467d6a274..c52607442 100644 --- a/test/Effort/ClinicalImportServiceTests.cs +++ b/test/Effort/ClinicalImportServiceTests.cs @@ -1,3 +1,4 @@ +using System.Threading.Channels; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.Logging; @@ -331,8 +332,10 @@ public async Task GetPreviewAsync_SyncMode_CalculatesCountsCorrectly() #region ExecuteImportAsync - EnsureEffortPerson/Course Tests - [Fact] - public async Task ExecuteImportAsync_CreatesEffortPerson_WhenMissing() + [Theory] + [InlineData(false, null)] + [InlineData(true, EffortConstants.CahfsReportUnit)] + public async Task ExecuteImportAsync_CreatesEffortPerson_WhenMissing(bool hasCahfsJob, string? expectedReportUnit) { // Arrange - term, source data, AAUD record, VIPER person — but NO EffortPerson await SeedTermAndCourseAsync(); @@ -382,6 +385,10 @@ public async Task ExecuteImportAsync_CreatesEffortPerson_WhenMissing() }); await _aaudContext.SaveChangesAsync(TestContext.Current.CancellationToken); + _instructorServiceMock + .GetCahfsMothraIdsAsync(Arg.Any>(), TermCode, Arg.Any()) + .Returns(hasCahfsJob ? new HashSet { "INST0020" } : new HashSet()); + // Act var result = await _service.ExecuteImportAsync(TermCode, ClinicalImportMode.AddNewOnly, modifiedBy: 1, TestContext.Current.CancellationToken); @@ -394,6 +401,67 @@ public async Task ExecuteImportAsync_CreatesEffortPerson_WhenMissing() Assert.Equal("CLINICAL", effortPerson.LastName); Assert.Equal("VME", effortPerson.EffortDept); Assert.Equal("1234", effortPerson.EffortTitleCode); + Assert.Equal(expectedReportUnit, effortPerson.ReportUnit); + await _instructorServiceMock.Received(1).GetCahfsMothraIdsAsync( + Arg.Any>(), TermCode, Arg.Any()); + await _instructorServiceMock.DidNotReceiveWithAnyArgs().HasCahfsAppointmentAsync(default!, default, TestContext.Current.CancellationToken); + } + + [Theory] + [InlineData(null, true, false, false, EffortConstants.CahfsReportUnit)] + [InlineData("", true, false, false, EffortConstants.CahfsReportUnit)] + [InlineData(null, false, false, false, null)] + [InlineData("PMI", true, false, false, "PMI")] + [InlineData(null, true, true, false, EffortConstants.CahfsReportUnit)] + [InlineData(null, true, true, true, EffortConstants.CahfsReportUnit)] + public async Task ExecuteImportAsync_TagsExistingPersonCahfs_OnlyWhenReportUnitUnset( + string? existingReportUnit, bool hasCahfsJob, bool hasExistingRecord, bool withProgress, string? expectedReportUnit) + { + // Arrange - instructor already exists for the term (e.g. added manually) + await SeedTermAndCourseAsync(); + await SeedSourceDataAsync("INST0022", "DVM", "453", weekCount: 2); + _context.ViperPersons.Add(new ViperPerson + { + PersonId = 22, + FirstName = "Existing", + LastName = "Clinical", + MothraId = "INST0022" + }); + _context.Persons.Add(new EffortPerson + { + PersonId = 22, + TermCode = TermCode, + FirstName = "EXISTING", + LastName = "CLINICAL", + EffortDept = "VME", + EffortTitleCode = "1234", + ReportUnit = existingReportUnit + }); + await _context.SaveChangesAsync(TestContext.Current.CancellationToken); + + if (hasExistingRecord) + { + // First import creates the clinical record, so the repeat import skips it + await _service.ExecuteImportAsync(TermCode, ClinicalImportMode.AddNewOnly, modifiedBy: 1, TestContext.Current.CancellationToken); + _auditServiceMock.ClearReceivedCalls(); + } + + _instructorServiceMock + .GetCahfsMothraIdsAsync(Arg.Any>(), TermCode, Arg.Any()) + .Returns(hasCahfsJob ? new HashSet { "INST0022" } : new HashSet()); + + // Act + var result = withProgress + ? await _service.ExecuteImportWithProgressAsync(TermCode, ClinicalImportMode.AddNewOnly, modifiedBy: 1, + Channel.CreateUnbounded().Writer, TestContext.Current.CancellationToken) + : await _service.ExecuteImportAsync(TermCode, ClinicalImportMode.AddNewOnly, modifiedBy: 1, TestContext.Current.CancellationToken); + + // Assert + Assert.True(result.Success); + var effortPerson = await _context.Persons.AsNoTracking().SingleAsync(p => p.PersonId == 22 && p.TermCode == TermCode, TestContext.Current.CancellationToken); + Assert.Equal(expectedReportUnit, effortPerson.ReportUnit); + _auditServiceMock.Received(expectedReportUnit != existingReportUnit ? 1 : 0).AddPersonChangeAudit( + 22, TermCode, EffortAuditActions.UpdatePerson, Arg.Any(), Arg.Any()); } [Fact] diff --git a/test/Effort/HarvestServiceTests.cs b/test/Effort/HarvestServiceTests.cs index 94b4198e3..be1e13eef 100644 --- a/test/Effort/HarvestServiceTests.cs +++ b/test/Effort/HarvestServiceTests.cs @@ -221,6 +221,85 @@ public async Task GeneratePreviewAsync_CallsTermServiceForTermName() _termServiceMock.Received(1).GetTermName(TestTermCode); } + [Theory] + [InlineData(false, null)] + [InlineData(true, EffortConstants.CahfsReportUnit)] + public async Task ImportPerson_SetsCahfsReportUnit_WhenPersonHasCahfsJob(bool hasCahfsJob, string? expectedReportUnit) + { + // Arrange + var ct = TestContext.Current.CancellationToken; + IReadOnlySet cahfsIds = new HashSet(hasCahfsJob ? ["00193236"] : []); + _instructorServiceMock + .GetCahfsMothraIdsAsync(TestTermCode, Arg.Any()) + .Returns(cahfsIds); + var context = new HarvestContext + { + TermCode = TestTermCode, + EffortContext = _context, + CrestContext = _crestContext, + CoursesContext = _coursesContext, + ViperContext = _viperContext, + AaudContext = _aaudContext, + DictionaryContext = _dictionaryContext, + AuditService = _auditServiceMock, + InstructorService = _instructorServiceMock, + TermService = _termServiceMock, + Logger = _loggerMock + }; + context.Preview.NonCrestInstructors.Add(new HarvestPersonPreview + { + MothraId = "00193236", + PersonId = 25756, + FirstName = "Linda", + LastName = "Barter", + Department = "VSR", + TitleCode = "001917" + }); + + // Act + await new NonCrestHarvestPhase().ExecuteAsync(context, ct); + + // Assert + var person = Assert.Single(_context.Persons.Local); + Assert.Equal(expectedReportUnit, person.ReportUnit); + _auditServiceMock.Received(1).AddHarvestPersonAudit(25756, TestTermCode, "Linda", "Barter", "VSR", expectedReportUnit); + } + + [Fact] + public async Task ImportPerson_LoadsCahfsIdsOnce_ForMultiplePeople() + { + // Arrange + var ct = TestContext.Current.CancellationToken; + IReadOnlySet cahfsIds = new HashSet { "00193236" }; + _instructorServiceMock + .GetCahfsMothraIdsAsync(TestTermCode, Arg.Any()) + .Returns(cahfsIds); + var context = new HarvestContext + { + TermCode = TestTermCode, + EffortContext = _context, + CrestContext = _crestContext, + CoursesContext = _coursesContext, + ViperContext = _viperContext, + AaudContext = _aaudContext, + DictionaryContext = _dictionaryContext, + AuditService = _auditServiceMock, + InstructorService = _instructorServiceMock, + TermService = _termServiceMock, + Logger = _loggerMock + }; + context.Preview.NonCrestInstructors.Add(new HarvestPersonPreview { MothraId = "00193236", PersonId = 25756, FirstName = "Linda", LastName = "Barter", Department = "VSR" }); + context.Preview.NonCrestInstructors.Add(new HarvestPersonPreview { MothraId = "00999999", PersonId = 25757, FirstName = "Other", LastName = "Person", Department = "VSR" }); + + // Act + await new NonCrestHarvestPhase().ExecuteAsync(context, ct); + + // Assert + await _instructorServiceMock.Received(1).GetCahfsMothraIdsAsync(TestTermCode, Arg.Any()); + Assert.Equal(EffortConstants.CahfsReportUnit, _context.Persons.Local.Single(p => p.PersonId == 25756).ReportUnit); + Assert.Null(_context.Persons.Local.Single(p => p.PersonId == 25757).ReportUnit); + } + #endregion #region ExecuteHarvestAsync Tests diff --git a/test/Effort/InstructorServiceTests.cs b/test/Effort/InstructorServiceTests.cs index 1107c2a64..ff383ab33 100644 --- a/test/Effort/InstructorServiceTests.cs +++ b/test/Effort/InstructorServiceTests.cs @@ -321,6 +321,53 @@ public async Task CreateInstructorAsync_ThrowsInstructorAlreadyExistsException_W Assert.Contains("already exists", ex.Message); } + [Theory] + [InlineData("072200", EffortConstants.CahfsReportUnit)] + [InlineData("072030", null)] + public async Task CreateInstructorAsync_SetsCahfsReportUnit_WhenPersonHasCahfsJob(string jobDept, string? expectedReportUnit) + { + // Arrange + _viperContext.People.Add(new Person + { + PersonId = 300, + ClientId = "33330000", + FirstName = "Manual", + LastName = "Add", + FullName = "Add, Manual", + MothraId = "33330000", + CurrentEmployee = true + }); + await _viperContext.SaveChangesAsync(TestContext.Current.CancellationToken); + _aaudContext.Ids.Add(new Id + { + IdsPKey = "MANUAL01", + IdsTermCode = "202410", + IdsMothraid = "33330000", + IdsClientid = "33330000" + }); + _aaudContext.Jobs.Add(new Job + { + JobPKey = "MANUAL01", + JobSeqNum = 1, + JobTermCode = "202410", + JobClientid = "33330000", + JobDepartmentCode = jobDept, + JobPercentFulltime = 100, + JobTitleCode = "1234", + JobBargainingUnit = "99", + JobSchoolDivision = "VM" + }); + await _aaudContext.SaveChangesAsync(TestContext.Current.CancellationToken); + + // Act + await _instructorService.CreateInstructorAsync( + new CreateInstructorRequest { PersonId = 300, TermCode = 202410 }, TestContext.Current.CancellationToken); + + // Assert + var created = await _context.Persons.AsNoTracking().SingleAsync(p => p.PersonId == 300, TestContext.Current.CancellationToken); + Assert.Equal(expectedReportUnit, created.ReportUnit); + } + #endregion #region UpdateInstructorAsync Tests @@ -761,6 +808,45 @@ public async Task ResolveInstructorDepartmentAsync_ReturnsUNK_WhenNoEmployeeOrJo Assert.Equal("UNK", dept); } + [Theory] + [InlineData("072200", "202410", "22220000", "202410", true)] + [InlineData("072030", "202410", "22220000", "202410", false)] + [InlineData("072200", "202402", "22220000", "202410", false)] + [InlineData("072200", "202410", "33330000", "202410", false)] + [InlineData("072200", "202410", "22220000", "202402", false)] + public async Task HasCahfsAppointmentAsync_MatchesCahfsJobForTerm(string jobDept, string jobTerm, string idsMothraId, string idsTerm, bool expected) + { + // Arrange + _aaudContext.Ids.Add(new Id + { + IdsPKey = "CAHFS01", + IdsTermCode = idsTerm, + IdsMothraid = idsMothraId, + IdsClientid = "22220000" + }); + _aaudContext.Jobs.Add(new Job + { + JobPKey = "CAHFS01", + JobSeqNum = 1, + JobTermCode = jobTerm, + JobClientid = "22220000", + JobDepartmentCode = jobDept, + JobPercentFulltime = 100, + JobTitleCode = "1234", + JobBargainingUnit = "99", + JobSchoolDivision = "VM" + }); + await _aaudContext.SaveChangesAsync(TestContext.Current.CancellationToken); + + // Act + var result = await _instructorService.HasCahfsAppointmentAsync("22220000", 202410, TestContext.Current.CancellationToken); + var termIds = await _instructorService.GetCahfsMothraIdsAsync(202410, TestContext.Current.CancellationToken); + + // Assert + Assert.Equal(expected, result); + Assert.Equal(expected, termIds.Contains("22220000")); + } + #endregion #region PersonDto Mapping Tests diff --git a/web/Areas/Effort/Constants/EffortConstants.cs b/web/Areas/Effort/Constants/EffortConstants.cs index be4c39bb4..2acb8522c 100644 --- a/web/Areas/Effort/Constants/EffortConstants.cs +++ b/web/Areas/Effort/Constants/EffortConstants.cs @@ -113,6 +113,17 @@ public static double ToStoredPercent(decimal displayValue) /// public const string ClinicalCustodialDept = "DVM"; + /// + /// AAUD department code for CAHFS. Harvested instructors with a job in this + /// department get the CAHFS report unit. + /// + public const string CahfsDeptCode = "072200"; + + /// + /// Report unit code for CAHFS (effort.ReportUnits.UnitCode). + /// + public const string CahfsReportUnit = "CAHFS"; + /// /// Default units for clinical courses. /// diff --git a/web/Areas/Effort/Services/ClinicalImportService.cs b/web/Areas/Effort/Services/ClinicalImportService.cs index 10bd7eb54..b2c9d8572 100644 --- a/web/Areas/Effort/Services/ClinicalImportService.cs +++ b/web/Areas/Effort/Services/ClinicalImportService.cs @@ -74,6 +74,11 @@ public class ClinicalImportService : IClinicalImportService /// private HashSet? _excludedTitleCodes; + /// + /// Source instructors with a CAHFS appointment for the term, loaded once per import. + /// + private IReadOnlySet _cahfsMothraIds = new HashSet(); + public ClinicalImportService( EffortDbContext context, VIPERContext viperContext, @@ -245,6 +250,8 @@ public async Task ExecuteImportAsync(int termCode, Clin ? await _context.Database.BeginTransactionAsync(ct) : null; + await TagCahfsOnExistingPersonsAsync(sourceData, termCode, ct); + // Execute import based on mode var result = await ExecuteImportInternalAsync(sourceData, existingRecords, termCode, mode, modifiedBy, ct); @@ -320,6 +327,8 @@ public async Task ExecuteImportWithProgressAsync( ? await _context.Database.BeginTransactionAsync(ct) : null; + await TagCahfsOnExistingPersonsAsync(sourceData, termCode, ct); + // Execute import based on mode with progress var result = await ExecuteImportWithProgressInternalAsync( sourceData, existingRecords, termCode, mode, modifiedBy, progressChannel, ct); @@ -986,6 +995,36 @@ private async Task ExecuteImportWithProgressInternalAsy return result; } + /// + /// Tag CAHFS on source instructors who already exist for the term with no report unit + /// (e.g. added before the rule), whether or not their clinical records change. + /// + private async Task TagCahfsOnExistingPersonsAsync(List sourceData, int termCode, CancellationToken ct) + { + var mothraIds = sourceData.Select(s => s.MothraId).Distinct().ToList(); + _cahfsMothraIds = await _instructorService.GetCahfsMothraIdsAsync(mothraIds, termCode, ct); + if (_cahfsMothraIds.Count == 0) + { + return; + } + + var untagged = await _context.Persons + .Where(p => p.TermCode == termCode && string.IsNullOrEmpty(p.ReportUnit)) + .Join(_context.ViperPersons.Where(vp => EF.Parameter(mothraIds).Contains(vp.MothraId)), + p => p.PersonId, vp => vp.PersonId, (p, vp) => new { Person = p, vp.MothraId }) + .ToListAsync(ct); + + foreach (var person in untagged.Where(u => _cahfsMothraIds.Contains(u.MothraId)).Select(u => u.Person)) + { + var oldValues = new { person.ReportUnit }; + person.ReportUnit = EffortConstants.CahfsReportUnit; + _auditService.AddPersonChangeAudit(person.PersonId, termCode, EffortAuditActions.UpdatePerson, + oldValues, new { person.ReportUnit }); + } + + await _context.SaveChangesAsync(ct); + } + /// /// Create a clinical effort record for the given instructor and course. /// Creates EffortPerson and EffortCourse on the fly if they don't exist. @@ -1140,14 +1179,15 @@ private async Task EnsureEffortPersonAsync( PercentAdmin = 0, JobGroupId = _jobGroupLookup?.GetValueOrDefault(titleCode), Title = null, - AdminUnit = null + AdminUnit = null, + ReportUnit = _cahfsMothraIds.Contains(mothraId) ? EffortConstants.CahfsReportUnit : null }; _context.Persons.Add(effortPerson); await _context.SaveChangesAsync(ct); _processedMothraIds[mothraId] = true; - _auditService.AddHarvestPersonAudit(personId, termCode, firstName, lastName, dept); + _auditService.AddHarvestPersonAudit(personId, termCode, firstName, lastName, dept, effortPerson.ReportUnit); return true; } diff --git a/web/Areas/Effort/Services/EffortAuditService.cs b/web/Areas/Effort/Services/EffortAuditService.cs index 9bbf29cf1..aeb5723d3 100644 --- a/web/Areas/Effort/Services/EffortAuditService.cs +++ b/web/Areas/Effort/Services/EffortAuditService.cs @@ -133,16 +133,20 @@ await _context.Audits _logger.LogInformation("Cleared audit records for term {TermCode}", termCode); } - public void AddHarvestPersonAudit(int personId, int termCode, string firstName, string lastName, string department) + public void AddHarvestPersonAudit(int personId, int termCode, string firstName, string lastName, string department, string? reportUnit) { - var changes = JsonSerializer.Serialize(new Dictionary + var changes = new Dictionary { ["PersonId"] = new ChangeDetail { OldValue = null, NewValue = personId.ToString() }, ["Name"] = new ChangeDetail { OldValue = null, NewValue = $"{lastName}, {firstName}" }, ["Department"] = new ChangeDetail { OldValue = null, NewValue = department } - }); + }; + if (reportUnit != null) + { + changes["ReportUnit"] = new ChangeDetail { OldValue = null, NewValue = reportUnit }; + } - AddAuditEntry(EffortAuditTables.Persons, personId, termCode, EffortAuditActions.HarvestCreatePerson, changes); + AddAuditEntry(EffortAuditTables.Persons, personId, termCode, EffortAuditActions.HarvestCreatePerson, JsonSerializer.Serialize(changes)); } public void AddHarvestCourseAudit(int courseId, int termCode, string subjCode, string crseNumb, string crn) diff --git a/web/Areas/Effort/Services/Harvest/HarvestContext.cs b/web/Areas/Effort/Services/Harvest/HarvestContext.cs index c26518f32..2613c9f43 100644 --- a/web/Areas/Effort/Services/Harvest/HarvestContext.cs +++ b/web/Areas/Effort/Services/Harvest/HarvestContext.cs @@ -59,6 +59,11 @@ public sealed class HarvestContext /// public HashSet? ExcludedTitleCodes { get; set; } + /// + /// MothraIds with a CAHFS job for the term, loaded once when the first person is imported. + /// + public IReadOnlySet? CahfsMothraIds { get; set; } + /// /// Warnings accumulated during harvest. /// diff --git a/web/Areas/Effort/Services/Harvest/HarvestPhaseBase.cs b/web/Areas/Effort/Services/Harvest/HarvestPhaseBase.cs index 68d7930c5..c76613f70 100644 --- a/web/Areas/Effort/Services/Harvest/HarvestPhaseBase.cs +++ b/web/Areas/Effort/Services/Harvest/HarvestPhaseBase.cs @@ -1,4 +1,5 @@ using Microsoft.EntityFrameworkCore; +using Viper.Areas.Effort.Constants; using Viper.Areas.Effort.Models.DTOs.Responses; using Viper.Areas.Effort.Models.Entities; using Viper.Classes.Utilities; @@ -53,6 +54,8 @@ protected async Task ImportPersonAsync( return; } + ctx.CahfsMothraIds ??= await ctx.InstructorService.GetCahfsMothraIdsAsync(ctx.TermCode, ct); + var effortPerson = new EffortPerson { PersonId = person.PersonId, @@ -65,14 +68,17 @@ protected async Task ImportPersonAsync( PercentAdmin = 0, JobGroupId = !string.IsNullOrEmpty(person.TitleCode) ? ctx.JobGroupLookup?.GetValueOrDefault(person.TitleCode.Trim()) : null, Title = null, - AdminUnit = null + AdminUnit = null, + ReportUnit = ctx.CahfsMothraIds.Contains(person.MothraId) + ? EffortConstants.CahfsReportUnit + : null }; ctx.EffortContext.Persons.Add(effortPerson); ctx.ImportedMothraIds.Add(person.MothraId); ctx.AuditService.AddHarvestPersonAudit( - person.PersonId, ctx.TermCode, person.FirstName, person.LastName, person.Department); + person.PersonId, ctx.TermCode, person.FirstName, person.LastName, person.Department, effortPerson.ReportUnit); // Update progress ctx.InstructorsImported++; diff --git a/web/Areas/Effort/Services/IEffortAuditService.cs b/web/Areas/Effort/Services/IEffortAuditService.cs index b0c8cc3b6..d2962ebf1 100644 --- a/web/Areas/Effort/Services/IEffortAuditService.cs +++ b/web/Areas/Effort/Services/IEffortAuditService.cs @@ -64,7 +64,7 @@ Task LogTermChangeAsync(int termCode, string action, /// Add a harvest person created audit entry to the context without saving. /// Use this within a transaction where the caller manages SaveChangesAsync. /// - void AddHarvestPersonAudit(int personId, int termCode, string firstName, string lastName, string department); + void AddHarvestPersonAudit(int personId, int termCode, string firstName, string lastName, string department, string? reportUnit); /// /// Add a harvest course created audit entry to the context without saving. diff --git a/web/Areas/Effort/Services/IInstructorService.cs b/web/Areas/Effort/Services/IInstructorService.cs index 7e20d0fe3..706b8c7d1 100644 --- a/web/Areas/Effort/Services/IInstructorService.cs +++ b/web/Areas/Effort/Services/IInstructorService.cs @@ -185,4 +185,19 @@ public interface IInstructorService /// Dictionary mapping MothraID to resolved department code (at least "UNK"). Task> BatchResolveDepartmentsAsync( List mothraIds, int termCode, CancellationToken ct = default); + + /// + /// Whether the person has an AAUD job in the CAHFS department (072200) for the term. + /// + Task HasCahfsAppointmentAsync(string mothraId, int termCode, CancellationToken ct = default); + + /// + /// The subset of the given MothraIds with an AAUD job in the CAHFS department (072200) for the term. + /// + Task> GetCahfsMothraIdsAsync(IReadOnlyCollection mothraIds, int termCode, CancellationToken ct = default); + + /// + /// All MothraIds with an AAUD job in the CAHFS department (072200) for the term. + /// + Task> GetCahfsMothraIdsAsync(int termCode, CancellationToken ct = default); } diff --git a/web/Areas/Effort/Services/InstructorService.cs b/web/Areas/Effort/Services/InstructorService.cs index 78196df3e..cd944a1a4 100644 --- a/web/Areas/Effort/Services/InstructorService.cs +++ b/web/Areas/Effort/Services/InstructorService.cs @@ -483,7 +483,10 @@ public async Task CreateInstructorAsync(CreateInstructorRequest reque PercentAdmin = 0, PercentClinical = null, VolunteerWos = null, - ReportUnit = null, + ReportUnit = !string.IsNullOrEmpty(person.MothraId) + && await HasCahfsAppointmentAsync(person.MothraId, request.TermCode, ct) + ? EffortConstants.CahfsReportUnit + : null, Title = null, AdminUnit = null, EffortVerified = null @@ -502,7 +505,8 @@ public async Task CreateInstructorAsync(CreateInstructorRequest reque instructor.FirstName, instructor.LastName, instructor.EffortDept, - instructor.EffortTitleCode + instructor.EffortTitleCode, + instructor.ReportUnit }); await _context.SaveChangesAsync(ct); @@ -861,6 +865,39 @@ public async Task> BatchResolveDepartmentsAsync( return result; } + public async Task HasCahfsAppointmentAsync(string mothraId, int termCode, CancellationToken ct = default) + { + return (await GetCahfsMothraIdsAsync([mothraId], termCode, ct)).Count > 0; + } + + /// + public Task> GetCahfsMothraIdsAsync(IReadOnlyCollection mothraIds, int termCode, CancellationToken ct = default) + { + return QueryCahfsMothraIdsAsync(_aaudContext.Ids.Where(i => EF.Parameter(mothraIds).Contains(i.IdsMothraid!)), termCode, ct); + } + + /// + public Task> GetCahfsMothraIdsAsync(int termCode, CancellationToken ct = default) + { + return QueryCahfsMothraIdsAsync(_aaudContext.Ids, termCode, ct); + } + + private async Task> QueryCahfsMothraIdsAsync(IQueryable candidates, int termCode, CancellationToken ct) + { + var termCodeStr = termCode.ToString(); + var matches = await _aaudContext.Jobs + .AsNoTracking() + .Where(job => job.JobTermCode == termCodeStr && job.JobDepartmentCode == EffortConstants.CahfsDeptCode) + .Join( + candidates.Where(i => i.IdsTermCode == termCodeStr && i.IdsMothraid != null), + job => job.JobPKey, + ids => ids.IdsPKey, + (job, ids) => ids.IdsMothraid!) + .Distinct() + .ToListAsync(ct); + return matches.ToHashSet(StringComparer.OrdinalIgnoreCase); + } + /// /// Determine the effort department from AAUD data using pre-fetched job departments. /// Used by batch operations to avoid N+1 queries. From d8ebea56893096036bda657b3604d793e0dd50ab Mon Sep 17 00:00:00 2001 From: Rex Lorenzo Date: Mon, 2 Nov 2026 21:27:12 -0800 Subject: [PATCH 2/4] VPR-244 fix(effort): skip non-CREST effort for CRNs already in CREST - An R-course listed in CREST at 0 units but in Banner at 2 units was harvested twice, duplicating the director's effort record and failing the save on UQ_Records_Course_Person_EffortType - Unit variants are still imported as courses; effort comes from CREST - Regression from the VPR-104 variable-unit mapping --- test/Effort/HarvestServiceTests.cs | 121 ++++++++++++++---- .../Services/Harvest/NonCrestHarvestPhase.cs | 29 ++++- 2 files changed, 115 insertions(+), 35 deletions(-) diff --git a/test/Effort/HarvestServiceTests.cs b/test/Effort/HarvestServiceTests.cs index be1e13eef..df42633e9 100644 --- a/test/Effort/HarvestServiceTests.cs +++ b/test/Effort/HarvestServiceTests.cs @@ -221,6 +221,79 @@ public async Task GeneratePreviewAsync_CallsTermServiceForTermName() _termServiceMock.Received(1).GetTermName(TestTermCode); } + [Theory] + [InlineData(true, "00193236", 0)] + [InlineData(true, "00999999", 1)] + [InlineData(true, null, 1)] + [InlineData(false, "00193236", 1)] + [InlineData(false, null, 1)] + public async Task NonCrestPreview_CrnInCrestAtOtherUnits_KeepsCourseVariantButSkipsEffort(bool inCrest, string? crestEffortMothraId, int expectedEffort) + { + // Arrange: R-course whose CREST row has 0 units while Banner lists it at 2 units + const string crn = "90517"; + var termStr = TestTermCode.ToString(); + _coursesContext.Baseinfos.Add(new Models.Courses.Baseinfo + { + BaseinfoPkey = "BK1", + BaseinfoTermCode = termStr, + BaseinfoSubjCode = "IMM", + BaseinfoCrseNumb = "491R", + BaseinfoSeqNumb = "001", + BaseinfoCrn = crn, + BaseinfoTitle = "Research", + BaseinfoUnitType = "CR", + BaseinfoUnitLow = 2, + BaseinfoUnitHigh = 2, + BaseinfoCollCode = "VM", + BaseinfoDeptCode = "IMM", + BaseinfoXlistFlag = "N", + BaseinfoXlistGroup = "" + }); + _coursesContext.Poas.Add(new Models.Courses.Poa { PoaPkey = "P1", PoaTermCode = termStr, PoaCrn = crn, PoaPidm = "111" }); + _aaudContext.Ids.Add(new Models.AAUD.Id { IdsPKey = "PK1", IdsTermCode = termStr, IdsClientid = "C1", IdsMothraid = "00193236", IdsPidm = "111" }); + _aaudContext.Employees.Add(new Models.AAUD.Employee + { + EmpPKey = "PK1", + EmpTermCode = termStr, + EmpClientid = "C1", + EmpHomeDept = "072030", + EmpAltDeptCode = "", + EmpSchoolDivision = "VM", + EmpCbuc = "99", + EmpStatus = "A", + EmpEffortTitleCode = "001917" + }); + _aaudContext.People.Add(new Viper.Models.AAUD.Person { PersonPKey = "PK1", PersonTermCode = termStr, PersonClientid = "C1", PersonLastName = "Barter", PersonFirstName = "Linda" }); + _viperContext.People.Add(new Person { PersonId = 25756, ClientId = "C1", MothraId = "00193236", FirstName = "Linda", LastName = "Barter", FullName = "Barter, Linda" }); + _instructorServiceMock + .BatchResolveDepartmentsAsync(Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(new Dictionary { ["00193236"] = "VSR" }); + var ct = TestContext.Current.CancellationToken; + await _coursesContext.SaveChangesAsync(ct); + await _aaudContext.SaveChangesAsync(ct); + await _viperContext.SaveChangesAsync(ct); + + var context = CreateHarvestContext(); + if (inCrest) + { + context.Preview.CrestCourses.Add(new HarvestCoursePreview { Crn = crn, SubjCode = "IMM", CrseNumb = "491R", Units = 0 }); + } + if (crestEffortMothraId != null) + { + // Without inCrest this row has no importable CREST course, so it must not suppress POA effort + context.Preview.CrestEffort.Add(new HarvestRecordPreview { Crn = crn, MothraId = crestEffortMothraId, RoleId = EffortConstants.DirectorRoleId }); + } + + // Act + await new NonCrestHarvestPhase().GeneratePreviewAsync(context, ct); + + // Assert: the 2-unit variant is still imported as a course, but CREST owns the effort + // and the director still supplies the variant dept + Assert.Contains(context.Preview.NonCrestCourses, c => c.Crn == crn && c.Units == 2 && c.Source == EffortConstants.SourceNonCrest && c.CustDept == "VSR"); + Assert.Equal(expectedEffort, context.Preview.NonCrestEffort.Count); + Assert.Equal(expectedEffort, context.Preview.NonCrestInstructors.Count); + } + [Theory] [InlineData(false, null)] [InlineData(true, EffortConstants.CahfsReportUnit)] @@ -232,20 +305,7 @@ public async Task ImportPerson_SetsCahfsReportUnit_WhenPersonHasCahfsJob(bool ha _instructorServiceMock .GetCahfsMothraIdsAsync(TestTermCode, Arg.Any()) .Returns(cahfsIds); - var context = new HarvestContext - { - TermCode = TestTermCode, - EffortContext = _context, - CrestContext = _crestContext, - CoursesContext = _coursesContext, - ViperContext = _viperContext, - AaudContext = _aaudContext, - DictionaryContext = _dictionaryContext, - AuditService = _auditServiceMock, - InstructorService = _instructorServiceMock, - TermService = _termServiceMock, - Logger = _loggerMock - }; + var context = CreateHarvestContext(); context.Preview.NonCrestInstructors.Add(new HarvestPersonPreview { MothraId = "00193236", @@ -274,20 +334,7 @@ public async Task ImportPerson_LoadsCahfsIdsOnce_ForMultiplePeople() _instructorServiceMock .GetCahfsMothraIdsAsync(TestTermCode, Arg.Any()) .Returns(cahfsIds); - var context = new HarvestContext - { - TermCode = TestTermCode, - EffortContext = _context, - CrestContext = _crestContext, - CoursesContext = _coursesContext, - ViperContext = _viperContext, - AaudContext = _aaudContext, - DictionaryContext = _dictionaryContext, - AuditService = _auditServiceMock, - InstructorService = _instructorServiceMock, - TermService = _termServiceMock, - Logger = _loggerMock - }; + var context = CreateHarvestContext(); context.Preview.NonCrestInstructors.Add(new HarvestPersonPreview { MothraId = "00193236", PersonId = 25756, FirstName = "Linda", LastName = "Barter", Department = "VSR" }); context.Preview.NonCrestInstructors.Add(new HarvestPersonPreview { MothraId = "00999999", PersonId = 25757, FirstName = "Other", LastName = "Person", Department = "VSR" }); @@ -918,6 +965,24 @@ public void ApplyDirectorCustodialDeptFallback_InheritsDirectorDept_OnlyForNonAc Assert.Equal("UNK", courses[2].CustDept); // IOR dept not academic — unchanged } + /// + /// Creates a HarvestContext wired to the test contexts and mocks, for driving a phase directly. + /// + private HarvestContext CreateHarvestContext() => new() + { + TermCode = TestTermCode, + EffortContext = _context, + CrestContext = _crestContext, + CoursesContext = _coursesContext, + ViperContext = _viperContext, + AaudContext = _aaudContext, + DictionaryContext = _dictionaryContext, + AuditService = _auditServiceMock, + InstructorService = _instructorServiceMock, + TermService = _termServiceMock, + Logger = _loggerMock + }; + /// /// Creates a HarvestService that uses a single custom phase for testing. /// diff --git a/web/Areas/Effort/Services/Harvest/NonCrestHarvestPhase.cs b/web/Areas/Effort/Services/Harvest/NonCrestHarvestPhase.cs index 4fc9bd456..b790e773e 100644 --- a/web/Areas/Effort/Services/Harvest/NonCrestHarvestPhase.cs +++ b/web/Areas/Effort/Services/Harvest/NonCrestHarvestPhase.cs @@ -151,11 +151,18 @@ string ResolveCustDept(string subjCode, string deptCode, string crn) => }); } - // Get instructors and effort records + // Get instructors and effort records. Effort belongs to the CRN, not a unit + // variant, so a POA on a CRN that CREST already supplies effort for (at any units) + // only feeds the director dept fallback. + var crestCrns = context.Preview.CrestCourses.Select(c => c.Crn).ToHashSet(); + var crestEffortKeys = context.Preview.CrestEffort + .Where(e => crestCrns.Contains(e.Crn)) + .Select(e => (e.Crn, e.MothraId)) + .ToHashSet(); var courseData = allNonCrestCourses .Select(c => new NonCrestCourseData(c.Crn, c.SubjCode, c.CrseNumb)) .ToList(); - await BuildNonCrestInstructorsAndEffortAsync(context, courseData, ct); + await BuildNonCrestInstructorsAndEffortAsync(context, courseData, crestEffortKeys, ct); } /// @@ -216,6 +223,7 @@ public override async Task ExecuteAsync(HarvestContext context, CancellationToke private async Task BuildNonCrestInstructorsAndEffortAsync( HarvestContext context, List allNonCrestCourses, + HashSet<(string Crn, string MothraId)> crestEffortKeys, CancellationToken ct) { var termCodeStr = context.TermCode.ToString(); @@ -305,6 +313,7 @@ private async Task BuildNonCrestInstructorsAndEffortAsync( var excludedMothraIds = new HashSet(StringComparer.OrdinalIgnoreCase); var excludedInstructors = new List(); var addedInstructorMothraIds = new HashSet(StringComparer.OrdinalIgnoreCase); + var directorRows = new List(); foreach (var poa in poaEntries) { @@ -329,12 +338,13 @@ private async Task BuildNonCrestInstructorsAndEffortAsync( var dept = batchDepts.GetValueOrDefault(mothraId, "UNK"); var titleDesc = context.TitleLookup.TryGetValue(titleCode, out var desc) ? desc : titleCode; + var inCrest = crestEffortKeys.Contains((poa.PoaCrn, mothraId)); // Exclude emeritus/recall appointments from harvest (skips both the instructor // and the effort record built below). if (excludedTitleCodes.Contains(titleCode)) { - if (excludedMothraIds.Add(mothraId)) + if (!inCrest && excludedMothraIds.Add(mothraId)) { excludedInstructors.Add($"{fullName} ({titleDesc})"); } @@ -342,7 +352,7 @@ private async Task BuildNonCrestInstructorsAndEffortAsync( } // Add instructor if not already added - skip if no valid VIPER person record - if (!addedInstructorMothraIds.Contains(mothraId)) + if (!inCrest && !addedInstructorMothraIds.Contains(mothraId)) { if (!viperPersonLookup.TryGetValue(mothraId, out var personId)) { @@ -371,7 +381,7 @@ private async Task BuildNonCrestInstructorsAndEffortAsync( var isResearchCourse = course.CrseNumb?.EndsWith('R') ?? false; var effortType = isResearchCourse ? EffortConstants.ResearchEffortType : EffortConstants.VariableEffortType; - context.Preview.NonCrestEffort.Add(new HarvestRecordPreview + var effortRow = new HarvestRecordPreview { MothraId = mothraId, PersonName = fullName, @@ -383,7 +393,12 @@ private async Task BuildNonCrestInstructorsAndEffortAsync( Hours = 0, Weeks = null, Source = EffortConstants.SourceNonCrest - }); + }; + directorRows.Add(effortRow); + if (!inCrest) + { + context.Preview.NonCrestEffort.Add(effortRow); + } } AddEmeritusExclusionWarning(context, PhaseName, excludedInstructors); @@ -393,7 +408,7 @@ private async Task BuildNonCrestInstructorsAndEffortAsync( // inherit the custodial dept from its Director/IOR when that instructor's resolved // department is academic. Without this, such courses harvest as "UNK". ApplyDirectorCustodialDeptFallback( - context.Preview.NonCrestCourses, context.Preview.NonCrestEffort, batchDepts); + context.Preview.NonCrestCourses, directorRows, batchDepts); // Sort instructors var sortedInstructors = context.Preview.NonCrestInstructors.OrderBy(i => i.FullName).ToList(); From 75a04bb78035152148c61f6bcc4cd9f09d2283d5 Mon Sep 17 00:00:00 2001 From: Rex Lorenzo Date: Fri, 6 Nov 2026 10:32:18 -0800 Subject: [PATCH 3/4] VPR-244 fix(effort): make harvest totals match what is saved - Harvest results and the import audit counted the preview, omitting the generic R-course and any effort records skipped during import - Preview totals now include the R-course records the harvest will add --- test/Effort/HarvestServiceTests.cs | 129 ++++++++++++++++++++ web/Areas/Effort/Services/HarvestService.cs | 62 +++++++--- 2 files changed, 171 insertions(+), 20 deletions(-) diff --git a/test/Effort/HarvestServiceTests.cs b/test/Effort/HarvestServiceTests.cs index df42633e9..157fe0603 100644 --- a/test/Effort/HarvestServiceTests.cs +++ b/test/Effort/HarvestServiceTests.cs @@ -1,3 +1,4 @@ +using System.Threading.Channels; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.Logging; @@ -148,6 +149,51 @@ public void Dispose() #region GeneratePreviewAsync Tests + [Theory] + [InlineData(true, EffortConstants.VariableEffortType, false, 2, 5)] + [InlineData(true, EffortConstants.VariableEffortType, true, 2, 3)] + [InlineData(true, "LEC", false, 2, 3)] + [InlineData(false, EffortConstants.VariableEffortType, false, 1, 3)] + public async Task GeneratePreviewAsync_SummaryIncludesExpectedRCourses( + bool autoCreate, string effortTypeId, bool usesWeeks, int expectedCourses, int expectedRecords) + { + // Arrange: both instructors get the R-course, including 00000002 who only has R-course effort. + // Only an hour-based VAR yields records, whatever its Active/AllowedOnRCourses flags. + var ct = TestContext.Current.CancellationToken; + _context.EffortTypes.Add(new EffortType + { + Id = effortTypeId, + Description = effortTypeId, + UsesWeeks = usesWeeks, + AllowedOnRCourses = effortTypeId != EffortConstants.VariableEffortType, + IsActive = effortTypeId != EffortConstants.VariableEffortType + }); + await _context.SaveChangesAsync(ct); + + var service = new HarvestService( + new List { new PreviewEffortPhase() }, + _context, + _viperContext, + _coursesContext, + _crestContext, + _aaudContext, + _dictionaryContext, + _auditServiceMock, + _termServiceMock, + _instructorServiceMock, + _rCourseServiceMock, + _clinicalImportServiceMock, + Options.Create(new EffortSettings { AutoCreateGenericRCourse = autoCreate }), + _loggerMock); + + // Act + var result = await service.GeneratePreviewAsync(TestTermCode, ct); + + // Assert + Assert.Equal(expectedCourses, result.Summary.TotalCourses); + Assert.Equal(expectedRecords, result.Summary.TotalEffortRecords); + } + [Fact] public async Task GeneratePreviewAsync_WithNoData_ReturnsEmptyPreview() { @@ -889,6 +935,68 @@ await _rCourseServiceMock.Received(1).CreateForEligibleInstructorsAsync( Arg.Any()); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Harvest_SummaryCountsPersistedRows_IncludingGeneratedRCourse(bool withProgress) + { + // Arrange + var ct = TestContext.Current.CancellationToken; + _context.Terms.Add(new EffortTerm { TermCode = TestTermCode }); + _context.EffortTypes.Add(new EffortType { Id = "LEC", Description = "Lecture", AllowedOnRCourses = true, IsActive = true }); + await _context.SaveChangesAsync(ct); + + _rCourseServiceMock + .When(s => s.CreateForEligibleInstructorsAsync(TestTermCode, 123, RCourseCreationContext.Harvest, Arg.Any())) + .Do(_ => + { + var rCourse = new EffortCourse { TermCode = TestTermCode, Crn = "RESID", SubjCode = "RES", CrseNumb = "000R", SeqNumb = "001", CustDept = "" }; + _context.Courses.Add(rCourse); + _context.SaveChanges(); + _context.Records.Add(new EffortRecord { PersonId = 100, TermCode = TestTermCode, CourseId = rCourse.Id, EffortTypeId = "LEC", RoleId = 2, Crn = "RESID" }); + _context.SaveChanges(); + }); + + var service = new HarvestService( + new List { new TestDataHarvestPhase(_context, TestTermCode) }, + _context, + _viperContext, + _coursesContext, + _crestContext, + _aaudContext, + _dictionaryContext, + _auditServiceMock, + _termServiceMock, + _instructorServiceMock, + _rCourseServiceMock, + _clinicalImportServiceMock, + RCourseEnabledSettings, + _loggerMock); + + // Act + HarvestResultDto? result; + if (withProgress) + { + var channel = Channel.CreateUnbounded(); + await service.ExecuteHarvestWithProgressAsync(TestTermCode, 123, channel.Writer, ct); + var events = await channel.Reader.ReadAllAsync(ct).ToListAsync(ct); + Assert.Null(events.Find(e => e.Type == "error")?.Error); + result = events.Single(e => e.Type == "complete").Result; + } + else + { + result = await service.ExecuteHarvestAsync(TestTermCode, 123, ct); + } + + // Assert: the test phase adds 1 person, course and record; the R-course adds 1 course and record + Assert.NotNull(result); + Assert.Equal(1, result.Summary.TotalInstructors); + Assert.Equal(2, result.Summary.TotalCourses); + Assert.Equal(2, result.Summary.TotalEffortRecords); + _auditServiceMock.Received(1).AddImportAudit( + TestTermCode, Arg.Any(), "Harvested: 1 instructors, 2 courses, 2 effort records"); + } + [Fact] public async Task ExecuteHarvestAsync_DoesNotCallRCourseService_WhenAutoCreateDisabled() { @@ -1048,6 +1156,27 @@ public Task ExecuteAsync(HarvestContext context, CancellationToken ct = default) => Task.CompletedTask; } + private sealed class PreviewEffortPhase : IHarvestPhase + { + public int Order => 1; + public string PhaseName => "PreviewEffort"; + public bool ShouldExecute(int termCode) => true; + + public Task GeneratePreviewAsync(HarvestContext context, CancellationToken ct = default) + { + context.Preview.CrestInstructors.Add(new HarvestPersonPreview { MothraId = "00000001" }); + context.Preview.NonCrestInstructors.Add(new HarvestPersonPreview { MothraId = "00000002" }); + context.Preview.CrestCourses.Add(new HarvestCoursePreview { Crn = "12345", SubjCode = "VET", CrseNumb = "410", Units = 4 }); + context.Preview.CrestEffort.Add(new HarvestRecordPreview { MothraId = "00000001", CourseCode = "VET 410" }); + context.Preview.NonCrestEffort.Add(new HarvestRecordPreview { MothraId = "00000001", CourseCode = "VSR 491R" }); + context.Preview.NonCrestEffort.Add(new HarvestRecordPreview { MothraId = "00000002", CourseCode = "VSR 491R" }); + return Task.CompletedTask; + } + + public Task ExecuteAsync(HarvestContext context, CancellationToken ct = default) + => Task.CompletedTask; + } + /// /// Test helper phase that adds test data during harvest execution. /// This simulates a harvest phase creating courses and records. diff --git a/web/Areas/Effort/Services/HarvestService.cs b/web/Areas/Effort/Services/HarvestService.cs index dc71cfdb3..4c02c59f2 100644 --- a/web/Areas/Effort/Services/HarvestService.cs +++ b/web/Areas/Effort/Services/HarvestService.cs @@ -76,6 +76,7 @@ public async Task GeneratePreviewAsync(int termCode, Cancella // Calculate summary CalculateSummary(harvestContext); + await AddExpectedRCoursesToSummaryAsync(harvestContext, ct); // Detect existing and removed items await DetectExistingAndRemovedItemsAsync(harvestContext, ct); @@ -146,18 +147,16 @@ public async Task ExecuteHarvestAsync(int termCode, int modifi await UpdateTermStatusAsync(termCode, ct); // Add import audit - var summaryText = BuildSummaryText(harvestContext); + var summary = await GetPersistedSummaryAsync(termCode, ct); + var summaryText = BuildSummaryText(summary); _auditService.AddImportAudit(termCode, EffortAuditActions.ImportEffort, summaryText); await _context.SaveChangesAsync(ct); await transaction.CommitAsync(ct); - // Calculate summary for result - CalculateSummary(harvestContext); - result.Success = true; result.HarvestedDate = DateTime.Now; - result.Summary = harvestContext.Preview.Summary; + result.Summary = summary; result.Warnings = harvestContext.Warnings; _logger.LogInformation("Harvest completed for term {TermCode}: {Summary}", termCode, summaryText); @@ -298,20 +297,19 @@ await progressChannel.WriteAsync(new HarvestProgressEvent await progressChannel.WriteAsync(HarvestProgressEvent.Finalizing(), ct); await UpdateTermStatusAsync(termCode, ct); - var summaryText = BuildSummaryText(harvestContext); + var summary = await GetPersistedSummaryAsync(termCode, ct); + var summaryText = BuildSummaryText(summary); _auditService.AddImportAudit(termCode, EffortAuditActions.ImportEffort, summaryText); await _context.SaveChangesAsync(ct); await transaction.CommitAsync(ct); - CalculateSummary(harvestContext); - var result = new HarvestResultDto { TermCode = termCode, Success = true, HarvestedDate = DateTime.Now, - Summary = harvestContext.Preview.Summary, + Summary = summary, Warnings = harvestContext.Warnings }; @@ -491,21 +489,45 @@ private static void CalculateSummary(HarvestContext context) }; } - private static string BuildSummaryText(HarvestContext context) + // R-courses are generated after the import, so they have no preview rows. Mirrors + // IRCourseService.CreateForEligibleInstructorsAsync so the preview totals match the harvest. + private async Task AddExpectedRCoursesToSummaryAsync(HarvestContext context, CancellationToken ct) { - var allInstructors = GetAllInstructors(context.Preview) - .DistinctBy(p => p.MothraId) - .Count(); + if (!_settings.AutoCreateGenericRCourse) + { + return; + } + + // Harvest recreates every person unverified, so every instructor gets the R-course + var eligibleInstructors = context.Preview.Summary.TotalInstructors; + if (eligibleInstructors == 0) + { + return; + } - var allCourses = context.Preview.CrestCourses.Count + - context.Preview.NonCrestCourses.Count(c => c.Source != EffortConstants.SourceInCrest) + - context.Preview.ClinicalCourses.Count; + // The course is created even when VAR can't hold the placeholder record. + context.Preview.Summary.TotalCourses++; + if (await _context.EffortTypes.AsNoTracking() + .AnyAsync(t => t.Id == EffortConstants.VariableEffortType && !t.UsesWeeks, ct)) + { + context.Preview.Summary.TotalEffortRecords += eligibleInstructors; + } + } - var allEffort = context.Preview.CrestEffort.Count + - context.Preview.NonCrestEffort.Count + - context.Preview.ClinicalEffort.Count; + // Counts saved rows, not the preview, which excludes post-harvest R-courses and skipped records. + private async Task GetPersistedSummaryAsync(int termCode, CancellationToken ct) + { + return new HarvestSummary + { + TotalInstructors = await _context.Persons.AsNoTracking().CountAsync(p => p.TermCode == termCode, ct), + TotalCourses = await _context.Courses.AsNoTracking().CountAsync(c => c.TermCode == termCode, ct), + TotalEffortRecords = await _context.Records.AsNoTracking().CountAsync(r => r.TermCode == termCode, ct) + }; + } - return $"Harvested: {allInstructors} instructors, {allCourses} courses, {allEffort} effort records"; + private static string BuildSummaryText(HarvestSummary summary) + { + return $"Harvested: {summary.TotalInstructors} instructors, {summary.TotalCourses} courses, {summary.TotalEffortRecords} effort records"; } private async Task DetectExistingAndRemovedItemsAsync(HarvestContext context, CancellationToken ct) From 430947675aa8c275dfe8f6c3a491c5f5bd760530 Mon Sep 17 00:00:00 2001 From: Rex Lorenzo Date: Wed, 18 Nov 2026 09:47:43 -0800 Subject: [PATCH 4/4] VPR-244 feat(effort): find CAHFS instructors from PPS jobs first - AAUD has no term row for an inactive person (such as unpaid leave), so they missed the CAHFS report unit - Use current non-separated 072200 jobs in PPS, then add the AAUD term jobs as a backfill - PPS shows the job held now, so someone who joined CAHFS after the term is tagged too --- test/Effort/InstructorServiceTests.cs | 52 +++++++++++++++++++ web/Areas/Effort/Constants/EffortConstants.cs | 10 +++- .../Effort/Services/IInstructorService.cs | 6 +-- .../Effort/Services/InstructorService.cs | 46 +++++++++++++--- 4 files changed, 102 insertions(+), 12 deletions(-) diff --git a/test/Effort/InstructorServiceTests.cs b/test/Effort/InstructorServiceTests.cs index ff383ab33..d3c41ce1d 100644 --- a/test/Effort/InstructorServiceTests.cs +++ b/test/Effort/InstructorServiceTests.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using MockQueryable.NSubstitute; using NSubstitute; using Viper.Areas.Effort; using Viper.Areas.Effort.Constants; @@ -12,6 +13,7 @@ using Viper.Areas.Effort.Services; using Viper.Classes.SQLContext; using Viper.Models.AAUD; +using Viper.Models.PPS; using Person = Viper.Models.VIPER.Person; namespace Viper.test.Effort; @@ -24,6 +26,7 @@ public sealed class InstructorServiceTests : IDisposable private readonly EffortDbContext _context; private readonly VIPERContext _viperContext; private readonly AAUDContext _aaudContext; + private readonly PPSContext _ppsContext; private readonly DictionaryContext _dictionaryContext; private readonly IEffortAuditService _auditServiceMock; private readonly ICourseClassificationService _classificationServiceMock; @@ -57,6 +60,11 @@ public InstructorServiceTests() _context = new EffortDbContext(effortOptions); _viperContext = new VIPERContext(viperOptions); _aaudContext = new AAUDContext(aaudOptions); + // vw_personJobPosition is keyless, so the in-memory provider cannot seed it + _ppsContext = Substitute.ForPartsOf(new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) + .Options); + SetPpsJobs(); _dictionaryContext = new DictionaryContext(dictionaryOptions); _auditServiceMock = Substitute.For(); _classificationServiceMock = Substitute.For(); @@ -72,6 +80,7 @@ public InstructorServiceTests() _context, _viperContext, _aaudContext, + _ppsContext, _dictionaryContext, _auditServiceMock, _classificationServiceMock, @@ -82,11 +91,18 @@ public InstructorServiceTests() Options.Create(new EffortSettings { AutoCreateGenericRCourse = true })); } + private void SetPpsJobs(params VwPersonJobPosition[] jobs) + { + var jobSet = jobs.ToList().BuildMockDbSet(); + _ppsContext.VwPersonJobPositions.Returns(jobSet); + } + public void Dispose() { _context.Dispose(); _viperContext.Dispose(); _aaudContext.Dispose(); + _ppsContext.Dispose(); _dictionaryContext.Dispose(); _cache.Dispose(); } @@ -847,6 +863,42 @@ public async Task HasCahfsAppointmentAsync_MatchesCahfsJobForTerm(string jobDept Assert.Equal(expected, termIds.Contains("22220000")); } + [Theory] + [InlineData("072200", "Active", "10000001", true)] + [InlineData("072200", "Inactive", "10000001", true)] // on leave + [InlineData("072200", "Separated", "10000001", false)] + [InlineData("072030", "Active", "10000001", false)] + [InlineData("072200", "Active", "19999999", false)] // employee ID with no AAUD user + public async Task HasCahfsAppointmentAsync_MatchesCurrentPpsJob_WithoutAaudTermRow(string jobDept, string jobStatus, string userEmployeeId, bool expected) + { + // Arrange - no AAUD ids/jobs rows for the term, as for someone on unpaid leave + _aaudContext.AaudUsers.Add(new AaudUser + { + MothraId = "22220000", + EmployeeId = userEmployeeId, + ClientId = "22220000", + LoginId = "cahfsuser", + FirstName = "Cahfs", + LastName = "User", + DisplayFirstName = "Cahfs", + DisplayLastName = "User", + DisplayFullName = "User, Cahfs", + Current = 1 + }); + await _aaudContext.SaveChangesAsync(TestContext.Current.CancellationToken); + SetPpsJobs(new VwPersonJobPosition { Emplid = "10000001", Deptid = jobDept, JobStatus1 = jobStatus }); + + // Act + var result = await _instructorService.HasCahfsAppointmentAsync("22220000", 202410, TestContext.Current.CancellationToken); + var termIds = await _instructorService.GetCahfsMothraIdsAsync(202410, TestContext.Current.CancellationToken); + var otherPerson = await _instructorService.GetCahfsMothraIdsAsync(["33330000"], 202410, TestContext.Current.CancellationToken); + + // Assert + Assert.Equal(expected, result); + Assert.Equal(expected, termIds.Contains("22220000")); + Assert.Empty(otherPerson); + } + #endregion #region PersonDto Mapping Tests diff --git a/web/Areas/Effort/Constants/EffortConstants.cs b/web/Areas/Effort/Constants/EffortConstants.cs index 2acb8522c..54ddeb9c1 100644 --- a/web/Areas/Effort/Constants/EffortConstants.cs +++ b/web/Areas/Effort/Constants/EffortConstants.cs @@ -114,11 +114,17 @@ public static double ToStoredPercent(decimal displayValue) public const string ClinicalCustodialDept = "DVM"; /// - /// AAUD department code for CAHFS. Harvested instructors with a job in this - /// department get the CAHFS report unit. + /// Department code for CAHFS, the same in PPS and AAUD. Harvested instructors + /// with a job in this department get the CAHFS report unit. /// public const string CahfsDeptCode = "072200"; + /// + /// PPS vw_personJobPosition.JobStatus for a job that has ended (terminated, + /// retired, deceased). The other values are Active and Inactive (on leave). + /// + public const string PpsSeparatedJobStatus = "Separated"; + /// /// Report unit code for CAHFS (effort.ReportUnits.UnitCode). /// diff --git a/web/Areas/Effort/Services/IInstructorService.cs b/web/Areas/Effort/Services/IInstructorService.cs index 706b8c7d1..3a0d8ebbe 100644 --- a/web/Areas/Effort/Services/IInstructorService.cs +++ b/web/Areas/Effort/Services/IInstructorService.cs @@ -187,17 +187,17 @@ Task> BatchResolveDepartmentsAsync( List mothraIds, int termCode, CancellationToken ct = default); /// - /// Whether the person has an AAUD job in the CAHFS department (072200) for the term. + /// Whether the person has a current PPS job, or an AAUD job for the term, in the CAHFS department (072200). /// Task HasCahfsAppointmentAsync(string mothraId, int termCode, CancellationToken ct = default); /// - /// The subset of the given MothraIds with an AAUD job in the CAHFS department (072200) for the term. + /// The subset of the given MothraIds with a current PPS job, or an AAUD job for the term, in the CAHFS department (072200). /// Task> GetCahfsMothraIdsAsync(IReadOnlyCollection mothraIds, int termCode, CancellationToken ct = default); /// - /// All MothraIds with an AAUD job in the CAHFS department (072200) for the term. + /// All MothraIds with a current PPS job, or an AAUD job for the term, in the CAHFS department (072200). /// Task> GetCahfsMothraIdsAsync(int termCode, CancellationToken ct = default); } diff --git a/web/Areas/Effort/Services/InstructorService.cs b/web/Areas/Effort/Services/InstructorService.cs index cd944a1a4..b31a473e2 100644 --- a/web/Areas/Effort/Services/InstructorService.cs +++ b/web/Areas/Effort/Services/InstructorService.cs @@ -22,6 +22,7 @@ public class InstructorService : IInstructorService private readonly EffortDbContext _context; private readonly VIPERContext _viperContext; private readonly AAUDContext _aaudContext; + private readonly PPSContext _ppsContext; private readonly DictionaryContext _dictionaryContext; private readonly IEffortAuditService _auditService; private readonly ICourseClassificationService _classificationService; @@ -77,6 +78,7 @@ public InstructorService( EffortDbContext context, VIPERContext viperContext, AAUDContext aaudContext, + PPSContext ppsContext, DictionaryContext dictionaryContext, IEffortAuditService auditService, ICourseClassificationService classificationService, @@ -89,6 +91,7 @@ public InstructorService( _context = context; _viperContext = viperContext; _aaudContext = aaudContext; + _ppsContext = ppsContext; _dictionaryContext = dictionaryContext; _auditService = auditService; _classificationService = classificationService; @@ -873,29 +876,58 @@ public async Task HasCahfsAppointmentAsync(string mothraId, int termCode, /// public Task> GetCahfsMothraIdsAsync(IReadOnlyCollection mothraIds, int termCode, CancellationToken ct = default) { - return QueryCahfsMothraIdsAsync(_aaudContext.Ids.Where(i => EF.Parameter(mothraIds).Contains(i.IdsMothraid!)), termCode, ct); + return QueryCahfsMothraIdsAsync(mothraIds, termCode, ct); } /// public Task> GetCahfsMothraIdsAsync(int termCode, CancellationToken ct = default) { - return QueryCahfsMothraIdsAsync(_aaudContext.Ids, termCode, ct); + return QueryCahfsMothraIdsAsync(null, termCode, ct); } - private async Task> QueryCahfsMothraIdsAsync(IQueryable candidates, int termCode, CancellationToken ct) + // mothraIds limits the result to those people; null means everyone. + private async Task> QueryCahfsMothraIdsAsync(IReadOnlyCollection? mothraIds, int termCode, CancellationToken ct) { + // PPS first: AAUD has no term row for an inactive person (e.g. on unpaid leave). + // This is the job held now, not during the term, so someone who joined CAHFS after + // the term is tagged too and someone who has since separated is left to AAUD below. + var cahfsEmplIds = await _ppsContext.VwPersonJobPositions + .AsNoTracking() + .Where(p => p.Deptid == EffortConstants.CahfsDeptCode + && p.JobStatus1 != EffortConstants.PpsSeparatedJobStatus + && p.Emplid != null) + .Select(p => p.Emplid!) + .Distinct() + .ToListAsync(ct); + + var ppsUsers = _aaudContext.AaudUsers + .AsNoTracking() + .Where(u => u.EmployeeId != null && EF.Parameter(cahfsEmplIds).Contains(u.EmployeeId)); + if (mothraIds != null) + { + ppsUsers = ppsUsers.Where(u => EF.Parameter(mothraIds).Contains(u.MothraId)); + } + var result = (await ppsUsers.Select(u => u.MothraId).ToListAsync(ct)) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + // Backfill from the AAUD jobs loaded for the term var termCodeStr = termCode.ToString(); - var matches = await _aaudContext.Jobs + var candidates = _aaudContext.Ids.Where(i => i.IdsTermCode == termCodeStr && i.IdsMothraid != null); + if (mothraIds != null) + { + candidates = candidates.Where(i => EF.Parameter(mothraIds).Contains(i.IdsMothraid!)); + } + result.UnionWith(await _aaudContext.Jobs .AsNoTracking() .Where(job => job.JobTermCode == termCodeStr && job.JobDepartmentCode == EffortConstants.CahfsDeptCode) .Join( - candidates.Where(i => i.IdsTermCode == termCodeStr && i.IdsMothraid != null), + candidates, job => job.JobPKey, ids => ids.IdsPKey, (job, ids) => ids.IdsMothraid!) .Distinct() - .ToListAsync(ct); - return matches.ToHashSet(StringComparer.OrdinalIgnoreCase); + .ToListAsync(ct)); + return result; } ///