Skip to content

LNK-4303: add event date - #1239

Merged
edward-miller-lcg merged 7 commits into
devfrom
LNK-4303-add-event-date
Nov 7, 2025
Merged

LNK-4303: add event date#1239
edward-miller-lcg merged 7 commits into
devfrom
LNK-4303-add-event-date

Conversation

@edward-miller-lcg

@edward-miller-lcg edward-miller-lcg commented Nov 6, 2025

Copy link
Copy Markdown
Contributor

🛠️ Description of Changes

Add EventDate column to PatientEvents to simplify querying when the need to evaluate an admit or discharge date. Update integration test for bad assertion. Update migration to backfill EventDates based on admit or discharge dates.

🧪 Testing Performed

Local testing and integration testing.

🧑‍🔬 Unit Testing

  • I have written or updated unit tests to cover my changes

📓 Documentation Updated

n/a

Summary by CodeRabbit

  • New Features

    • Patient events now capture and track actual event dates based on admission or discharge timing.
  • Improvements

    • Updated event queries to sort and filter by actual event dates rather than creation timestamps, ensuring accurate chronological ordering and reporting of patient encounters.
  • Tests

    • Test data adjusted to validate updated event date handling.

* add EventDate field to PatientEvent
* update PatientEventQueries for new field to simplify querying
* update integration tests
* update migration to set EventDate to payload value for existing records.
@coderabbitai

coderabbitai Bot commented Nov 6, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This PR adds an EventDate property to the PatientEvent entity to track event timing from payload data. Factory logic extracts discharge/admit dates from FHIR payloads, queries replace CreateDate/ModifyDate with EventDate for filtering and sorting, and EF Core migrations add the column with data migration logic and indexing.

Changes

Cohort / File(s) Summary
Entity and Schema Updates
DotNet/Census/Domain/Entities/POI/PatientEvent.cs, DotNet/Census/Domain/Context/CensusContext.cs
Adds DateTime EventDate property to PatientEvent entity; establishes one-to-many PatientEncounterPatientIdentifier relationship and creates index IX_PatientEvents_EventDate.
Factory Logic
DotNet/Census/Application/Factories/PatientEventFactory.cs
Introduces GetEventDate() helper method using pattern matching to extract EventDate from FHIR payloads (discharge date, admit date, or UtcNow fallback); assigns to newly created PatientEvent.
Query Updates
DotNet/Census/Domain/Queries/PatientEventQueries.cs, DotNet/Census/Domain/Queries/PatientEncounterQueries.cs
Replaces CreateDate/ModifyDate with EventDate across all date filtering, ordering, and event grouping logic; adjusts admit date assignments in encounter creation flow.
Unused Dependencies
DotNet/Census/Domain/Managers/PatientEventManager.cs
Removes unused LantanaGroup.Link.Shared.Application.Services using directive.
EF Core Migrations
DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.cs, DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.Designer.cs
Introduces migration to add nullable EventDate column (datetime2) with SQL logic to populate from payload dates or fallback to CreateDate; creates index and enforces NOT NULL constraint.
Model Snapshot
DotNet/Census/Migrations/CensusContextModelSnapshot.cs
Updates namespace formatting; adds [DbContext] attribute to class signature; expands BuildModel() with comprehensive Quartz (QRTZ_*) and Census entity mappings, relationships, and indexes.
Test Updates
DotNet/ServiceTests/IntegrationTests/Census/QueryTests.cs
Comments out discharge event creation in GetAdmittedPatientEventModelsByDateRange test, leaving only admit events in the test dataset.

Sequence Diagram

sequenceDiagram
    participant Factory as PatientEventFactory
    participant Payload as FHIR Payload
    participant Event as PatientEvent
    participant DB as Database
    
    Factory->>Payload: Extract event type
    alt Discharge Event
        Factory->>Payload: Get DischargeDate
    else Admit Event
        Factory->>Payload: Get AdmitDate
    else Other Event
        Factory->>Factory: Use DateTime.UtcNow
    end
    
    Factory->>Event: Assign EventDate
    Event->>DB: Persist with EventDate
    DB->>DB: Index on EventDate
    
    Note over Factory,DB: Query phase uses EventDate<br/>for filtering and sorting
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Pattern consistency: Straightforward replacement of CreateDate/ModifyDate with EventDate across query methods; pattern is repeated but consistent.
  • Migration complexity: Data migration logic with conditional SQL extraction from JSON payloads requires careful validation of edge cases and null handling.
  • Model snapshot: Comprehensive rewrite with extensive Quartz entity mappings and relationship definitions; requires verification that all entities and constraints are correctly preserved.
  • Specific areas needing attention:
    • SQL migration logic in 20251106152644_AddEventDateToPatientEvent.cs for payload date extraction correctness
    • Verify all query method changes in PatientEventQueries.cs and PatientEncounterQueries.cs maintain expected filtering boundaries
    • Confirm model snapshot BuildModel() Quartz and Census entity mappings are complete and correct
    • Ensure test comment in QueryTests.cs aligns with intended test behavior or add explanation

Possibly related PRs

Suggested reviewers

  • seanmcilvenna
  • smailliwcs
  • arianamihailescu
  • nvmLantana

Poem

🐰 A hare hops through events with dates so clear,
No more CreateDate confusion here!
EventDate shines from payload deep,
Migrations sorted, queries leap.
The census grows chronologically neat!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Linked Issues check ❓ Inconclusive The PR partially addresses LNK-4303 objectives by implementing EventDate for simplified querying but does not address legacy table removal or API endpoint fixes mentioned in the issue. Clarify whether the EventDate addition is the only required change for LNK-4303 or if additional work on table removal and API endpoints is expected in this PR.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'LNK-4303: add event date' clearly and concisely summarizes the main change: adding an EventDate field to PatientEvents for simplified querying.
Description check ✅ Passed The pull request description includes all required sections from the template with appropriate content covering changes, testing performed, and documentation status.
Out of Scope Changes check ✅ Passed Changes are focused on adding EventDate functionality and related database migrations; however, test modifications and some namespace/formatting changes appear incidental to the core objective.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
DotNet/Census/Domain/Queries/PatientEncounterQueries.cs (1)

254-334: Process correlation groups in EventDate order.

Inside the rebuild loop we still iterate correlationGroup.OrderBy(e => e.ModifyDate). This defeats the earlier change to sort by EventDate: a discharge ingested later (ModifyDate newer) but representing an earlier clinical time will still execute before its admit event, so the discharge update is skipped and the encounter remains open. Please switch the per-correlation ordering to EventDate so the rebuild truly replays events chronologically.

🧹 Nitpick comments (1)
DotNet/ServiceTests/IntegrationTests/Census/QueryTests.cs (1)

291-294: Keep the discharge event and assert the new EventDate behavior

Commenting out the discharge event makes the dataset less realistic and stops us from exercising the branch where a patient’s latest event is a discharge. With the EventDate ordering now in play, we should leave that discharge record in place and update the expectations so the test proves we exclude patients once they’ve been discharged. Suggested change:

-        // Within date range, discharge event, patient 1 (latest for patient 1)
-        //var dischargeCorrelationId1 = Guid.NewGuid().ToString();
-        //var patient1DischargePayload = new FHIRListDischargePayload(patientId1, DateTime.UtcNow.AddDays(-1));
-        //var patient1DischargeEvent = patient1DischargePayload.CreatePatientEvent(facilityId, dischargeCorrelationId1);
-        //events.Add(patient1DischargeEvent);
+        // Within date range, discharge event, patient 1 (latest for patient 1)
+        var dischargeCorrelationId1 = Guid.NewGuid().ToString();
+        var patient1DischargePayload = new FHIRListDischargePayload(patientId1, DateTime.UtcNow.AddDays(-1));
+        var patient1DischargeEvent = patient1DischargePayload.CreatePatientEvent(facilityId, dischargeCorrelationId1);
+        events.Add(patient1DischargeEvent);
...
-        // Should return 2 events (latest events for each patient within the date range)
-        Assert.Equal(2, results?.Count() ?? 0);
-
-        // Verify both admitted patients are in the results
-        Assert.Contains(results, e => e.SourcePatientId == patientId1);
-        Assert.Contains(results, e => e.SourcePatientId == patientId2);
+        // Should return only the patient whose latest event in-range is still an admit
+        Assert.Single(results);
+
+        Assert.DoesNotContain(results, e => e.SourcePatientId == patientId1);
+        Assert.Contains(results, e => e.SourcePatientId == patientId2);
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 53bdfa6 and 6a4be58.

📒 Files selected for processing (10)
  • DotNet/Census/Application/Factories/PatientEventFactory.cs (2 hunks)
  • DotNet/Census/Domain/Context/CensusContext.cs (2 hunks)
  • DotNet/Census/Domain/Entities/POI/PatientEvent.cs (1 hunks)
  • DotNet/Census/Domain/Managers/PatientEventManager.cs (0 hunks)
  • DotNet/Census/Domain/Queries/PatientEncounterQueries.cs (3 hunks)
  • DotNet/Census/Domain/Queries/PatientEventQueries.cs (5 hunks)
  • DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.Designer.cs (1 hunks)
  • DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.cs (1 hunks)
  • DotNet/Census/Migrations/CensusContextModelSnapshot.cs (1 hunks)
  • DotNet/ServiceTests/IntegrationTests/Census/QueryTests.cs (1 hunks)
💤 Files with no reviewable changes (1)
  • DotNet/Census/Domain/Managers/PatientEventManager.cs
🧰 Additional context used
📓 Path-based instructions (2)
**/*.cs

⚙️ CodeRabbit configuration file

**/*.cs: The HtmlInputSanitizer class's Sanitize() and SanitizeAndRemove() methods should be used when dealing with string query parameters from REST requests.

Files:

  • DotNet/Census/Application/Factories/PatientEventFactory.cs
  • DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.cs
  • DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.Designer.cs
  • DotNet/Census/Domain/Context/CensusContext.cs
  • DotNet/ServiceTests/IntegrationTests/Census/QueryTests.cs
  • DotNet/Census/Domain/Entities/POI/PatientEvent.cs
  • DotNet/Census/Domain/Queries/PatientEventQueries.cs
  • DotNet/Census/Domain/Queries/PatientEncounterQueries.cs
  • DotNet/Census/Migrations/CensusContextModelSnapshot.cs
**

⚙️ CodeRabbit configuration file

**: Pull requests that have "TECH_DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates,
and logging improvements. These TECH_DEBT PRs must not affect core functionality. All PRs that are not considered technical debt must include information on what
testing was performed in the description of the PR. If it does not, ask the author to provide details on what testing was performed.
When reviewing code, suggest unit tests using XUnit in the following scenarios:

  • If/Else or Switch/Case blocks are introduced or modified — ensure each branch has a corresponding unit test.
  • Logic that depends on service or interface configuration — suggest tests to validate different implementations are correctly resolved.
  • No network activity (HTTP calls, sockets, etc.) should appear in unit tests. Recommend using mocks (via Moq) for any external communication.
    Large unit tests should be avoided; keeping unit tests small and focused on targeted business logic (i.e. string sanitization)

**: Pull requests that have DOCS in the title should only contain changes related to documentation within the /docs folder or in .md files through-out the code-base. The description
of the PR should specify what documentation was updated. Documentation updates should use EventCatalog.dev structure, where service-specific functionality should be described
in the service's index.mdx (i.e. /services/XXX/index.mdx or /domains/XXX/services/YYY/index.mdx). Configurations that are shared by multiple services should be
reflected in the /docs/docs/config files.

Files:

  • DotNet/Census/Application/Factories/PatientEventFactory.cs
  • DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.cs
  • DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.Designer.cs
  • DotNet/Census/Domain/Context/CensusContext.cs
  • DotNet/ServiceTests/IntegrationTests/Census/QueryTests.cs
  • DotNet/Census/Domain/Entities/POI/PatientEvent.cs
  • DotNet/Census/Domain/Queries/PatientEventQueries.cs
  • DotNet/Census/Domain/Queries/PatientEncounterQueries.cs
  • DotNet/Census/Migrations/CensusContextModelSnapshot.cs
🧠 Learnings (4)
📓 Common learnings
Learnt from: edward-miller-lcg
Repo: lantanagroup/link-cloud PR: 1095
File: Tests/BackendE2ETests/ApiRequests/SubmissionZipReader.cs:235-297
Timestamp: 2025-09-10T03:18:32.895Z
Learning: User edward-miller-lcg prefers minimal logging in test scenarios and considers frequent progress updates during polling loops to be "too noisy" for test output.
📚 Learning: 2025-01-22T17:06:33.481Z
Learnt from: edward-miller-lcg
Repo: lantanagroup/link-cloud PR: 615
File: DotNet/DataAcquisition.Domain/Migrations/20241204194556_Init.Designer.cs:202-247
Timestamp: 2025-01-22T17:06:33.481Z
Learning: Entity Framework Core migration designer files (*.Designer.cs) are auto-generated by the EF Core CLI and should never be manually edited. Changes to the database schema should be made by modifying the entity classes and creating new migrations.

Applied to files:

  • DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.Designer.cs
  • DotNet/Census/Migrations/CensusContextModelSnapshot.cs
📚 Learning: 2025-01-22T17:07:51.015Z
Learnt from: edward-miller-lcg
Repo: lantanagroup/link-cloud PR: 615
File: DotNet/DataAcquisition.Domain/Migrations/20241204194556_Init.Designer.cs:59-88
Timestamp: 2025-01-22T17:07:51.015Z
Learning: Skip reviewing auto-generated Entity Framework Core migration files (*.Designer.cs) as they are generated automatically and should not be manually modified. Schema changes should be made in the entity model classes instead.

Applied to files:

  • DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.Designer.cs
  • DotNet/Census/Migrations/CensusContextModelSnapshot.cs
📚 Learning: 2025-06-26T20:07:57.494Z
Learnt from: edward-miller-lcg
Repo: lantanagroup/link-cloud PR: 929
File: DotNet/DataAcquisitionTests/ServiceTests/PatientDataServiceTests.cs:337-454
Timestamp: 2025-06-26T20:07:57.494Z
Learning: In the `CreateLogEntries` method of `PatientDataService`, when `IQueryListProcessor.Process` throws a `ProduceException<string, ResourceAcquired>`, the exception is rethrown directly without being wrapped in a `TransientException`. The test should validate the original `ProduceException` being thrown.

Applied to files:

  • DotNet/ServiceTests/IntegrationTests/Census/QueryTests.cs
🧬 Code graph analysis (6)
DotNet/Census/Application/Factories/PatientEventFactory.cs (3)
DotNet/ServiceTests/IntegrationTests/Census/QueryTests.cs (1)
  • DateTime (345-354)
DotNet/Census/Domain/Converters/PayloadJsonConverter.cs (1)
  • IPayload (24-88)
DotNet/Census/Application/Models/Payloads/Fhir/List/FhirListAdmitPayload.cs (1)
  • FHIRListAdmitPayload (12-43)
DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.cs (2)
DotNet/Census/Application/Factories/PatientEventFactory.cs (1)
  • DateTime (27-35)
DotNet/ServiceTests/IntegrationTests/Census/QueryTests.cs (1)
  • DateTime (345-354)
DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.Designer.cs (5)
DotNet/Census/Migrations/CensusContextModelSnapshot.cs (1)
  • DbContext (13-884)
DotNet/Census/Domain/Context/CensusContext.cs (3)
  • CensusContext (11-153)
  • CensusContext (19-21)
  • CensusContext (23-25)
DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.cs (1)
  • AddEventDateToPatientEvent (9-71)
DotNet/Census/Application/Factories/PatientEventFactory.cs (1)
  • DateTime (27-35)
DotNet/ServiceTests/IntegrationTests/Census/QueryTests.cs (1)
  • DateTime (345-354)
DotNet/Census/Domain/Context/CensusContext.cs (1)
DotNet/Census/Application/Factories/PatientEventFactory.cs (1)
  • PatientEvent (10-25)
DotNet/Census/Domain/Entities/POI/PatientEvent.cs (2)
DotNet/Census/Application/Factories/PatientEventFactory.cs (1)
  • DateTime (27-35)
DotNet/ServiceTests/IntegrationTests/Census/QueryTests.cs (1)
  • DateTime (345-354)
DotNet/Census/Migrations/CensusContextModelSnapshot.cs (2)
DotNet/Census/Migrations/20251106152644_AddEventDateToPatientEvent.Designer.cs (1)
  • DbContext (14-887)
DotNet/Census/Domain/Context/CensusContext.cs (3)
  • CensusContext (11-153)
  • CensusContext (19-21)
  • CensusContext (23-25)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Unit Tests for Java
  • GitHub Check: Unit Tests for DotNet
  • GitHub Check: Smoke Test with Docker Compose
  • GitHub Check: Integration Tests
  • GitHub Check: Analyze (csharp)
  • GitHub Check: Analyze (java-kotlin)
🔇 Additional comments (1)
DotNet/Census/Application/Factories/PatientEventFactory.cs (1)

27-34: Add targeted unit tests for GetEventDate.

The new switch expression introduces multiple branches (admit, discharge, fallback). Per our test guidelines, please add focused XUnit coverage to prove each branch returns the expected date (including a non-FHIR payload/null case). This will guard against regressions if additional payload types appear later.

Comment thread DotNet/Census/Application/Factories/PatientEventFactory.cs Outdated
@edward-miller-lcg
edward-miller-lcg merged commit cc98929 into dev Nov 7, 2025
16 checks passed
@edward-miller-lcg
edward-miller-lcg deleted the LNK-4303-add-event-date branch November 7, 2025 18:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants