feature: Corrections and Supersession

This commit is contained in:
voltsrage
2026-06-26 16:33:31 +08:00
parent 706318e5d2
commit f232761fd7
35 changed files with 4907 additions and 75 deletions
+168 -17
View File
@@ -1,8 +1,8 @@
# VigilCare Records API
A clinical records intake backend built with ASP.NET Core 8, PostgreSQL, MinIO, and Redis. The domain models the scan-to-approved lifecycle at the center of any paper chart digitization system: scanned document upload, human data entry, dual-human verification with separation of duties, site-configurable clinical approval routing, and batch status machine enforcement.
A clinical records intake backend built with ASP.NET Core 8, PostgreSQL, MinIO, and Redis. The domain models the scan-to-approved lifecycle at the center of any paper chart digitization system: scanned document upload, human data entry, dual-human verification with separation of duties, site-configurable clinical approval routing, atomic promotion to live clinical tables, and governed correction via supersession.
**Implementation status:** Three planned phases are complete through Phase 3 — from schema, authentication, and batch CRUD through draft data entry and verification/rejection with separation of duties and work queues. See [Implemented Phases](#implemented-phases) for the full breakdown.
**Implementation status:** Five planned phases are complete through Phase 5 — from schema, authentication, and batch CRUD through draft data entry, verification/rejection with separation of duties, approval with atomic promotion to VigilCareClinical live tables, and correction batches that supersede erroneous promoted observations without silent edits. See [Implemented Phases](#implemented-phases) for the full breakdown.
## Domain Model — How It Maps to a Real Clinical System
@@ -45,12 +45,16 @@ Append-only audit log entry for every state transition, field-level correction,
## Features
- **Document Upload and Batch Creation** — multipart upload (PDF, JPEG, PNG; max 25 MB) with MinIO storage, SHA-256 integrity hash, presigned GET URLs (15-minute expiry); duplicate detection per patient within 24 hours by SHA-256 (`409 DUPLICATE_DOCUMENT`); cross-patient duplicate scans allowed; batch created in `UPLOADED` status with `DigitizationEvent` audit trail
- **Document Upload and Batch Creation** — multipart upload (PDF, JPEG, PNG; max 25 MB) with MinIO storage, SHA-256 integrity hash, presigned GET URLs (15-minute expiry); duplicate detection per patient within 24 hours by SHA-256 (`409 DUPLICATE_DOCUMENT`); cross-patient duplicate scans allowed; optional `supersedesBatchId` creates a correction batch linked to a promoted batch; batch created in `UPLOADED` status with `DigitizationEvent` audit trail
- **Batch Assignment** — `PATCH /digitization-batches/:id/assign` assigns an entry clerk with a Redis lock (`SET batch:assign:{id} NX EX 3600`) to prevent double-assignment; `409 BATCH_ALREADY_ASSIGNED` on conflict
- **Draft Data Entry** — full CRUD on draft payload: upsert patient demographics, upsert encounter context, add/edit/delete observation rows; plausibility validation on observation values at draft save time (catches decimal errors before verification); automatic `UPLOADED → IN_ENTRY` transition on first save; draft save requires the acting user to match `enteredByUserId` or hold `Administrator` role (`409 BATCH_NOT_ASSIGNED`)
- **Submit for Verification** — validates completeness per batch type (e.g. vitals sheet requires linked patient, encounter context, and at least one observation with `recordedAt`); transitions `IN_ENTRY → PENDING_VERIFICATION`; returns `422` with missing fields if incomplete
- **Verification and Rejection** — verifier reviews entry against the scan with field-level checks (`fieldName`, `status: ok|warning|error`, optional `note`); verify pass transitions to `VERIFIED` or `AWAITING_CLINICAL_APPROVAL` based on site configuration for the batch type; verify fail transitions to `REJECTED` with mandatory reason; **separation of duties** enforced: entry clerk cannot verify their own batch (`409 SEPARATION_OF_DUTIES_VIOLATION`)
- **Clinical Approval Routing** — site-configurable per batch type (`SiteConfig.ClinicalApprovalRequired`); high-stakes batch types (encounter summary, vitals sheet, lab results, medication list, mixed) route to `AWAITING_CLINICAL_APPROVAL` after verification for physician sign-off; low-stakes types (patient registration, allergy update) go directly to `VERIFIED`
- **Approval and Promotion** — `POST /digitization-batches/:id/approve` atomically promotes draft data to live VigilCareClinical tables (`patients`, `encounters`, `observations`) in a single PostgreSQL transaction; generates MRN via PostgreSQL sequence (`VCR-000001`); patient deduplication by name + DOB; encounter matching by patient + department + active status; writes `observation.created` outbox events for downstream consumers; separation of duties enforced (approver cannot be entry clerk or verifier); `Idempotency-Key` header required for safe retries with 24-hour TTL; retroactive alert policy (`enableRetroactiveAlerts`) controls whether backfill observations emit outbox events
- **Promotion Result Query** — `GET /digitization-batches/:id/promotion-result` returns live entity IDs (patient, MRN, encounter, observations) created during promotion
- **Corrections and Supersession** — approved live observations are never silently edited; a correction uploads a new batch with `supersedesBatchId`, goes through the full entry → verify → approve cycle, and on promotion marks the original batch's `live_observations` rows as `is_superseded` (append-only — never deleted); `422 SUPERSEDED_BATCH_NOT_PROMOTED`, `409 BATCH_ALREADY_SUPERSEDED`, and `404 SUPERSEDED_BATCH_NOT_FOUND` guard invalid supersession targets; correction batches inherit patient context and reuse the original promotion encounter
- **Patient Digitization History** — `GET /patients/:id/digitization-history` returns all batches for a patient with correction chain metadata (`isCorrection`, `hasBeenSuperseded`, `supersededByBatchId`), live vs superseded observation counts, summary totals, and per-batch audit trails; `404 PATIENT_HISTORY_NOT_FOUND` when no batches exist for the patient
- **Work Queues** — `GET /work-queue/verification` (batches in `PENDING_VERIFICATION`, sorted by submission time ASC); `GET /work-queue/entry` (batches in `UPLOADED`, `IN_ENTRY`, or `REJECTED`); `GET /work-queue/clinical-approval` (batches in `AWAITING_CLINICAL_APPROVAL`); role-restricted access
- **Batch Status Machine** — explicit transition matrix enforced in the service layer; illegal transitions return `409`; `PROMOTED` is terminal — corrections require a new batch with `supersedesBatchId`
- **JWT Authentication** — `POST /auth/login` returns access token (15 min) and refresh token (7 days); `POST /auth/refresh` rotates tokens; `POST /auth/logout` revokes server-side; `GET /auth/me` returns authenticated user profile; BCrypt password hashing
@@ -76,25 +80,29 @@ HTTP request
├── BatchService (batch CRUD, status machine, Redis assignment lock, duplicate detection)
├── DraftService (draft patient/encounter/observation CRUD, plausibility validation, submit-for-verification)
├── VerificationService (verify/reject with separation of duties, site-config approval routing)
├── PromotionService (approve + atomic promote to live tables, patient dedup, encounter matching, outbox events, supersession on correction promotion)
├── DigitizationHistoryService (patient digitization history with correction chain and audit trails)
├── IdempotencyService (Idempotency-Key storage + replay for safe promotion retries)
├── MrnGenerator (PostgreSQL sequence-backed MRN generation: VCR-000001)
├── WorkQueueService (verification, entry, clinical approval queues)
├── DocumentStorageService (MinIO upload, SHA-256, presigned URLs)
├── PlausibilityValidator (per-code numeric range guard)
├── PostgreSQL (EF Core — writes, keyed reads)
├── PostgreSQL (EF Core — writes, keyed reads, clinical schema for live tables)
├── Redis (batch assignment locks)
└── MinIO (scanned document storage)
```
**Relationship to VigilCareClinical:** VigilCare Records is the precursor that creates the fuel — patient identity, encounters, and observations — in a governed, auditable way. Draft observations are invisible to VigilCareClinical's alert engine, Elasticsearch ward projection, and scoring consumers. Only batches that pass approval are promoted to live tables. Promotion (Phase 4) will write directly to VigilCareClinical's `patients`, `encounters`, `observations`, and `outbox_events` tables in a single transaction.
**Relationship to VigilCareClinical:** VigilCare Records is the precursor that creates the fuel — patient identity, encounters, and observations — in a governed, auditable way. Draft observations are invisible to VigilCareClinical's alert engine, Elasticsearch ward projection, and scoring consumers. Only batches that pass approval are promoted to live tables. Promotion writes directly to VigilCareClinical's `patients`, `encounters`, `observations`, and `outbox_events` tables in a single atomic transaction with idempotency protection.
```
┌─────────────────────────────────────────────────────────────────────┐
│ VigilCare Records (this project) │
│ │
│ Scan → Entry → Verify → Approve
│ Scan → Entry → Verify → Approve → Promote
│ ↓ │
│ Draft tables (never alert) │
│ ↓ on approval (Phase 4)
│ Promotion service ──────────────────────────────────────────────┐ │
│ ↓ on approval
│ PromotionService (atomic txn + idempotency) ────────────────────┐ │
└──────────────────────────────────────────────────────────────────│──┘
┌──────────────────────────────────────────────────────────────────▼──┐
@@ -129,6 +137,7 @@ VigilCareRecordsAPI/
├── Program.cs # Service registration, middleware, seed on startup
├── appsettings.json # Connection strings, Redis, MinIO, Seq, JWT, site config
├── Controllers/
│ ├── ApprovalController.cs # Batch approval and promotion to live clinical tables
│ ├── AuthController.cs # JWT login, token refresh, logout, authenticated user profile
│ ├── DigitizationBatchesController.cs # Batch CRUD, document upload, assignment
│ ├── DraftController.cs # Draft data entry: patient, encounter, observations, submit
@@ -136,10 +145,17 @@ VigilCareRecordsAPI/
│ └── WorkQueueController.cs # Work queues: verification, entry, clinical approval
├── Domain/
│ ├── Entities/
│ │ ├── Clinical/
│ │ │ ├── Patient.cs # Live patient record with MRN (promoted from draft)
│ │ │ ├── Encounter.cs # Live encounter (promoted from draft)
│ │ │ ├── Observation.cs # Live observation with source traceability (batchId, draftObsId)
│ │ │ ├── OutboxEvent.cs # Transactional outbox for downstream consumers (Kafka)
│ │ │ └── IdempotencyRecord.cs # Idempotency-Key storage for safe promotion retries
│ │ ├── Draft/
│ │ │ ├── DraftPatient.cs # Structured patient demographics from paper chart
│ │ │ ├── DraftEncounter.cs # Encounter context: admission, department, room/bed
│ │ │ └── DraftObservation.cs # Single measurement: code, value, unit, recordedAt
│ │ ├── DigitizationBatch.cs # Central workflow entity with status machine
│ │ ├── DraftPatient.cs # Structured patient demographics from paper chart
│ │ ├── DraftEncounter.cs # Encounter context: admission, department, room/bed
│ │ ├── DraftObservation.cs # Single measurement: code, value, unit, recordedAt
│ │ ├── ScannedDocument.cs # MinIO object reference with SHA-256 integrity hash
│ │ ├── DigitizationEvent.cs # Append-only audit trail for every status transition
│ │ ├── User.cs # Username, BCrypt hash, full name, role, active flag
@@ -154,11 +170,14 @@ VigilCareRecordsAPI/
│ ├── BloodType.cs # A+, A-, B+, B-, AB+, AB-, O+, O-
│ └── Department.cs # Clinical departments
├── Services/
│ ├── Interfaces/ # IAuthService, IBatchService, IDraftService, IVerificationService, IWorkQueueService, IDocumentStorageService
│ ├── Interfaces/ # IAuthService, IBatchService, IDraftService, IVerificationService, IWorkQueueService, IDocumentStorageService, IPromotionService, IIdempotencyService, IMrnGenerator
│ ├── AuthService.cs # Login (BCrypt verify), JWT generation, refresh rotation, logout, audit logging
│ ├── BatchService.cs # Batch CRUD, status machine transitions, Redis assignment lock, duplicate detection
│ ├── DraftService.cs # Draft CRUD with plausibility validation, batch-type completeness on submit
│ ├── VerificationService.cs # Verify/reject with separation of duties, site-config clinical approval routing
│ ├── PromotionService.cs # Atomic approve + promote: draft → live tables in single transaction
│ ├── IdempotencyService.cs # Idempotency-Key record storage + replay (24h TTL)
│ ├── MrnGenerator.cs # PostgreSQL sequence-backed MRN generation (VCR-000001)
│ ├── WorkQueueService.cs # Verification, entry, and clinical approval work queues
│ ├── DocumentStorageService.cs # MinIO upload with SHA-256, presigned URL generation
│ └── PlausibilityValidator.cs # Per-code numeric range guard (reused from VigilCareClinical)
@@ -169,6 +188,7 @@ VigilCareRecordsAPI/
├── Models/Records/
│ ├── Auth/ # LoginRequest, LoginResponse, RefreshRequest, LogoutRequest, TokenResponse, UserProfileResponse
│ ├── Batch/ # CreateBatchForm, CreateBatchRequest, AssignBatchRequest, BatchDetailResponse, BatchListResponse, DraftPayloadResponse, VerifyBatchRequest, RejectBatchRequest, FieldCheck
│ ├── Promotion/ # ApproveRequest, PromotionResultResponse
│ ├── DraftPatient/ # DraftPatientDto, UpsertDraftPatientRequest
│ ├── DraftEncounter/ # DraftEncounterDto, UpsertDraftEncounterRequest
│ ├── DraftObservation/ # DraftObservationDto, CreateDraftObservationRequest, UpdateDraftObservationRequest
@@ -176,10 +196,13 @@ VigilCareRecordsAPI/
│ └── Common/ # PagedResult
├── Data/
│ ├── AppDbContext.cs # EF Core context — entity configs, indexes, constraints
│ ├── Configurations/ # IEntityTypeConfiguration per entity (snake_case mapping)
│ ├── Configurations/
│ │ ├── Clinical/ # PatientConfiguration, EncounterConfiguration, ObservationConfiguration, OutboxEventConfiguration, IdempotencyRecordConfiguration
│ │ ├── Draft/ # DraftPatientConfiguration, DraftEncounterConfiguration, DraftObservationConfiguration
│ │ └── ... # DigitizationBatch, DigitizationEvent, ScannedDocument, User, RefreshToken, AuthAuditEvent configs
│ ├── Seed/
│ │ └── DataSeeder.cs # Seeds 12 demo users (two per role) on startup
│ └── Migrations/ # InitialCreate, InitialSchema, AddRefreshTokensAndAuthAudit
│ └── Migrations/ # InitialCreate, InitialSchema, AddRefreshTokensAndAuthAudit, AddIdempotencyRecords, AddClinicalSchemaAndPromotion, AddMrnSequence
├── Common/
│ ├── ApiResponse.cs # { success, statusCode, data, error } envelope
│ └── Exceptions/
@@ -199,18 +222,21 @@ tests/
└── VigilCareRecordsAPI.Tests/
├── DraftEntryTests.cs # Draft CRUD, plausibility validation, submit-for-verification completeness
├── VerificationTests.cs # Verification, rejection, separation of duties, clinical approval routing
├── PromotionTests.cs # Approval, atomic promotion, idempotency, separation of duties, retroactive alerts, patient dedup
├── Fixtures/
│ ├── ApiFixture.cs # WebApplicationFactory with PostgreSQL, Redis, MinIO containers
│ └── DatabaseCollection.cs # Shared test collection
└── Helpers/
├── AuthHelper.cs # JWT token generation for test users
├── BatchSeedHelper.cs # Creates seeded batches at various lifecycle stages
├── BatchPipelineHelper.cs # End-to-end batch pipeline: upload → entry → verify → ready for approval
└── DbResetHelper.cs # Database cleanup between tests
scripts/
├── run-vigilcare-records-verification.sh # Phase 1 — schema, auth, roles, batch CRUD, MinIO, status machine
├── run-vigilcare-records-phase-2-verification.sh # Phase 2 — draft entry, plausibility, submit-for-verification
── run-vigilcare-records-phase-3-verification.sh # Phase 3 — verification, rejection, separation of duties, work queues
── run-vigilcare-records-phase-3-verification.sh # Phase 3 — verification, rejection, separation of duties, work queues
└── run-vigilcare-records-phase-4-verification.sh # Phase 4 — approval, atomic promotion, idempotency, patient dedup, outbox events
docs/
├── plans/ # Phase 19 implementation and verification guides
@@ -360,6 +386,7 @@ Integration tests use `WebApplicationFactory` with PostgreSQL, Redis, and MinIO
|---|---|---|
| `DraftEntryTests` | 2 | Draft CRUD, plausibility validation, submit-for-verification completeness checks |
| `VerificationTests` | 3 | Verification, rejection, separation of duties enforcement, clinical approval routing |
| `PromotionTests` | 4 | Approval, atomic promotion to live tables, idempotency replay, separation of duties, retroactive alert policy, patient deduplication, MRN generation |
### Verification Scripts
@@ -369,6 +396,7 @@ With the API running (`dotnet run`) and Docker Compose up:
./scripts/run-vigilcare-records-verification.sh # Phase 1 — schema, auth, batch CRUD, MinIO, status machine
./scripts/run-vigilcare-records-phase-2-verification.sh # Phase 2 — draft entry, plausibility, submit
./scripts/run-vigilcare-records-phase-3-verification.sh # Phase 3 — verification, rejection, separation of duties
./scripts/run-vigilcare-records-phase-4-verification.sh # Phase 4 — approval, promotion, idempotency, patient dedup
```
---
@@ -534,6 +562,54 @@ Error response:
|---|---|---|---|
| `reason` | string | yes | Rejection reason (minimum 10 characters) |
### Approval and Promotion
| Method | Path | Auth | Description |
|---|---|---|---|
| POST | `/digitization-batches/{id}/approve` | Clinical Approver, Administrator | Approve and atomically promote draft data to live clinical tables |
| GET | `/digitization-batches/{id}/promotion-result` | Any authenticated | Retrieve live entity IDs created during promotion |
**POST `/approve` headers:**
| Header | Required | Description |
|---|---|---|
| `Idempotency-Key` | yes | Unique key (max 100 chars) for safe retries; replays return the original response within 24 hours |
**POST `/approve` body:**
| Field | Type | Required | Description |
|---|---|---|---|
| `enableRetroactiveAlerts` | bool | no | Default `false`. When `true`, backfill observations emit outbox events for downstream alerting. Live capture batches always emit outbox events regardless of this flag. |
**Promotion response (`PromotionResultResponse`):**
| Field | Type | Description |
|---|---|---|
| `batchId` | Guid | The promoted batch |
| `status` | string | `promoted` |
| `patientId` | Guid | Live patient ID (created or matched) |
| `mrn` | string | Medical Record Number (e.g. `VCR-000001`) |
| `encounterId` | Guid | Live encounter ID (created or matched) |
| `observationIds` | Guid[] | Live observation IDs created |
| `promotedAt` | DateTimeOffset | Promotion timestamp |
| `outboxEventsWritten` | int | Number of outbox events emitted for downstream consumers |
**Status codes:**
| Code | Meaning |
|---|---|
| 200 | Batch approved and promoted (or idempotent replay) |
| 400 | Missing or invalid `Idempotency-Key` header |
| 404 | Batch not found |
| 409 | Illegal status transition or separation of duties violation |
| 422 | Missing draft patient data |
**Separation of duties:** The approver cannot be the entry clerk (`enteredByUserId`) or the verifier (`verifiedByUserId`) of the same batch. Both checks return `409 SEPARATION_OF_DUTIES_VIOLATION`.
**Patient deduplication:** On promotion, the service matches existing patients by `fullName` + `dateOfBirth`. If a match is found, the existing patient record is updated with any new fields from the draft. Otherwise, a new patient is created with a sequence-generated MRN (`VCR-NNNNNN`).
**Encounter matching:** Active encounters for the same patient and department are reused. Otherwise, a new encounter is created. Encounters with a discharge diagnosis are created with `discharged` status.
### Work Queues
| Method | Path | Auth | Description |
@@ -641,6 +717,81 @@ occurredAt DateTimeOffset
metadataJson string? optional JSON (field checks, rejection reason, assigned-to)
```
### Patient (Clinical — Live)
```
id Guid PK
mrn string required, unique — generated from PostgreSQL sequence (VCR-000001)
fullName string required
dateOfBirth DateOnly?
sex string?
bloodType BloodType?
emergencyContact string?
allergiesJson string?
noKnownAllergies bool
createdAt DateTimeOffset
updatedAt DateTimeOffset
```
### Encounter (Clinical — Live)
```
id Guid PK
patientId Guid FK → Patient
admissionDate DateTimeOffset?
department Department?
roomBed string?
admissionReason string?
dischargeDiagnosis string?
status string active | discharged
sourceBatchId Guid? FK → DigitizationBatch (traceability)
createdAt DateTimeOffset
updatedAt DateTimeOffset
```
### Observation (Clinical — Live)
```
id Guid PK
encounterId Guid FK → Encounter
patientId Guid FK → Patient
observationCode string required (e.g. HEART_RATE, TEMP_C)
value decimal required
unit string required
recordedAt DateTimeOffset required
note string?
source string digitization_backfill | live_capture
sourceDraftObservationId Guid? FK → DraftObservation (traceability)
sourceBatchId Guid? FK → DigitizationBatch (traceability)
createdAt DateTimeOffset
```
### OutboxEvent
```
id Guid PK
eventType string e.g. observation.created
aggregateType string e.g. Observation
aggregateId Guid FK → the created entity
payloadJson string full event payload for downstream consumers
createdAt DateTimeOffset
processedAt DateTimeOffset? set when consumed
retryCount int default 0
```
### IdempotencyRecord
```
id Guid PK
idempotencyKey string required, unique (from Idempotency-Key header)
operationName string e.g. batch_promote
resourceId Guid the batch ID
httpStatusCode int original response code
responseBodyJson string serialized original response
createdAt DateTimeOffset
expiresAt DateTimeOffset 24-hour TTL
```
### User
```
@@ -703,14 +854,14 @@ Response shape:
## Implemented Phases
Three phases from the project roadmap are implemented and verified. Integration tests (`dotnet test`) and per-phase verification scripts cover Phases 13.
Four phases from the project roadmap are implemented and verified. Integration tests (`dotnet test`) and per-phase verification scripts cover Phases 14.
| Phase | Feature | Status |
|---|---|---|
| 1 | Schema, EF Core migrations, JWT authentication with refresh tokens, six user roles, batch CRUD, MinIO upload with SHA-256 and presigned URLs, batch status machine with transition matrix, duplicate document detection, Redis batch assignment locks, twelve seeded demo users, auth audit events | Done |
| 2 | Draft data entry API (patient demographics, encounter context, observations), plausibility validation on observation values, batch-type completeness validation on submit-for-verification, automatic `UPLOADED → IN_ENTRY` transition on first save, assignment guard (`BATCH_NOT_ASSIGNED`), `DraftEntryTests` integration tests | Done |
| 3 | Verification with field-level checks (`ok`, `warning`, `error` per field), rejection with mandatory reason (min 10 chars), separation of duties enforcement (`SEPARATION_OF_DUTIES_VIOLATION`), site-configurable clinical approval routing per batch type, work queue endpoints (verification, entry, clinical approval) with role-based access, `VerificationTests` integration tests | Done |
| 4 | Approval and promotion to VigilCareClinical live tables, outbox integration, idempotent promotion, retroactive alert policy | Planned |
| 4 | Approval with three-person separation of duties (entry ≠ verifier ≠ approver), atomic promotion to live `patients`/`encounters`/`observations` tables in a single PostgreSQL transaction, PostgreSQL sequence-backed MRN generation (`VCR-NNNNNN`), patient dedup by name + DOB, encounter matching by patient + department + active status, transactional outbox (`observation.created` events), retroactive alert policy per batch, `Idempotency-Key` header with 24h TTL for safe retries, `PromotionTests` integration tests, Phase 4 verification script | Done |
| 5 | Corrections and supersession — new batch replaces old, superseded observations soft-flagged | Planned |
| 6 | Track B live capture with clinician attestation, synchronous alert evaluation | Planned |
| 7 | Digitization workstation UI (Vue 3 side-by-side scan viewer + entry form) | Planned |