diff --git a/.gitignore b/.gitignore index 3c09827..1640eb1 100644 --- a/.gitignore +++ b/.gitignore @@ -128,5 +128,3 @@ Properties/PublishProfiles/*.pubxml *.swp *.bak *.cache - -docs/plans diff --git a/VigilCareRecordsAPI/BackgroundServices/AppBootstrapHostedService.cs b/VigilCareRecordsAPI/BackgroundServices/AppBootstrapHostedService.cs index 892e98f..7e9a1a9 100644 --- a/VigilCareRecordsAPI/BackgroundServices/AppBootstrapHostedService.cs +++ b/VigilCareRecordsAPI/BackgroundServices/AppBootstrapHostedService.cs @@ -1,7 +1,4 @@ using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using Minio; -using Minio.DataModel.Args; /// /// Runs migrate / demo seed / MinIO bucket ensure after Kestrel is listening. @@ -38,19 +35,12 @@ public sealed class AppBootstrapHostedService : BackgroundService using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await db.Database.MigrateAsync(stoppingToken); - await DataSeeder.SeedAsync(db); - - var minio = scope.ServiceProvider.GetRequiredService(); - var minioOpts = scope.ServiceProvider.GetRequiredService>().Value; - if (!await minio.BucketExistsAsync( - new BucketExistsArgs().WithBucket(minioOpts.BucketName), stoppingToken)) - { - await minio.MakeBucketAsync( - new MakeBucketArgs().WithBucket(minioOpts.BucketName), stoppingToken); - _logger.LogInformation("Created MinIO bucket {Bucket}", minioOpts.BucketName); - } + await DataSeeder.SeedAsync(db, stoppingToken); var storage = scope.ServiceProvider.GetRequiredService(); + await storage.EnsureBucketAsync(stoppingToken); + _logger.LogInformation("MinIO bucket ensure completed."); + await SeedDocumentStorage.EnsureAsync(db, storage, _logger, stoppingToken); _startupHealthCheck.StartupCompleted = true; diff --git a/VigilCareRecordsAPI/BackgroundServices/OcrProcessingService.cs b/VigilCareRecordsAPI/BackgroundServices/OcrProcessingService.cs index 0019b56..5ef86a8 100644 --- a/VigilCareRecordsAPI/BackgroundServices/OcrProcessingService.cs +++ b/VigilCareRecordsAPI/BackgroundServices/OcrProcessingService.cs @@ -147,10 +147,10 @@ public class OcrProcessingService : BackgroundService try { - await using var documentStream = await storage.DownloadAsync(document.ObjectKey); - var extraction = await ocr.ExtractAsync(documentStream, document.ContentType); + await using var documentStream = await storage.DownloadAsync(document.ObjectKey, ct); + var extraction = await ocr.ExtractAsync(documentStream, document.ContentType, ct); - await preFiller.PreFillAsync(batch.Id, batch.BatchType, extraction); + await preFiller.PreFillAsync(batch.Id, batch.BatchType, extraction, ct); var fieldConfidences = extraction.Fields .GroupBy(f => f.FieldName, StringComparer.Ordinal) @@ -163,7 +163,7 @@ public class OcrProcessingService : BackgroundService BatchId = batch.Id, Provider = _options.Provider, FieldConfidencesJson = JsonSerializer.Serialize(fieldConfidences), - RawText = extraction.RawText, + RawText = TruncateRawText(extraction.RawText), DurationMs = extraction.DurationMs, ProcessedAt = processedAt }); @@ -213,4 +213,16 @@ public class OcrProcessingService : BackgroundService batch.Id, ex.Message); } } + + /// Caps persisted OCR text to limit DB/LOH growth; draft GET uses confidences only. + internal const int MaxRawTextChars = 64 * 1024; + + private static string? TruncateRawText(string? rawText) + { + if (string.IsNullOrEmpty(rawText)) + return rawText; + return rawText.Length <= MaxRawTextChars + ? rawText + : rawText[..MaxRawTextChars]; + } } diff --git a/VigilCareRecordsAPI/BackgroundServices/PromotionRetryService.cs b/VigilCareRecordsAPI/BackgroundServices/PromotionRetryService.cs index 244378f..4f245ae 100644 --- a/VigilCareRecordsAPI/BackgroundServices/PromotionRetryService.cs +++ b/VigilCareRecordsAPI/BackgroundServices/PromotionRetryService.cs @@ -133,7 +133,7 @@ public class PromotionRetryService : BackgroundService $"Batch {batchId} is in Approved status but has no ApprovedByUserId"); // Attempt promotion with a unique idempotency key per attempt - await promotionService.PromoteAsync(batchId, approverUserId); + await promotionService.PromoteAsync(batchId, approverUserId, ct); // --- Success path --- DiagnosticsMetrics.PromotionRetryTotal.WithLabels("success").Inc(); diff --git a/VigilCareRecordsAPI/Controllers/DigitizationBatchesController.cs b/VigilCareRecordsAPI/Controllers/DigitizationBatchesController.cs index b58f3ef..3435c6d 100644 --- a/VigilCareRecordsAPI/Controllers/DigitizationBatchesController.cs +++ b/VigilCareRecordsAPI/Controllers/DigitizationBatchesController.cs @@ -146,32 +146,41 @@ public class DigitizationBatchesController : ControllerBase [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status404NotFound)] public async Task GetDocument(Guid id) { - var batch = await _batches.GetByIdAsync(id); + var batchMeta = await _db.DigitizationBatches + .AsNoTracking() + .Where(b => b.Id == id) + .Select(b => new { b.DocumentRef }) + .FirstOrDefaultAsync(); - if (batch.DocumentRef == "live-capture") + if (batchMeta is null) + return NotFound(ApiResponse.Fail(404, "Batch not found.", "BATCH_NOT_FOUND")); + + if (batchMeta.DocumentRef == "live-capture" || string.IsNullOrEmpty(batchMeta.DocumentRef)) return NotFound(ApiResponse.Fail( 404, "This batch has no scanned document.", "NO_DOCUMENT")); - var scanned = await _db.ScannedDocuments + var contentType = await _db.ScannedDocuments .AsNoTracking() - .FirstOrDefaultAsync(d => d.BatchId == id); - - var contentType = scanned?.ContentType ?? "application/octet-stream"; + .Where(d => d.BatchId == id) + .Select(d => d.ContentType) + .FirstOrDefaultAsync() ?? "application/octet-stream"; await RecordDocumentAccessAsync(id); try { - if (!await _storage.ObjectExistsAsync(batch.DocumentRef)) - return NotFound(ApiResponse.Fail( - 404, - "Scanned document is missing from storage. Re-upload the batch or restore the object.", - "DOCUMENT_NOT_FOUND")); - - var stream = await _storage.DownloadAsync(batch.DocumentRef); + var stream = await _storage.DownloadAsync( + batchMeta.DocumentRef, HttpContext.RequestAborted); Response.Headers.CacheControl = "private, max-age=300"; return File(stream, contentType); } + catch (Minio.Exceptions.ObjectNotFoundException) + { + return NotFound(ApiResponse.Fail( + 404, + "Scanned document is missing from storage. Re-upload the batch or restore the object.", + "DOCUMENT_NOT_FOUND")); + } catch (Exception ex) when (ex is not OperationCanceledException) { return StatusCode(503, ApiResponse.Fail( diff --git a/VigilCareRecordsAPI/Controllers/Fhir/FhirPatientController.cs b/VigilCareRecordsAPI/Controllers/Fhir/FhirPatientController.cs index 6636d0e..d05983b 100644 --- a/VigilCareRecordsAPI/Controllers/Fhir/FhirPatientController.cs +++ b/VigilCareRecordsAPI/Controllers/Fhir/FhirPatientController.cs @@ -54,12 +54,15 @@ public class FhirPatientController : ControllerBase [HttpGet("{id}/$everything")] [ProducesResponseType(typeof(Bundle), StatusCodes.Status200OK)] [ProducesResponseType(typeof(OperationOutcome), StatusCodes.Status404NotFound)] - public async Task Everything(string id) + public async Task Everything( + string id, + [FromQuery(Name = "_count")] int count = 100, + [FromQuery(Name = "_offset")] int offset = 0) { - var bundle = await _fhir.GetPatientEverythingAsync(Guid.Parse(id)); + var bundle = await _fhir.GetPatientEverythingAsync(Guid.Parse(id), count, offset); if (bundle is null) return NotFound(FhirErrorHelper.NotFound("Patient", id)); return Ok(bundle); - } + } } \ No newline at end of file diff --git a/VigilCareRecordsAPI/Controllers/PatientsController.cs b/VigilCareRecordsAPI/Controllers/PatientsController.cs index c3b920a..0a5fe78 100644 --- a/VigilCareRecordsAPI/Controllers/PatientsController.cs +++ b/VigilCareRecordsAPI/Controllers/PatientsController.cs @@ -41,9 +41,12 @@ public class PatientsController : ControllerBase [HttpGet("{patientId:guid}/digitization-history")] [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status404NotFound)] - public async Task GetDigitizationHistory(Guid patientId) + public async Task GetDigitizationHistory( + Guid patientId, + [FromQuery] int page = 1, + [FromQuery] int pageSize = 20) { - var history = await _history.GetPatientHistoryAsync(patientId); + var history = await _history.GetPatientHistoryAsync(patientId, page, pageSize); return Ok(ApiResponse.Ok(history)); } } diff --git a/VigilCareRecordsAPI/Data/Seed/DataSeeder.cs b/VigilCareRecordsAPI/Data/Seed/DataSeeder.cs index 5b02f6a..8245a75 100644 --- a/VigilCareRecordsAPI/Data/Seed/DataSeeder.cs +++ b/VigilCareRecordsAPI/Data/Seed/DataSeeder.cs @@ -24,9 +24,9 @@ public static class DataSeeder private static readonly Guid Patient4Id = Guid.Parse("b1000000-0000-0000-0000-000000000004"); private static readonly Guid Patient5Id = Guid.Parse("b1000000-0000-0000-0000-000000000005"); - public static async Task SeedAsync(AppDbContext db) + public static async Task SeedAsync(AppDbContext db, CancellationToken ct = default) { - if (await db.Users.AnyAsync()) return; + if (await db.Users.AnyAsync(ct)) return; // ── Users (2 per role) ──────────────────────────────────────────────── var users = new[] diff --git a/VigilCareRecordsAPI/Data/Seed/SeedDocumentStorage.cs b/VigilCareRecordsAPI/Data/Seed/SeedDocumentStorage.cs index 92d20e0..f6a7329 100644 --- a/VigilCareRecordsAPI/Data/Seed/SeedDocumentStorage.cs +++ b/VigilCareRecordsAPI/Data/Seed/SeedDocumentStorage.cs @@ -61,17 +61,35 @@ public static class SeedDocumentStorage logger.LogInformation("Seeded {Count} missing ScannedDocument rows", missingDocs.Count); } + // Prefer ensuring objects only for keys we just registered as missing docs, + // plus a single pass for remaining keys via EnsureObjectAsync (Stat+Put if needed). + // Cap bootstrap MinIO work so restarts on large DBs stay bounded. + const int maxObjectEnsuresPerBootstrap = 200; + var keysToEnsure = missingDocs + .Select(d => d.ObjectKey) + .Concat(batches.Select(b => b.DocumentRef)) + .Distinct(StringComparer.Ordinal) + .Take(maxObjectEnsuresPerBootstrap) + .ToList(); + var uploaded = 0; - foreach (var batch in batches) + foreach (var objectKey in keysToEnsure) { ct.ThrowIfCancellationRequested(); - if (!await storage.ObjectExistsAsync(batch.DocumentRef)) + if (!await storage.ObjectExistsAsync(objectKey, ct)) { - await storage.EnsureObjectAsync(batch.DocumentRef, MinimalPdf, "application/pdf"); + await storage.EnsureObjectAsync(objectKey, MinimalPdf, "application/pdf", ct); uploaded++; } } + if (batches.Count > maxObjectEnsuresPerBootstrap) + { + logger.LogWarning( + "SeedDocumentStorage capped MinIO ensure at {Cap} of {Total} batch keys; remaining keys will be ensured on later bootstraps or first access", + maxObjectEnsuresPerBootstrap, batches.Count); + } + if (uploaded > 0) logger.LogInformation("Uploaded {Count} placeholder scan PDFs to object storage", uploaded); } diff --git a/VigilCareRecordsAPI/Infrastructure/Fhir/FhirJsonOutputFormatter.cs b/VigilCareRecordsAPI/Infrastructure/Fhir/FhirJsonOutputFormatter.cs index d65f953..a405f2a 100644 --- a/VigilCareRecordsAPI/Infrastructure/Fhir/FhirJsonOutputFormatter.cs +++ b/VigilCareRecordsAPI/Infrastructure/Fhir/FhirJsonOutputFormatter.cs @@ -6,6 +6,9 @@ using Task = System.Threading.Tasks.Task; public class FhirJsonOutputFormatter : TextOutputFormatter { + private static readonly Lazy Serializer = new(() => + new FhirJsonSerializer(new SerializerSettings { Pretty = false })); + public FhirJsonOutputFormatter() { SupportedMediaTypes.Add("application/fhir+json"); @@ -24,8 +27,7 @@ public class FhirJsonOutputFormatter : TextOutputFormatter var resource = context.Object as Resource; if (resource is null) return; - var serializer = new FhirJsonSerializer(new SerializerSettings { Pretty = true }); - var json = serializer.SerializeToString(resource); + var json = Serializer.Value.SerializeToString(resource); await context.HttpContext.Response.WriteAsync(json, selectedEncoding); } -} \ No newline at end of file +} diff --git a/VigilCareRecordsAPI/Models/Records/Batch/PatientDigitizationHistoryResponse.cs b/VigilCareRecordsAPI/Models/Records/Batch/PatientDigitizationHistoryResponse.cs index fb5c0ca..8a27667 100644 --- a/VigilCareRecordsAPI/Models/Records/Batch/PatientDigitizationHistoryResponse.cs +++ b/VigilCareRecordsAPI/Models/Records/Batch/PatientDigitizationHistoryResponse.cs @@ -4,5 +4,8 @@ public record PatientDigitizationHistoryResponse( int PromotedBatches, int SupersededBatches, int PendingBatches, + int Page, + int PageSize, + int TotalPages, IReadOnlyList Entries ); diff --git a/VigilCareRecordsAPI/Program.cs b/VigilCareRecordsAPI/Program.cs index aa790ea..42b3733 100644 --- a/VigilCareRecordsAPI/Program.cs +++ b/VigilCareRecordsAPI/Program.cs @@ -1,5 +1,7 @@ using System.Text; using System.Threading.RateLimiting; +using Azure; +using Azure.AI.DocumentIntelligence; using FluentValidation; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Diagnostics.HealthChecks; @@ -62,9 +64,21 @@ try builder.Services.AddSingleton(); if (ocrOptions.Provider == "azure") + { + builder.Services.AddSingleton(sp => + { + var opts = sp.GetRequiredService>() + .Value.Azure; + return new DocumentIntelligenceClient( + new Uri(opts.Endpoint), + new AzureKeyCredential(opts.ApiKey)); + }); builder.Services.AddScoped(); + } else + { builder.Services.AddScoped(); + } builder.Services.AddScoped(); builder.Services.AddHostedService(); diff --git a/VigilCareRecordsAPI/Services/BatchService.cs b/VigilCareRecordsAPI/Services/BatchService.cs index 0e128f1..f2bfb6c 100644 --- a/VigilCareRecordsAPI/Services/BatchService.cs +++ b/VigilCareRecordsAPI/Services/BatchService.cs @@ -189,7 +189,10 @@ public class BatchService : IBatchService BatchStatus? status, BatchType? batchType, Guid? assignedTo, BatchTrack? track, int page, int pageSize, string sortBy = "createdAt", string sortDirection = "desc") { - var query = _db.DigitizationBatches.AsQueryable(); + pageSize = Math.Clamp(pageSize, 1, 100); + page = Math.Max(1, page); + + var query = _db.DigitizationBatches.AsNoTracking().AsQueryable(); if (status.HasValue) query = query.Where(b => b.Status == status.Value); diff --git a/VigilCareRecordsAPI/Services/CoverSheetService.cs b/VigilCareRecordsAPI/Services/CoverSheetService.cs index 2f5e488..684baa6 100644 --- a/VigilCareRecordsAPI/Services/CoverSheetService.cs +++ b/VigilCareRecordsAPI/Services/CoverSheetService.cs @@ -65,6 +65,7 @@ public class CoverSheetService : ICoverSheetService public async Task LookupByCodeAsync(string code) { return await _db.CoverSheets + .AsNoTracking() .Include(c => c.Patient) .Include(c => c.AssignToUser) .Include(c => c.Batch) @@ -74,6 +75,7 @@ public class CoverSheetService : ICoverSheetService public async Task LookupByIdAsync(Guid id) { return await _db.CoverSheets + .AsNoTracking() .Include(c => c.Patient) .Include(c => c.AssignToUser) .Include(c => c.Batch) @@ -85,6 +87,11 @@ public class CoverSheetService : ICoverSheetService if (ids.Count == 0) return new List(); + if (ids.Count > 100) + throw new ValidationException( + "At most 100 cover sheet IDs are allowed per batch PDF request.", + "COVER_SHEET_BATCH_PDF_LIMIT"); + var idSet = ids.Distinct().ToList(); var sheets = await _db.CoverSheets .AsNoTracking() @@ -120,6 +127,9 @@ public class CoverSheetService : ICoverSheetService public async Task> ListAsync( bool? isUsed, Guid? patientId, int page, int pageSize) { + pageSize = Math.Clamp(pageSize, 1, 100); + page = Math.Max(1, page); + var query = _db.CoverSheets .AsNoTracking() .Include(c => c.Patient) diff --git a/VigilCareRecordsAPI/Services/DigitizationHistoryService.cs b/VigilCareRecordsAPI/Services/DigitizationHistoryService.cs index d088a16..a022afe 100644 --- a/VigilCareRecordsAPI/Services/DigitizationHistoryService.cs +++ b/VigilCareRecordsAPI/Services/DigitizationHistoryService.cs @@ -2,6 +2,7 @@ using Microsoft.EntityFrameworkCore; public class DigitizationHistoryService : IDigitizationHistoryService { + private const int MaxAuditEventsPerBatch = 50; private readonly AppDbContext _db; public DigitizationHistoryService(AppDbContext db) @@ -9,10 +10,14 @@ public class DigitizationHistoryService : IDigitizationHistoryService _db = db; } - public async Task GetPatientHistoryAsync(Guid patientId) + public async Task GetPatientHistoryAsync( + Guid patientId, int page = 1, int pageSize = 20) { - // Verify the patient exists (has at least one batch) + pageSize = Math.Clamp(pageSize, 1, 50); + page = Math.Max(1, page); + var hasBatches = await _db.DigitizationBatches + .AsNoTracking() .AnyAsync(b => b.PatientId == patientId); if (!hasBatches) @@ -20,37 +25,70 @@ public class DigitizationHistoryService : IDigitizationHistoryService $"No digitization history found for patient {patientId}.", "PATIENT_HISTORY_NOT_FOUND"); - // Load all batches for this patient with their relationships - var batches = await _db.DigitizationBatches - .Include(b => b.DraftObservations) - .Include(b => b.Events) - .ThenInclude(e => e.Actor) - .Include(b => b.EnteredByUser) - .Include(b => b.VerifiedByUser) - .Include(b => b.ApprovedByUser) + var statusCounts = await _db.DigitizationBatches + .AsNoTracking() .Where(b => b.PatientId == patientId) - .OrderByDescending(b => b.CreatedAt) + .GroupBy(b => b.Status) + .Select(g => new { Status = g.Key, Count = g.Count() }) .ToListAsync(); - // For each promoted batch, count live vs superseded observations - var promotedBatchIds = batches + var totalBatches = statusCounts.Sum(s => s.Count); + var promotedBatches = statusCounts + .Where(s => s.Status == BatchStatus.Promoted) + .Sum(s => s.Count); + var pendingBatches = statusCounts + .Where(s => s.Status != BatchStatus.Promoted && s.Status != BatchStatus.Rejected) + .Sum(s => s.Count); + var totalPages = Math.Max(1, (int)Math.Ceiling(totalBatches / (double)pageSize)); + + var batchPage = await _db.DigitizationBatches + .AsNoTracking() + .Where(b => b.PatientId == patientId) + .OrderByDescending(b => b.CreatedAt) + .Skip((page - 1) * pageSize) + .Take(pageSize) + .Select(b => new + { + b.Id, + b.Status, + b.BatchType, + b.Track, + b.SupersedesBatchId, + b.CreatedAt, + b.PromotedAt, + b.PromotionEncounterId, + b.EnteredByUserId, + EnteredByUserName = b.EnteredByUser != null ? b.EnteredByUser.FullName : null, + b.VerifiedByUserId, + VerifiedByUserName = b.VerifiedByUser != null ? b.VerifiedByUser.FullName : null, + b.ApprovedByUserId, + ApprovedByUserName = b.ApprovedByUser != null ? b.ApprovedByUser.FullName : null, + DraftObservationCount = b.DraftObservations.Count, + }) + .ToListAsync(); + + var pageBatchIds = batchPage.Select(b => b.Id).ToList(); + + var promotedPageIds = batchPage .Where(b => b.Status == BatchStatus.Promoted) .Select(b => b.Id) .ToList(); - var liveObservationCounts = await _db.LiveObservations - .Where(o => promotedBatchIds.Contains(o.SourceBatchId)) - .GroupBy(o => new { o.SourceBatchId, o.IsSuperseded }) - .Select(g => new - { - g.Key.SourceBatchId, - g.Key.IsSuperseded, - Count = g.Count() - }) - .ToListAsync(); + var liveObservationCounts = promotedPageIds.Count == 0 + ? [] + : await _db.LiveObservations + .AsNoTracking() + .Where(o => promotedPageIds.Contains(o.SourceBatchId)) + .GroupBy(o => new { o.SourceBatchId, o.IsSuperseded }) + .Select(g => new + { + g.Key.SourceBatchId, + g.Key.IsSuperseded, + Count = g.Count() + }) + .ToListAsync(); - // Build a lookup: batchId -> (activeCount, supersededCount) - var obsCountLookup = promotedBatchIds.ToDictionary( + var obsCountLookup = promotedPageIds.ToDictionary( id => id, id => { @@ -61,17 +99,58 @@ public class DigitizationHistoryService : IDigitizationHistoryService return (Active: active, Superseded: superseded); }); - // Build a lookup for "has been superseded" — batches that appear as - // SupersedesBatchId on another batch that reached Promoted - var supersededByLookup = await _db.DigitizationBatches - .Where(b => b.SupersedesBatchId.HasValue - && b.Status == BatchStatus.Promoted - && promotedBatchIds.Contains(b.SupersedesBatchId.Value)) - .ToDictionaryAsync( - b => b.SupersedesBatchId!.Value, - b => b.Id); + var supersededByLookup = promotedPageIds.Count == 0 + ? new Dictionary() + : await _db.DigitizationBatches + .AsNoTracking() + .Where(b => b.SupersedesBatchId.HasValue + && b.Status == BatchStatus.Promoted + && promotedPageIds.Contains(b.SupersedesBatchId.Value)) + .ToDictionaryAsync( + b => b.SupersedesBatchId!.Value, + b => b.Id); - var entries = batches.Select(b => + // Cap audit trail: newest MaxAuditEventsPerBatch events per batch on this page. + var events = pageBatchIds.Count == 0 + ? [] + : await _db.DigitizationEvents + .AsNoTracking() + .Where(e => pageBatchIds.Contains(e.BatchId)) + .OrderByDescending(e => e.OccurredAt) + .Select(e => new + { + e.BatchId, + EventType = e.EventType, + e.OccurredAt, + e.ActorUserId, + ActorName = e.Actor != null ? e.Actor.FullName : "Unknown", + e.MetadataJson + }) + .ToListAsync(); + + var auditByBatch = events + .GroupBy(e => e.BatchId) + .ToDictionary( + g => g.Key, + g => g.Take(MaxAuditEventsPerBatch) + .OrderBy(e => e.OccurredAt) + .Select(e => new DigitizationEventSummary( + e.EventType.ToDbString(), + e.OccurredAt, + e.ActorUserId, + e.ActorName, + e.MetadataJson)) + .ToList()); + + // SupersededBatches is global for the patient (not page-local). + var supersededBatchCount = await _db.DigitizationBatches + .AsNoTracking() + .Where(b => b.PatientId == patientId && b.Status == BatchStatus.Promoted) + .Where(b => _db.DigitizationBatches.Any(s => + s.SupersedesBatchId == b.Id && s.Status == BatchStatus.Promoted)) + .CountAsync(); + + var entries = batchPage.Select(b => { var counts = obsCountLookup.GetValueOrDefault(b.Id, (Active: 0, Superseded: 0)); var hasBeenSuperseded = supersededByLookup.ContainsKey(b.Id); @@ -86,37 +165,32 @@ public class DigitizationHistoryService : IDigitizationHistoryService IsCorrection: b.SupersedesBatchId.HasValue, HasBeenSuperseded: hasBeenSuperseded, SupersededByBatchId: hasBeenSuperseded ? supersededByBatchId : null, - DraftObservationCount: b.DraftObservations.Count, + DraftObservationCount: b.DraftObservationCount, LiveObservationCount: counts.Active, SupersededObservationCount: counts.Superseded, CreatedAt: b.CreatedAt, PromotedAt: b.PromotedAt, PromotionEncounterId: b.PromotionEncounterId, EnteredByUserId: b.EnteredByUserId, - EnteredByUserName: b.EnteredByUser?.FullName, + EnteredByUserName: b.EnteredByUserName, VerifiedByUserId: b.VerifiedByUserId, - VerifiedByUserName: b.VerifiedByUser?.FullName, + VerifiedByUserName: b.VerifiedByUserName, ApprovedByUserId: b.ApprovedByUserId, - ApprovedByUserName: b.ApprovedByUser?.FullName, - AuditTrail: b.Events - .OrderBy(e => e.OccurredAt) - .Select(e => new DigitizationEventSummary( - e.EventType.ToDbString(), - e.OccurredAt, - e.ActorUserId, - e.Actor?.FullName ?? "Unknown", - e.MetadataJson)) - .ToList() + ApprovedByUserName: b.ApprovedByUserName, + AuditTrail: auditByBatch.GetValueOrDefault(b.Id, []) ); }).ToList(); return new PatientDigitizationHistoryResponse( PatientId: patientId, - TotalBatches: entries.Count, - PromotedBatches: entries.Count(e => e.Status == "PROMOTED"), - SupersededBatches: entries.Count(e => e.HasBeenSuperseded), - PendingBatches: entries.Count(e => e.Status != "PROMOTED" && e.Status != "REJECTED"), + TotalBatches: totalBatches, + PromotedBatches: promotedBatches, + SupersededBatches: supersededBatchCount, + PendingBatches: pendingBatches, + Page: page, + PageSize: pageSize, + TotalPages: totalPages, Entries: entries ); } -} \ No newline at end of file +} diff --git a/VigilCareRecordsAPI/Services/DocumentStorageService.cs b/VigilCareRecordsAPI/Services/DocumentStorageService.cs index d5325df..aea33d7 100644 --- a/VigilCareRecordsAPI/Services/DocumentStorageService.cs +++ b/VigilCareRecordsAPI/Services/DocumentStorageService.cs @@ -7,6 +7,8 @@ public class DocumentStorageService : IDocumentStorageService { private readonly IMinioClient _minio; private readonly MinioOptions _options; + // Process-lifetime: DocumentStorageService is scoped; bucket only needs ensuring once. + private static int _bucketReady; // 0 = unknown, 1 = ensured public DocumentStorageService(IMinioClient minio, IOptions options) { @@ -15,17 +17,21 @@ public class DocumentStorageService : IDocumentStorageService } public async Task<(string objectKey, string sha256, long fileSize)> UploadAsync( - Stream fileStream, string contentType, Guid batchId) + Stream fileStream, string contentType, Guid batchId, CancellationToken ct = default) { var now = DateTimeOffset.UtcNow; - using var sha256 = SHA256.Create(); + using var sha256 = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); using var memStream = new MemoryStream(); - await fileStream.CopyToAsync(memStream); - memStream.Position = 0; + var buffer = new byte[81920]; + int read; + while ((read = await fileStream.ReadAsync(buffer.AsMemory(0, buffer.Length), ct)) > 0) + { + sha256.AppendData(buffer.AsSpan(0, read)); + await memStream.WriteAsync(buffer.AsMemory(0, read), ct); + } - var hashBytes = sha256.ComputeHash(memStream); - var hashHex = Convert.ToHexString(hashBytes).ToLowerInvariant(); + var hashHex = Convert.ToHexString(sha256.GetHashAndReset()).ToLowerInvariant(); memStream.Position = 0; var extension = contentType switch @@ -38,45 +44,49 @@ public class DocumentStorageService : IDocumentStorageService var objectKey = $"scans/{now.Year}/{now.Month:D2}/{batchId}/{hashHex}.{extension}"; - await EnsureBucketAsync(); + await EnsureBucketAsync(ct); await _minio.PutObjectAsync(new PutObjectArgs() .WithBucket(_options.BucketName) .WithObject(objectKey) .WithStreamData(memStream) .WithObjectSize(memStream.Length) - .WithContentType(contentType)); + .WithContentType(contentType), ct); return (objectKey, hashHex, memStream.Length); } - public async Task GetPresignedUrlAsync(string objectKey) + public async Task GetPresignedUrlAsync(string objectKey, CancellationToken ct = default) { + ct.ThrowIfCancellationRequested(); return await _minio.PresignedGetObjectAsync(new PresignedGetObjectArgs() .WithBucket(_options.BucketName) .WithObject(objectKey) .WithExpiry(_options.PresignedUrlExpiryMinutes * 60)); } - public async Task DownloadAsync(string objectKey) + public async Task DownloadAsync(string objectKey, CancellationToken ct = default) { var memStream = new MemoryStream(); await _minio.GetObjectAsync(new GetObjectArgs() .WithBucket(_options.BucketName) .WithObject(objectKey) - .WithCallbackStream(stream => stream.CopyTo(memStream))); + .WithCallbackStream(async (stream, cancellationToken) => + { + await stream.CopyToAsync(memStream, 81920, cancellationToken); + }), ct); memStream.Position = 0; return memStream; } - public async Task ObjectExistsAsync(string objectKey) + public async Task ObjectExistsAsync(string objectKey, CancellationToken ct = default) { try { await _minio.StatObjectAsync(new StatObjectArgs() .WithBucket(_options.BucketName) - .WithObject(objectKey)); + .WithObject(objectKey), ct); return true; } catch (Minio.Exceptions.ObjectNotFoundException) @@ -85,10 +95,11 @@ public class DocumentStorageService : IDocumentStorageService } } - public async Task EnsureObjectAsync(string objectKey, byte[] content, string contentType) + public async Task EnsureObjectAsync( + string objectKey, byte[] content, string contentType, CancellationToken ct = default) { - await EnsureBucketAsync(); - if (await ObjectExistsAsync(objectKey)) + await EnsureBucketAsync(ct); + if (await ObjectExistsAsync(objectKey, ct)) return; using var stream = new MemoryStream(content); @@ -97,13 +108,20 @@ public class DocumentStorageService : IDocumentStorageService .WithObject(objectKey) .WithStreamData(stream) .WithObjectSize(stream.Length) - .WithContentType(contentType)); + .WithContentType(contentType), ct); } - private async Task EnsureBucketAsync() + public async Task EnsureBucketAsync(CancellationToken ct = default) { - var exists = await _minio.BucketExistsAsync(new BucketExistsArgs().WithBucket(_options.BucketName)); + if (Interlocked.CompareExchange(ref _bucketReady, 0, 0) == 1) + return; + + var exists = await _minio.BucketExistsAsync( + new BucketExistsArgs().WithBucket(_options.BucketName), ct); if (!exists) - await _minio.MakeBucketAsync(new MakeBucketArgs().WithBucket(_options.BucketName)); + await _minio.MakeBucketAsync( + new MakeBucketArgs().WithBucket(_options.BucketName), ct); + + Interlocked.Exchange(ref _bucketReady, 1); } -} \ No newline at end of file +} diff --git a/VigilCareRecordsAPI/Services/FhirService.cs b/VigilCareRecordsAPI/Services/FhirService.cs index 1cd9e93..e68a71f 100644 --- a/VigilCareRecordsAPI/Services/FhirService.cs +++ b/VigilCareRecordsAPI/Services/FhirService.cs @@ -145,52 +145,111 @@ public class FhirService : IFhirService total, count, offset, "Observation"); } - public async Task GetPatientEverythingAsync(Guid patientId) + public async Task GetPatientEverythingAsync( + Guid patientId, int count = 100, int offset = 0) { + count = Math.Clamp(count, 1, 500); + offset = Math.Max(0, offset); + var patient = await _db.Patients.AsNoTracking().FirstOrDefaultAsync(p => p.Id == patientId); if (patient is null) return null; - var encounters = await _db.Encounters.AsNoTracking() - .Where(e => e.PatientId == patientId) - .ToListAsync(); - - var observations = await _db.Observations.AsNoTracking() - .Where(o => o.PatientId == patientId) - .OrderByDescending(o => o.RecordedAt) - .ToListAsync(); + var encounterCount = await _db.Encounters.AsNoTracking() + .CountAsync(e => e.PatientId == patientId); + var observationCount = await _db.Observations.AsNoTracking() + .CountAsync(o => o.PatientId == patientId); + var total = 1 + encounterCount + observationCount; var bundle = new Bundle { Type = Bundle.BundleType.Searchset, - Total = 1 + encounters.Count + observations.Count, + Total = total, Meta = new Meta { LastUpdated = DateTimeOffset.UtcNow }, }; - bundle.Entry.Add(new Bundle.EntryComponent - { - FullUrl = $"{_options.BaseUrl}/Patient/{patient.Id}", - Resource = PatientMapper.ToFhir(patient, _options.BaseUrl), - Search = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Match }, - }); + // Virtual layout: index 0 = Patient, then encounters, then observations. + var remaining = count; + var cursor = offset; - foreach (var enc in encounters) + if (cursor == 0 && remaining > 0) { bundle.Entry.Add(new Bundle.EntryComponent { - FullUrl = $"{_options.BaseUrl}/Encounter/{enc.Id}", - Resource = EncounterMapper.ToFhir(enc, _options.BaseUrl), - Search = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Include }, + FullUrl = $"{_options.BaseUrl}/Patient/{patient.Id}", + Resource = PatientMapper.ToFhir(patient, _options.BaseUrl), + Search = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Match }, }); + remaining--; + cursor = 1; } - foreach (var obs in observations) + if (remaining > 0 && cursor < 1 + encounterCount) { - bundle.Entry.Add(new Bundle.EntryComponent + var encSkip = Math.Max(0, cursor - 1); + var encTake = Math.Min(remaining, encounterCount - encSkip); + if (encTake > 0) { - FullUrl = $"{_options.BaseUrl}/Observation/{obs.Id}", - Resource = ObservationMapper.ToFhir(obs, _options.BaseUrl), - Search = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Include }, - }); + var encounters = await _db.Encounters.AsNoTracking() + .Where(e => e.PatientId == patientId) + .OrderByDescending(e => e.AdmissionDate) + .Skip(encSkip) + .Take(encTake) + .ToListAsync(); + + foreach (var enc in encounters) + { + bundle.Entry.Add(new Bundle.EntryComponent + { + FullUrl = $"{_options.BaseUrl}/Encounter/{enc.Id}", + Resource = EncounterMapper.ToFhir(enc, _options.BaseUrl), + Search = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Include }, + }); + } + + remaining -= encounters.Count; + cursor += encounters.Count; + } + } + + if (remaining > 0 && cursor < total) + { + var obsSkip = Math.Max(0, cursor - 1 - encounterCount); + var obsTake = Math.Min(remaining, observationCount - obsSkip); + if (obsTake > 0) + { + var observations = await _db.Observations.AsNoTracking() + .Where(o => o.PatientId == patientId) + .OrderByDescending(o => o.RecordedAt) + .Skip(obsSkip) + .Take(obsTake) + .ToListAsync(); + + foreach (var obs in observations) + { + bundle.Entry.Add(new Bundle.EntryComponent + { + FullUrl = $"{_options.BaseUrl}/Observation/{obs.Id}", + Resource = ObservationMapper.ToFhir(obs, _options.BaseUrl), + Search = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Include }, + }); + } + } + } + + var selfUrl = $"{_options.BaseUrl}/Patient/{patientId}/$everything?_count={count}&_offset={offset}"; + bundle.Link.Add(new Bundle.LinkComponent { Relation = "self", Url = selfUrl }); + + if (offset + count < total) + { + var nextUrl = $"{_options.BaseUrl}/Patient/{patientId}/$everything?_count={count}&_offset={offset + count}"; + bundle.Link.Add(new Bundle.LinkComponent { Relation = "next", Url = nextUrl }); + } + + if (offset > 0) + { + var prevOffset = Math.Max(0, offset - count); + var prevUrl = $"{_options.BaseUrl}/Patient/{patientId}/$everything?_count={count}&_offset={prevOffset}"; + bundle.Link.Add(new Bundle.LinkComponent { Relation = "previous", Url = prevUrl }); } return bundle; diff --git a/VigilCareRecordsAPI/Services/Interfaces/IDigitizationHistoryService.cs b/VigilCareRecordsAPI/Services/Interfaces/IDigitizationHistoryService.cs index a338cf5..fd18047 100644 --- a/VigilCareRecordsAPI/Services/Interfaces/IDigitizationHistoryService.cs +++ b/VigilCareRecordsAPI/Services/Interfaces/IDigitizationHistoryService.cs @@ -1,4 +1,5 @@ public interface IDigitizationHistoryService { - Task GetPatientHistoryAsync(Guid patientId); -} \ No newline at end of file + Task GetPatientHistoryAsync( + Guid patientId, int page = 1, int pageSize = 20); +} diff --git a/VigilCareRecordsAPI/Services/Interfaces/IDocumentStorageService.cs b/VigilCareRecordsAPI/Services/Interfaces/IDocumentStorageService.cs index 21bfe4f..9ef3c78 100644 --- a/VigilCareRecordsAPI/Services/Interfaces/IDocumentStorageService.cs +++ b/VigilCareRecordsAPI/Services/Interfaces/IDocumentStorageService.cs @@ -1,10 +1,13 @@ public interface IDocumentStorageService { - Task<(string objectKey, string sha256, long fileSize)> UploadAsync(Stream fileStream, string contentType, Guid batchId); - Task GetPresignedUrlAsync(string objectKey); - Task DownloadAsync(string objectKey); + Task<(string objectKey, string sha256, long fileSize)> UploadAsync( + Stream fileStream, string contentType, Guid batchId, CancellationToken ct = default); + Task GetPresignedUrlAsync(string objectKey, CancellationToken ct = default); + Task DownloadAsync(string objectKey, CancellationToken ct = default); /// Returns false when the object is missing from the bucket. - Task ObjectExistsAsync(string objectKey); + Task ObjectExistsAsync(string objectKey, CancellationToken ct = default); /// Uploads bytes only when the object key is not already present. - Task EnsureObjectAsync(string objectKey, byte[] content, string contentType); -} \ No newline at end of file + Task EnsureObjectAsync(string objectKey, byte[] content, string contentType, CancellationToken ct = default); + /// Ensures the configured bucket exists. Safe to call repeatedly; caches success in-process. + Task EnsureBucketAsync(CancellationToken ct = default); +} diff --git a/VigilCareRecordsAPI/Services/Interfaces/IFhirService.cs b/VigilCareRecordsAPI/Services/Interfaces/IFhirService.cs index c3e5473..89618af 100644 --- a/VigilCareRecordsAPI/Services/Interfaces/IFhirService.cs +++ b/VigilCareRecordsAPI/Services/Interfaces/IFhirService.cs @@ -16,7 +16,7 @@ public interface IFhirService string? patient, string? code, string? date, string? category, string? encounter, int count, int offset); - Task GetPatientEverythingAsync(Guid patientId); + Task GetPatientEverythingAsync(Guid patientId, int count = 100, int offset = 0); CapabilityStatement GetCapabilityStatement(); } \ No newline at end of file diff --git a/VigilCareRecordsAPI/Services/Interfaces/IOcrService.cs b/VigilCareRecordsAPI/Services/Interfaces/IOcrService.cs index c094017..3c0f64b 100644 --- a/VigilCareRecordsAPI/Services/Interfaces/IOcrService.cs +++ b/VigilCareRecordsAPI/Services/Interfaces/IOcrService.cs @@ -1,4 +1,5 @@ public interface IOcrService { - Task ExtractAsync(Stream documentStream, string contentType); -} \ No newline at end of file + Task ExtractAsync( + Stream documentStream, string contentType, CancellationToken ct = default); +} diff --git a/VigilCareRecordsAPI/Services/Interfaces/IPromotionService.cs b/VigilCareRecordsAPI/Services/Interfaces/IPromotionService.cs index 9abd43b..d719ae0 100644 --- a/VigilCareRecordsAPI/Services/Interfaces/IPromotionService.cs +++ b/VigilCareRecordsAPI/Services/Interfaces/IPromotionService.cs @@ -21,5 +21,6 @@ public interface IPromotionService /// Task GetPromotionResultAsync(Guid batchId); - Task PromoteAsync(Guid batchId, Guid actorUserId); + Task PromoteAsync( + Guid batchId, Guid actorUserId, CancellationToken ct = default); } \ No newline at end of file diff --git a/VigilCareRecordsAPI/Services/Ocr/AzureDocumentOcrService.cs b/VigilCareRecordsAPI/Services/Ocr/AzureDocumentOcrService.cs index 4d1c135..e8e1ec6 100644 --- a/VigilCareRecordsAPI/Services/Ocr/AzureDocumentOcrService.cs +++ b/VigilCareRecordsAPI/Services/Ocr/AzureDocumentOcrService.cs @@ -1,6 +1,5 @@ using Azure; using Azure.AI.DocumentIntelligence; -using Microsoft.Extensions.Options; public class AzureDocumentOcrService : IOcrService { @@ -56,26 +55,24 @@ public class AzureDocumentOcrService : IOcrService private readonly ILogger _logger; public AzureDocumentOcrService( - IOptions options, + DocumentIntelligenceClient client, ILogger logger) { - var opts = options.Value.Azure; - _client = new DocumentIntelligenceClient( - new Uri(opts.Endpoint), - new AzureKeyCredential(opts.ApiKey)); + _client = client; _logger = logger; } public async Task ExtractAsync( - Stream documentStream, string contentType) + Stream documentStream, string contentType, CancellationToken ct = default) { var sw = System.Diagnostics.Stopwatch.StartNew(); - var content = BinaryData.FromStream(documentStream); + var content = await BinaryData.FromStreamAsync(documentStream, ct); var operation = await _client.AnalyzeDocumentAsync( WaitUntil.Completed, "prebuilt-document", - content); + content, + cancellationToken: ct); var result = operation.Value; var fields = new List(); diff --git a/VigilCareRecordsAPI/Services/Ocr/ImagePreprocessor.cs b/VigilCareRecordsAPI/Services/Ocr/ImagePreprocessor.cs index 5bda250..ed7f8de 100644 --- a/VigilCareRecordsAPI/Services/Ocr/ImagePreprocessor.cs +++ b/VigilCareRecordsAPI/Services/Ocr/ImagePreprocessor.cs @@ -10,18 +10,20 @@ public class ImagePreprocessor private const int PdfRenderWidth = 2550; private const int PdfRenderHeight = 3300; - public Stream Preprocess(Stream input, string contentType) + public async Task PreprocessAsync( + Stream input, string contentType, CancellationToken ct = default) { Stream? pdfRenderStream = null; try { if (contentType == "application/pdf") { - pdfRenderStream = RenderPdfFirstPage(input); + pdfRenderStream = await RenderPdfFirstPageAsync(input, ct); input = pdfRenderStream; } - using var image = Image.Load(input); + ct.ThrowIfCancellationRequested(); + using var image = await Image.LoadAsync(input, ct); image.Mutate(ctx => ctx .Grayscale() @@ -29,22 +31,26 @@ public class ImagePreprocessor .BinaryThreshold(0.5f)); var output = new MemoryStream(); - image.SaveAsPng(output); + await image.SaveAsPngAsync(output, ct); output.Position = 0; return output; } finally { - pdfRenderStream?.Dispose(); + if (pdfRenderStream is not null) + await pdfRenderStream.DisposeAsync(); } } - private static Stream RenderPdfFirstPage(Stream pdfStream) + private static async Task RenderPdfFirstPageAsync( + Stream pdfStream, CancellationToken ct) { using var buffer = new MemoryStream(); - pdfStream.CopyTo(buffer); + await pdfStream.CopyToAsync(buffer, 81920, ct); var pdfBytes = buffer.ToArray(); + ct.ThrowIfCancellationRequested(); + using var docReader = DocLib.Instance.GetDocReader( pdfBytes, new PageDimensions(PdfRenderWidth, PdfRenderHeight)); @@ -59,7 +65,7 @@ public class ImagePreprocessor using var image = Image.LoadPixelData(rawBytes, width, height); var output = new MemoryStream(); - image.SaveAsPng(output); + await image.SaveAsPngAsync(output, ct); output.Position = 0; return output; } diff --git a/VigilCareRecordsAPI/Services/Ocr/OcrDraftPreFiller.cs b/VigilCareRecordsAPI/Services/Ocr/OcrDraftPreFiller.cs index 43173ad..42bdf5c 100644 --- a/VigilCareRecordsAPI/Services/Ocr/OcrDraftPreFiller.cs +++ b/VigilCareRecordsAPI/Services/Ocr/OcrDraftPreFiller.cs @@ -37,8 +37,12 @@ public class OcrDraftPreFiller } public async Task PreFillAsync( - Guid batchId, BatchType batchType, OcrExtractionResult extraction) + Guid batchId, + BatchType batchType, + OcrExtractionResult extraction, + CancellationToken ct = default) { + ct.ThrowIfCancellationRequested(); var requirements = BatchTypeFieldRequirements.ForBatchType(batchType); var confidentFields = extraction.Fields .Where(f => f.Confidence >= _options.ConfidenceThreshold) @@ -54,7 +58,7 @@ public class OcrDraftPreFiller if (requirements.ShowObservations) await PreFillObservationsAsync(batchId, confidentFields); - await _db.SaveChangesAsync(); + await _db.SaveChangesAsync(ct); } private async Task PreFillPatientAsync( diff --git a/VigilCareRecordsAPI/Services/Ocr/TesseractOcrService.cs b/VigilCareRecordsAPI/Services/Ocr/TesseractOcrService.cs index fac6819..0be7d37 100644 --- a/VigilCareRecordsAPI/Services/Ocr/TesseractOcrService.cs +++ b/VigilCareRecordsAPI/Services/Ocr/TesseractOcrService.cs @@ -2,7 +2,7 @@ using System.Text.RegularExpressions; using Microsoft.Extensions.Options; using Tesseract; -public class TesseractOcrService : IOcrService +public class TesseractOcrService : IOcrService, IDisposable { private static readonly (Regex Pattern, string FieldName)[] ClinicalPatterns = [ @@ -25,6 +25,9 @@ public class TesseractOcrService : IOcrService private readonly TesseractOcrOptions _options; private readonly ImagePreprocessor _preprocessor; private readonly ILogger _logger; + private readonly object _engineLock = new(); + private TesseractEngine? _engine; + private bool _disposed; public TesseractOcrService( IOptions options, @@ -37,28 +40,57 @@ public class TesseractOcrService : IOcrService } public async Task ExtractAsync( - Stream documentStream, string contentType) + Stream documentStream, string contentType, CancellationToken ct = default) { var sw = System.Diagnostics.Stopwatch.StartNew(); - using var preprocessed = _preprocessor.Preprocess(documentStream, contentType); - using var memStream = new MemoryStream(); - await preprocessed.CopyToAsync(memStream); - var imageBytes = memStream.ToArray(); + await using var preprocessed = await _preprocessor.PreprocessAsync( + documentStream, contentType, ct); - using var engine = new TesseractEngine( - _options.DataPath, _options.Language, EngineMode.Default); - using var pix = Pix.LoadFromMemory(imageBytes); - using var page = engine.Process(pix); + ct.ThrowIfCancellationRequested(); + + byte[] imageBytes; + if (preprocessed is MemoryStream ms) + { + imageBytes = ms.ToArray(); + } + else + { + using var copy = new MemoryStream(); + await preprocessed.CopyToAsync(copy, ct); + imageBytes = copy.ToArray(); + } + + ct.ThrowIfCancellationRequested(); + + string rawText; + float meanConfidence; + lock (_engineLock) + { + var engine = GetEngine(); + using var pix = Pix.LoadFromMemory(imageBytes); + using var page = engine.Process(pix); + rawText = page.GetText(); + meanConfidence = page.GetMeanConfidence(); + } - var rawText = page.GetText(); - var meanConfidence = page.GetMeanConfidence(); var fields = ParseClinicalText(rawText, meanConfidence); sw.Stop(); + _logger.LogDebug( + "Tesseract OCR finished in {DurationMs}ms with {FieldCount} fields", + sw.ElapsedMilliseconds, fields.Count); + return new OcrExtractionResult(fields, rawText, (int)sw.ElapsedMilliseconds); } + private TesseractEngine GetEngine() + { + ObjectDisposedException.ThrowIf(_disposed, this); + return _engine ??= new TesseractEngine( + _options.DataPath, _options.Language, EngineMode.Default); + } + private static List ParseClinicalText(string text, float meanConfidence) { var fields = new List(); @@ -87,4 +119,13 @@ public class TesseractOcrService : IOcrService return fields; } + + public void Dispose() + { + if (_disposed) + return; + _disposed = true; + _engine?.Dispose(); + _engine = null; + } } diff --git a/VigilCareRecordsAPI/Services/PromotionService.cs b/VigilCareRecordsAPI/Services/PromotionService.cs index 3c5fdcd..a7fb544 100644 --- a/VigilCareRecordsAPI/Services/PromotionService.cs +++ b/VigilCareRecordsAPI/Services/PromotionService.cs @@ -138,6 +138,7 @@ public class PromotionService : IPromotionService public async Task GetPromotionResultAsync(Guid batchId) { var batch = await _db.DigitizationBatches + .AsNoTracking() .FirstOrDefaultAsync(b => b.Id == batchId); if (batch is null) @@ -150,6 +151,7 @@ public class PromotionService : IPromotionService // Retrieve the live patient by looking up the encounter var encounter = await _db.Encounters + .AsNoTracking() .Include(e => e.Patient) .FirstOrDefaultAsync(e => e.Id == batch.PromotionEncounterId); @@ -159,6 +161,7 @@ public class PromotionService : IPromotionService "PROMOTION_ENCOUNTER_NOT_FOUND"); var observationIds = await _db.Observations + .AsNoTracking() .Where(o => o.SourceBatchId == batchId) .Select(o => o.Id) .ToArrayAsync(); @@ -324,8 +327,10 @@ public class PromotionService : IPromotionService if (draft.DateOfBirth.HasValue) { var sameDobPatients = await _db.Patients + .AsNoTracking() .Where(p => p.DateOfBirth == draft.DateOfBirth) .Select(p => new { p.Id, p.Mrn, p.FullName }) + .Take(50) .ToListAsync(); foreach (var candidate in sameDobPatients) @@ -603,13 +608,14 @@ public class PromotionService : IPromotionService return Task.FromResult((observationIds.ToArray(), outboxCount)); } - public async Task PromoteAsync(Guid batchId, Guid actorUserId) + public async Task PromoteAsync( + Guid batchId, Guid actorUserId, CancellationToken ct = default) { var stopwatch = Stopwatch.StartNew(); try { - await using var transaction = await _db.Database.BeginTransactionAsync(); + await using var transaction = await _db.Database.BeginTransactionAsync(ct); try { @@ -617,7 +623,7 @@ public class PromotionService : IPromotionService .Include(b => b.DraftPatient) .Include(b => b.DraftEncounter) .Include(b => b.DraftObservations) - .FirstOrDefaultAsync(b => b.Id == batchId); + .FirstOrDefaultAsync(b => b.Id == batchId, ct); if (batch is null) throw new NotFoundException("Batch not found.", "BATCH_NOT_FOUND"); @@ -635,8 +641,8 @@ public class PromotionService : IPromotionService var core = await ExecutePromotionCoreAsync( batch, actorUserId, enableRetroactiveAlerts, now); - await _db.SaveChangesAsync(); - await transaction.CommitAsync(); + await _db.SaveChangesAsync(ct); + await transaction.CommitAsync(ct); stopwatch.Stop(); DiagnosticsMetrics.PromotionDuration.Observe(stopwatch.Elapsed.TotalSeconds); diff --git a/VigilCareRecordsAPI/Services/UserDirectoryService.cs b/VigilCareRecordsAPI/Services/UserDirectoryService.cs index 35c4d61..dd788e4 100644 --- a/VigilCareRecordsAPI/Services/UserDirectoryService.cs +++ b/VigilCareRecordsAPI/Services/UserDirectoryService.cs @@ -15,6 +15,7 @@ public class UserDirectoryService : IUserDirectoryService return await query .OrderBy(u => u.FullName) + .Take(500) .Select(u => new UserSummaryResponse( u.Id, u.Username, diff --git a/VigilCareRecordsAPI/Services/VerificationService.cs b/VigilCareRecordsAPI/Services/VerificationService.cs index 54483c3..8d52c8c 100644 --- a/VigilCareRecordsAPI/Services/VerificationService.cs +++ b/VigilCareRecordsAPI/Services/VerificationService.cs @@ -28,7 +28,6 @@ public class VerificationService : IVerificationService Guid batchId, VerifyBatchRequest request, Guid verifierUserId) { var batch = await _db.DigitizationBatches - .Include(b => b.Events) .FirstOrDefaultAsync(b => b.Id == batchId); if (batch is null) diff --git a/VigilCareRecordsAPI/Services/WorkQueueService.cs b/VigilCareRecordsAPI/Services/WorkQueueService.cs index 82fe9a0..aa6baef 100644 --- a/VigilCareRecordsAPI/Services/WorkQueueService.cs +++ b/VigilCareRecordsAPI/Services/WorkQueueService.cs @@ -79,6 +79,9 @@ public class WorkQueueService : IWorkQueueService string sortBy, string sortDirection) { + pageSize = Math.Clamp(pageSize, 1, 100); + page = Math.Max(1, page); + if (!_allowedSortFields.Contains(sortBy)) throw new ValidationException( $"Invalid sortBy field '{sortBy}'. Allowed: {string.Join(", ", _allowedSortFields)}.", @@ -87,10 +90,8 @@ public class WorkQueueService : IWorkQueueService var totalCount = await query.CountAsync(); var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); - var sorted = ApplySort(query, sortBy, sortDirection); + var sorted = ApplySort(query.AsNoTracking(), sortBy, sortDirection); var items = await sorted - .Include(b => b.EnteredByUser) - .Include(b => b.Events) .Skip((page - 1) * pageSize) .Take(pageSize) .Select(b => new WorkQueueItemResponse( @@ -128,23 +129,21 @@ public class WorkQueueService : IWorkQueueService statusCounts[status.ToDbString()] = count; } - var pendingBatches = await _db.DigitizationBatches + var pendingQuery = _db.DigitizationBatches .AsNoTracking() - .Where(b => b.Status == BatchStatus.PendingVerification) - .Select(b => b.UpdatedAt) - .ToListAsync(); + .Where(b => b.Status == BatchStatus.PendingVerification); + var pendingCount = await pendingQuery.CountAsync(); double avgTimeInQueueMinutes = 0; double oldestPendingMinutes = 0; - if (pendingBatches.Count > 0) + if (pendingCount > 0) { - var ages = pendingBatches - .Select(updatedAt => (now - updatedAt).TotalMinutes) - .ToList(); - - avgTimeInQueueMinutes = ages.Average(); - oldestPendingMinutes = ages.Max(); + var oldestUpdatedAt = await pendingQuery.MinAsync(b => b.UpdatedAt); + oldestPendingMinutes = (now - oldestUpdatedAt).TotalMinutes; + avgTimeInQueueMinutes = await pendingQuery + .Select(b => (now - b.UpdatedAt).TotalMinutes) + .AverageAsync(); } var cutoff = now.AddHours(-24); @@ -177,7 +176,7 @@ public class WorkQueueService : IWorkQueueService _logger.LogDebug( "Work queue overview: {PendingCount} pending, avg queue {AvgMinutes:F1}m, reject rate {RejectRate:P1}", - pendingBatches.Count, avgTimeInQueueMinutes, rejectRate); + pendingCount, avgTimeInQueueMinutes, rejectRate); return new WorkQueueOverviewResponse { diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 16ba42c..a385444 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -48,6 +48,10 @@ services: options: { max-size: "50m", max-file: "5" } deploy: resources: + # 1G is a starting cap. Revisit after measuring peak working-set under + # concurrent document downloads + OCR with dotnet-counters + # (working-set, gc-heap-size, loh-size). See docs/plans/performance-hardening-overview.md. + # Do not raise this limit without measured peak evidence. limits: { memory: 1G } dashboard: diff --git a/docs/plans/README.md b/docs/plans/README.md new file mode 100644 index 0000000..f40fe6c --- /dev/null +++ b/docs/plans/README.md @@ -0,0 +1,118 @@ +# VigilCare Records — Phase Plans + +Implementation guides for the digitization platform. Product Phases **1–13 are complete** (API + initial workstation UI). Historical Phase 1–13 plan files are **not in this repository**; verification scripts under `scripts/` still reference those filenames for provenance only. + +## UI redesign (Phases 14–18) + +These phases redesign [`vigilcare-records-web`](../../vigilcare-records-web/) against the design specification. **No new backend behavior** — restyle, re-layout, and wire endpoints that already exist. + +| Phase | Plan | Focus | Status | +|---|---|---|---| +| 14 | [phase-14-plan.md](./phase-14-plan.md) | Design tokens, app shell (sidebar), login | Planned | +| 15 | [phase-15-plan.md](./phase-15-plan.md) | Shared UX primitives (status, OCR badges, SoD, sticky actions) | Planned | +| 16 | [phase-16-plan.md](./phase-16-plan.md) | Entry / Verification / Clinical Approval workstation layouts | Planned | +| 17 | [phase-17-plan.md](./phase-17-plan.md) | Intake, Cover Sheets, Live Capture, History, Dashboard, FHIR Explorer | Planned | +| 18 | [phase-18-plan.md](./phase-18-plan.md) | Surface unused existing APIs (events, work queues, Users admin) | Done | + +```mermaid +flowchart LR + P14[Phase14_Tokens_Shell_Login] + P15[Phase15_Shared_UX] + P16[Phase16_Workstation] + P17[Phase17_Support_Screens] + P18[Phase18_Unused_APIs] + P14 --> P15 --> P16 --> P17 --> P18 +``` + +Complete phases in order. Do not start Phase *N+1* until Phase *N* success criteria pass. + +## Performance hardening (Phases 19–22) + +Backend CPU/memory/reliability remediations from the VigilCareRecordsAPI performance audit. Master tracker: [performance-hardening-overview.md](./performance-hardening-overview.md). + +| Phase | Plan | Focus | Status | +|---|---|---|---| +| 19 | [phase-19-plan.md](./phase-19-plan.md) | Bounds, AsNoTracking, slim GetDocument, FHIR serializer | Done | +| 20 | [phase-20-plan.md](./phase-20-plan.md) | MinIO async/CT, history + `$everything` paging, overview aggregates | Done | +| 21 | [phase-21-plan.md](./phase-21-plan.md) | OCR CT, Azure singleton client, buffer reductions, RawText cap | Done | +| 22 | [phase-22-plan.md](./phase-22-plan.md) | Fuzzy Take cap, seed N+1/CT, PromoteAsync CT, ops notes | Done | + +```mermaid +flowchart LR + P19[Phase19_Bounds] + P20[Phase20_Memory] + P21[Phase21_OCR] + P22[Phase22_Polish] + P19 --> P20 --> P21 --> P22 +``` + +Prefer one PR per phase. Keep overview + phase-plan checklists updated in the same PR as the code. + +## Design source of truth + +- **Spec:** [../designs/design-doc.md](../designs/design-doc.md) +- **Mockups:** PNG files in [`../designs/`](../designs/) +- **Corrections override mockups:** design-doc §36 (no login role picker; no infra health on operator dashboard; OCR is assistive; consistent naming) + +### Image → screen mapping + +Rename mockup files when convenient so implementers do not rely on ChatGPT timestamps: + +| Suggested name | Screen | +|---|---| +| `01-login.png` | Login | +| `02-dashboard.png` | Queue / operator dashboard | +| `03-intake.png` | Intake | +| `04-data-entry.png` | Data Entry | +| `05-verification.png` | Verification | +| `06-clinical-approval.png` | Clinical Approval | +| `07-live-capture.png` | Live Capture | +| `08-patient-history.png` | Patient History | +| `09-cover-sheets.png` | Cover Sheets (if present) | +| `10-fhir-explorer.png` | FHIR Explorer (if present) | + +Until renamed, match mockups to design-doc sections by visual content, then apply §36 corrections before implementing. + +## Constraint (Phases 14–18) + +Allowed: + +- Visual system (colors, density, typography scale) — **keep Public Sans**; adopt navy/blue palette from design-doc +- App shell and navigation labels for **existing routes** +- Layout and copy changes on existing views +- Frontend-only OCR badge thresholds and SoD UI mirroring API rules +- Calling existing API endpoints the web UI underuses (`…/events`, `work-queue/*`, `users`) + +Not allowed without a later phase / API work: + +- New clinical or workflow backend rules +- Fake metrics (API/Redis/MinIO uptime cards, MEWS panels without data) +- SSO, forgot-password, password step-up unless already implemented +- OCR bounding-box click-to-highlight (no coordinates in API) + +## Deferred (needs new API or product scope) + +Design-doc / mockup items **out of scope for Phases 14–18**: + +| Item | Why deferred | +|---|---| +| Global ⌘K search across patients/batches/documents | No unified search API | +| Notifications center | No notifications API | +| Help Center | Content/product, not Records API | +| Supervision: Workload, Reports, Queues (as separate BI) | Beyond `work-queue/overview` | +| Master Data, Configuration, Audit Logs admin UIs | No dedicated admin APIs for config/master data | +| Infra service-health widgets on dashboard | Health probes are ops, not operator UX | +| Multi-document “18 of 76” batch progress | Batches are single-document today | +| OCR region highlight on scan | No field coordinates in OCR payload | +| Hospital SSO / Forgot password | Auth surface not implemented | +| Live Capture password re-auth / critical alert MEWS cards | Not in live-capture API contract as mocked | + +Track these in [../vigilcare-records-gap-analysis.md](../vigilcare-records-gap-analysis.md) or a future phase when APIs exist. + +## Related docs + +- [../vigilcare-records-prd.md](../vigilcare-records-prd.md) — product requirements and phase roadmap +- [../digitization-workstation-guide.md](../digitization-workstation-guide.md) — operator workflows +- [../vigilcare-records-gap-analysis.md](../vigilcare-records-gap-analysis.md) — hardening backlog +- [performance-hardening-overview.md](./performance-hardening-overview.md) — Phases 19–22 audit finding tracker +- [../../README.md](../../README.md) — API reference and quick start diff --git a/docs/plans/performance-hardening-overview.md b/docs/plans/performance-hardening-overview.md new file mode 100644 index 0000000..3defb2b --- /dev/null +++ b/docs/plans/performance-hardening-overview.md @@ -0,0 +1,70 @@ +# Performance Hardening Overview (Phases 19–22) + +Master tracker for CPU/memory/reliability remediations identified in the VigilCareRecordsAPI static performance audit. Status values: `Not started` | `In progress` | `Done`. + +**Do not invent runtime benchmarks.** Verify with code review, integration tests, and existing verification scripts. Measure with `dotnet-counters` / `dotnet-gcdump` only when validating Phase 20–21 under load. + +## Phase map + +| Audit phase | Product phase | Plan | Focus | Status | +|---|---|---|---|---| +| Phase 0 quick wins | **19** | [phase-19-plan.md](./phase-19-plan.md) | Bounds, tracking, over-fetch | Done | +| Phase 1 memory safety | **20** | [phase-20-plan.md](./phase-20-plan.md) | MinIO buffering, history / `$everything` paging | Done | +| Phase 2 OCR reliability | **21** | [phase-21-plan.md](./phase-21-plan.md) | OCR buffers, Azure client lifetime, cancellation | Done | +| Phase 3 polish | **22** | [phase-22-plan.md](./phase-22-plan.md) | Fuzzy match cap, seed N+1, promote CT, ops notes | Done | + +```mermaid +flowchart LR + P19[Phase19_Bounds] + P20[Phase20_Memory] + P21[Phase21_OCR] + P22[Phase22_Polish] + P19 --> P20 --> P21 --> P22 +``` + +Complete phases in order. Prefer one PR per phase; keep the phase plan checklist and this overview in sync in the same PR. + +## Finding → phase checklist + +| # | Severity | Finding | Phase | Key files | Status | +|---|---|---|---|---|---| +| 1 | Critical | MinIO download full-buffer + sync `CopyTo` | 20 | `DocumentStorageService.cs` | Done | +| 2 | High | OCR/PDF multiplies large in-memory copies | 21 | `ImagePreprocessor.cs`, `TesseractOcrService.cs`, `AzureDocumentOcrService.cs` | Done | +| 3 | High | Unbounded patient digitization history | 20 | `DigitizationHistoryService.cs` | Done | +| 4 | High | FHIR `$everything` loads all clinical rows | 20 | `FhirService.cs` | Done | +| 5 | High | Unclamped `pageSize` on list/queue endpoints | 19 | `BatchService`, `WorkQueueService`, `CoverSheetService` | Done | +| 6 | Medium | Azure OCR client scoped (handler churn) | 21 | `Program.cs`, `AzureDocumentOcrService.cs` | Done | +| 7 | Medium | Missing CT on download / OCR / promote | 20–22 | storage, OCR, `PromotionService` | Done | +| 8 | Medium | Unbounded cover-sheet batch PDF | 19 | `CoverSheetController`, `BatchPdfRequest` | Done | +| 9 | Medium | 1 GB container limit / OCR peak RAM | 22 | `docker-compose.prod.yml`, this overview | Done | +| 10 | Medium | FHIR Pretty serializer per response | 19 | `FhirJsonOutputFormatter.cs` | Done | +| 11 | Medium | Missing `AsNoTracking` / over-fetch | 19 | batch, cover sheet, verification, promotion reads | Done | +| 12 | Medium | Work-queue overview loads all pending timestamps | 20 | `WorkQueueService.cs` | Done | +| 13 | Medium | Upload full buffer + `EnsureBucket` every time | 20 | `DocumentStorageService.cs`, bootstrap | Done | +| 14 | Low–Med | Fuzzy match loads all same-DOB patients | 22 | `PromotionService.cs` | Done | +| 15 | Low–Med | Seed bootstrap MinIO N+1 | 22 | `SeedDocumentStorage.cs` | Done | +| 16 | Low | Tesseract engine per document | 21 | `TesseractOcrService.cs` | Done | + +## Diagnostic notes (ops) + +| Symptom | Tool | +|---|---| +| High working set / GC | `dotnet-counters` (`gc-heap-size`, `gen-2-gc-count`, `loh-size`, `working-set`); `dotnet-gcdump` | +| Thread starvation / blocking | `dotnet-counters` (`threadpool-*`); `dotnet-trace` | +| EF / large payloads | Response size checks; Npgsql/EF command logging at Warning in Production | +| Container OOM | Correlate with concurrent document downloads + OCR; see Phase 22 ops note | + +**Memory distinctions:** GC heap = managed; working set = process RSS (includes unmanaged Tesseract/ImageSharp/sockets). This hardening targets managed buffering and bounded queries first. + +## Non-goals + +- Premature GC / `DOTNET_gcServer` tuning without measured need +- Unbounded Parallel / Channel fan-out +- Replacing API document proxy with presigned-only delivery +- Frontend redesign beyond consumers broken by history / `$everything` paging + +## Related + +- [phase-19-plan.md](./phase-19-plan.md) … [phase-22-plan.md](./phase-22-plan.md) +- [../vigilcare-records-gap-analysis.md](../vigilcare-records-gap-analysis.md) +- [../vigilcare-records-prd.md](../vigilcare-records-prd.md) diff --git a/docs/plans/phase-14-plan.md b/docs/plans/phase-14-plan.md new file mode 100644 index 0000000..e8c06e9 --- /dev/null +++ b/docs/plans/phase-14-plan.md @@ -0,0 +1,139 @@ +# Phase 14 — Design System, App Shell, and Login + +## What exists + +From Phases 7–13 (workstation UI): + +- Teal primary palette + Public Sans in [`vigilcare-records-web/tailwind.config.js`](../../vigilcare-records-web/tailwind.config.js) +- Global utilities in [`vigilcare-records-web/src/assets/main.css`](../../vigilcare-records-web/src/assets/main.css) +- Top horizontal nav in [`AppHeader.vue`](../../vigilcare-records-web/src/components/AppHeader.vue) — each view embeds `` +- Centered card login in [`LoginView.vue`](../../vigilcare-records-web/src/views/LoginView.vue) — username/password only (no role picker) +- Role flags and default routes in [`stores/auth.ts`](../../vigilcare-records-web/src/stores/auth.ts) (`canIntake`, `canEntry`, `canVerify`, `canApprove`, `canLiveCapture`, `canSupervise`) +- Routes in [`router/index.ts`](../../vigilcare-records-web/src/router/index.ts) + +Design reference: [design-doc.md](../designs/design-doc.md) §§1–10, §35 (sidebar labels for **existing** routes only), §36 (login corrections). + +## What needs to be built + +Establish the visual foundation and application chrome so later phases only restyle content areas. **Keep Public Sans** (do not switch to Inter). Adopt the navy/blue token set from the design doc. Replace header-only navigation with a role-filtered left sidebar shell. Redesign login as a split brand + form layout without inventing auth features. + +Do not start Phase 15 until tokens, shell, and login meet the success criteria below. + +--- + +## Step 1 — Design tokens in Tailwind + CSS + +**[`tailwind.config.js`](../../vigilcare-records-web/tailwind.config.js)** — replace/extend `primary` and `clinical` to match design-doc §3: + +| Token | Hex | Use | +|---|---|---| +| Navy / sidebar | `#08254A` | Sidebar, logo backdrop | +| Primary blue | `#155EEF` | CTA, selected nav, links, focus | +| Primary blue hover | `#0B4FD6` | Hover | +| Soft blue | `#EEF4FF` | Selected rows, info panels | +| Page background | `#F7F9FC` | App canvas | +| Surface | `#FFFFFF` | Cards / panels | +| Strong / body / secondary / disabled text | `#101828` / `#344054` / `#667085` / `#98A2B3` | Typography | +| Border / strong border | `#E4E7EC` / `#D0D5DD` | Dividers | +| Success / warning / error | per design-doc §3 Semantic | Status + clinical | + +Keep `fontFamily.sans` as Public Sans. + +**[`main.css`](../../vigilcare-records-web/src/assets/main.css)** — map existing utility classes (`.btn-primary`, `.form-input`, `.card`, `.status-badge`, `.app-header`, `.nav-link`, `.split-pane`) onto the new tokens so legacy class names still work during migration. Add CSS variables if helpful for non-Tailwind consumers: + +```css +:root { + --vc-navy: #08254A; + --vc-primary: #155EEF; + --vc-primary-hover: #0B4FD6; + --vc-bg: #F7F9FC; + --vc-surface: #FFFFFF; + /* … */ +} +``` + +Radius: inputs/buttons ~6–8px; cards ~8–12px (design-doc §6). Shadows: minimal (design-doc §7). + +--- + +## Step 2 — `AppShell.vue` + page chrome + +Create [`vigilcare-records-web/src/components/AppShell.vue`](../../vigilcare-records-web/src/components/AppShell.vue): + +- Left sidebar (~240px, collapsible to icon rail): navy background, VigilCare Records logo, nav sections +- Main column: optional thin top bar (page title slot, user name, Sign Out) + `` for page content +- Login route must **not** use the shell + +**Sidebar items — only existing routes**, filtered by auth flags: + +| Label | Route | Flag | +|---|---|---| +| Intake | `/intake` | `canIntake` | +| Cover Sheets | `/cover-sheets` | `canIntake` | +| Data Entry | `/entry` | `canEntry` | +| Verification | `/verification` | `canVerify` | +| Clinical Approval | `/approval` | `canApprove` | +| Live Capture | `/live-capture` | `canLiveCapture` | +| Patient History | `/patients` | authenticated | +| Queue Dashboard | `/dashboard` | `canSupervise` | +| FHIR Explorer | `/fhir-explorer` | `canSupervise` | + +Optional “Dashboard” label: for administrators, Queue Dashboard is the home; do **not** add empty Supervision/Admin destinations (Users lands in Phase 18). + +Selected item: soft blue / primary treatment per design-doc §8. Collapse control at sidebar bottom. + +**Migrate views:** either wrap each authenticated view in `` or introduce a layout route. Prefer a single authenticated layout so `AppHeader` can shrink to a title/actions bar or be removed. + +Update [`AppHeader.vue`](../../vigilcare-records-web/src/components/AppHeader.vue) to stop duplicating nav links (title + actions only), or delete nav from it once shell owns navigation. + +Update router/tests that assert on header nav links ([`__tests__/router/guards.test.ts`](../../vigilcare-records-web/src/__tests__/router/guards.test.ts) and view tests) as needed. + +--- + +## Step 3 — Login redesign + +**[`LoginView.vue`](../../vigilcare-records-web/src/views/LoginView.vue)** — two-column desktop layout (design-doc §10): + +- **Left (~45%):** navy brand panel — logo, headline “Digitize. Verify. Trust.”, short subtext. Restrained illustration optional; avoid marketing feature clutter. +- **Right:** centered auth card (≈420–460px) — username, password, Sign In. Keep existing `auth.login` flow. + +**Must not include:** role selector, SSO button, forgot-password (unless those APIs exist — they do not). + +Mobile: stack brand above form or show form-only. + +--- + +## Step 4 — Naming consistency in chrome + +Use these labels everywhere in shell/header (design-doc §36): + +- **Data Entry** (not “Entry”) +- **Clinical Approval** (not “Approvals”) +- **Queue Dashboard** (supervisor overview) + +--- + +## Success criteria + +- [ ] Tailwind/CSS tokens match design-doc primary/neutral/semantic hex values; Public Sans unchanged +- [ ] Authenticated pages render navy left sidebar; nav filtered by role; no dead links +- [ ] Login is split layout; no role selector; existing seeded users still sign in +- [ ] Existing Vitest suites pass (`cd vigilcare-records-web && npm test`) after test updates for shell/nav +- [ ] Visual: white/gray surfaces, blue primary CTA, no purple SaaS gradient aesthetic + +## Out of scope + +- Supervision nav (Workload, Reports, Master Data, Configuration, Audit Logs) +- Users admin page (Phase 18) +- Workstation density / sticky actions (Phase 15–16) +- Restyling Intake/Entry forms beyond inheriting new button/input tokens + +## Verification + +1. `cd vigilcare-records-web && npm test` +2. Manual: log in as `intake1`, `entry1`, `verifier1`, `approver1` (or seed equivalents), `clinician1`, admin — confirm sidebar items match role and default landing routes still work +3. Manual: login page at desktop width shows brand + form; no role dropdown + +## Gate + +Do not start [Phase 15](./phase-15-plan.md) until success criteria above are met. diff --git a/docs/plans/phase-15-plan.md b/docs/plans/phase-15-plan.md new file mode 100644 index 0000000..5198c34 --- /dev/null +++ b/docs/plans/phase-15-plan.md @@ -0,0 +1,129 @@ +# Phase 15 — Shared UX Primitives + +## What exists + +From [Phase 14](./phase-14-plan.md): design tokens, `AppShell`, redesigned login. + +Still fragmented across views: + +- Status rendering via ad-hoc Tailwind classes / `.status-badge` in lists and forms +- OCR assist via [`useOcrFieldConfidence.ts`](../../vigilcare-records-web/src/composables/useOcrFieldConfidence.ts) (thresholds 0.85 / 0.7) and banners in [`EntryForm.vue`](../../vigilcare-records-web/src/components/EntryForm.vue) / [`VerificationForm.vue`](../../vigilcare-records-web/src/components/VerificationForm.vue) +- SoD: Verification subtitle shows truncated `enteredByUserId` only ([`VerificationView.vue`](../../vigilcare-records-web/src/views/VerificationView.vue)) +- Toasts: [`ToastContainer.vue`](../../vigilcare-records-web/src/components/ToastContainer.vue) + [`useToast.ts`](../../vigilcare-records-web/src/composables/useToast.ts) +- Empty/loading: inconsistent per view (`BatchList` loading text, etc.) + +Design reference: [design-doc.md](../designs/design-doc.md) §§9, 14 (OCR), 15 (SoD), 26–29, 31. + +## What needs to be built + +Reusable components and composables that Phases 16–17 apply. Prefer shared primitives over one-off markup. Frontend-only threshold tweaks for OCR badges are allowed; no API changes. + +Do not start Phase 16 until these primitives exist and have basic tests. + +--- + +## Step 1 — Status badge system + +Create e.g. [`StatusBadge.vue`](../../vigilcare-records-web/src/components/StatusBadge.vue): + +- Input: batch `status` string (`UPLOADED`, `IN_ENTRY`, `PENDING_VERIFICATION`, `AWAITING_CLINICAL_APPROVAL`, `VERIFIED`, `APPROVED`, `PROMOTED`, `REJECTED`, `CANCELLED`, …) +- Output: label (humanized) + semantic color + optional icon +- Must not rely on color alone (icon or text prefix) + +Wire into [`BatchList.vue`](../../vigilcare-records-web/src/components/BatchList.vue) and any header chips that show status. + +--- + +## Step 2 — Empty, loading, error patterns + +Create small presentational components (names flexible): + +| Component | Behavior | +|---|---| +| `EmptyState.vue` | Operational copy (“No batches are waiting for verification.”) + optional CTA | +| `SkeletonBlock.vue` / row skeletons | Prefer over full-page spinner (design-doc §27) | +| `InlineError.vue` | What happened / what was preserved / Retry action (design-doc §28) | + +Apply to queue lists as the first consumer; other views adopt in Phase 16–17. + +--- + +## Step 3 — Sticky workstation action bar + +Create e.g. [`WorkstationActionBar.vue`](../../vigilcare-records-web/src/components/WorkstationActionBar.vue): + +- Sticky bottom of the form/panel column +- Slots: `left` (e.g. Reject), `center` (Save Draft), `primary` (Submit…), `right` (Next) +- Uses Phase 14 primary/destructive button styles + +Not wired into Entry/Verification/Approval until Phase 16 — but component + Story/test fixture ready. + +--- + +## Step 4 — OCR field badges + +Update [`useOcrFieldConfidence.ts`](../../vigilcare-records-web/src/composables/useOcrFieldConfidence.ts): + +- Expose numeric confidence and a badge label helper (`OCR 98%`) in addition to CSS class +- Align thresholds with design-doc §14 (recommended): **95–100%** subtle green, **80–94%** amber, **<80%** strong warning (adjust from current 0.85 / 0.7) + +Update Entry/Verification forms to show compact badges beside fields when `ocrConfidence.fieldConfidences[path]` exists. Banner copy must say OCR is assistive, not authoritative (e.g. “Pre-filled by OCR — review against the scan”). + +**Out of this step:** click-to-highlight regions on the scan (no coordinates in API). + +--- + +## Step 5 — Separation of Duties banner + +Create e.g. [`SeparationOfDutiesBanner.vue`](../../vigilcare-records-web/src/components/SeparationOfDutiesBanner.vue): + +Props: `enteredByUserId`, `enteredByUserName?`, `currentUserId`, `currentUserName?` + +- When IDs differ: restrained info banner — “Separation of Duties Enforced” + entered by / current verifier +- When same: blocking message — “You cannot verify a batch you entered.” Emit/`disabled` flag for parent to disable Pass actions + +Use `enteredByUserId` from batch detail today; names optional until API/history provides them. + +Unit-test both states. + +--- + +## Step 6 — Confirmation dialog pattern + +Create e.g. [`ConfirmDialog.vue`](../../vigilcare-records-web/src/components/ConfirmDialog.vue) for **meaningful** actions only: + +- Approve & Promote +- Reject batch / return for rework +- Cancel batch / delete unsubmitted upload (if used) + +Props: title, body, confirmLabel, variant (`primary` | `danger`). Do not use for harmless navigation. + +Approval copy must state promotion into live clinical tables (design-doc §16). + +--- + +## Success criteria + +- [ ] `StatusBadge` covers all batch statuses used in the UI +- [ ] Empty/skeleton/error components exist and are used at least on one queue list +- [ ] `WorkstationActionBar` renders sticky with slots; documented for Phase 16 +- [ ] OCR badges show percentage + threshold colors; banner is non-authoritative +- [ ] SoD banner blocks same-user verify in UI (in addition to API 409) +- [ ] Confirm dialog used for at least one destructive/irreversible path or ready with tests +- [ ] `npm test` passes; new component tests under `src/__tests__/components/` + +## Out of scope + +- Full Entry/Verification/Approval layout redesign (Phase 16) +- Batch events audit panel (Phase 18) +- Changing verification/approval API contracts + +## Verification + +1. `cd vigilcare-records-web && npm test` +2. Manual: open a batch with OCR confidence (OCR enabled env) — badges visible +3. Manual: as entry clerk who entered a batch, open verification for that batch — SoD banner + disabled Pass (if seed allows; else unit test covers) + +## Gate + +Do not start [Phase 16](./phase-16-plan.md) until success criteria above are met. diff --git a/docs/plans/phase-16-plan.md b/docs/plans/phase-16-plan.md new file mode 100644 index 0000000..f66f92a --- /dev/null +++ b/docs/plans/phase-16-plan.md @@ -0,0 +1,138 @@ +# Phase 16 — Core Digitization Workstation (Entry, Verification, Approval) + +## What exists + +From [Phase 14](./phase-14-plan.md) + [Phase 15](./phase-15-plan.md): shell, tokens, shared primitives. + +Workstation screens today: + +| View | Files | Layout | +|---|---|---| +| Data Entry | [`EntryView.vue`](../../vigilcare-records-web/src/views/EntryView.vue), [`EntryForm.vue`](../../vigilcare-records-web/src/components/EntryForm.vue) | Queue list **or** scan + form split | +| Verification | [`VerificationView.vue`](../../vigilcare-records-web/src/views/VerificationView.vue), [`VerificationForm.vue`](../../vigilcare-records-web/src/components/VerificationForm.vue) | Same pattern | +| Clinical Approval | [`ApprovalView.vue`](../../vigilcare-records-web/src/views/ApprovalView.vue) | Same pattern + approval panel | +| Scan | [`ScanViewer.vue`](../../vigilcare-records-web/src/components/ScanViewer.vue) | Document iframe/blob | + +Stores/API: [`stores/batches.ts`](../../vigilcare-records-web/src/stores/batches.ts) — draft CRUD, submit, verify, reject, approve. **Do not change endpoint contracts.** + +Design reference: [design-doc.md](../designs/design-doc.md) §§14–16, §22 (density), §34 (evidence hierarchy). + +## What needs to be built + +Redesign the three high-risk screens for dense, scan-first workflows. Same store methods and routes. Apply Phase 15 SoD, OCR badges, sticky action bars, status badges, confirm dialogs. + +Do not start Phase 17 until Entry, Verification, and Clinical Approval meet success criteria. + +--- + +## Step 1 — Shared workstation layout pattern + +Introduce a consistent layout (component or shared structure in each view): + +1. **Optional left rail:** queue / document list (when useful) — can show assigned/pending items while a batch is open, without new APIs (reuse current list payloads) +2. **Center:** source scan (`ScanViewer`) — dominant evidence (Level 1) +3. **Right:** structured form / draft / clinical summary — Levels 2–4 + +Queue-only mode (no `batchId`) remains a full-width list with EmptyState/skeletons. + +Target desktop width ≥1280px; do not force phone layouts for these flows (design-doc §32). + +--- + +## Step 2 — Scan viewer chrome + +Polish [`ScanViewer.vue`](../../vigilcare-records-web/src/components/ScanViewer.vue): + +- Neutral page surface, subtle page shadow only +- Controls: zoom, fit width (keep existing capabilities; add only if trivial) +- Loading/error via Phase 15 patterns +- No decorative overlays or “AI confidence” chrome on the image itself + +--- + +## Step 3 — Data Entry + +**[`EntryView.vue`](../../vigilcare-records-web/src/views/EntryView.vue) / [`EntryForm.vue`](../../vigilcare-records-web/src/components/EntryForm.vue):** + +- Dense form sections driven by existing `fieldRequirements` (unchanged logic) +- OCR badges + assistive banner (Phase 15) +- Sticky `WorkstationActionBar`: + - Left: reject/flag if already supported; otherwise omit + - Center: Save Draft (existing autosave/save) + - Primary: **Submit for Verification** + - Right: optional next-batch navigation if list context exists +- Autosave feedback per design-doc §9 (use existing save behavior; improve visible “Last saved” if data available) + +Update tests in [`__tests__/components/EntryForm.test.ts`](../../vigilcare-records-web/src/__tests__/components/EntryForm.test.ts). + +--- + +## Step 4 — Verification + +**[`VerificationView.vue`](../../vigilcare-records-web/src/views/VerificationView.vue) / [`VerificationForm.vue`](../../vigilcare-records-web/src/components/VerificationForm.vue):** + +- Mount `SeparationOfDutiesBanner`; disable Pass when same user +- Source scan + draft with validation markers remain primary; avoid analytics chrome +- Sticky actions: + - **Pass Verification** when pass selected + - **Return for Rework** when reject selected (with reason — existing reject flow) +- Avoid generic “Submit Decision” labeling +- Confirm dialog for reject if not already modal-confirmed + +Update [`__tests__/components/VerificationForm.test.ts`](../../vigilcare-records-web/src/__tests__/components/VerificationForm.test.ts). + +--- + +## Step 5 — Clinical Approval + +**[`ApprovalView.vue`](../../vigilcare-records-web/src/views/ApprovalView.vue):** + +- Visually distinct from verification (stronger clinical framing, not a clone with purple chip only) +- Show scan + verified draft summary; highlight high-stakes fields from existing draft data when present +- Retroactive alerts toggle: keep existing `enableRetroactiveAlerts` behavior; copy per design-doc §16 +- Primary: **Approve & Promote** via `ConfirmDialog` stating promotion to live clinical tables +- Destructive: **Reject Batch** with reason +- Post-success: show promotion result if already returned by API (`promotion-result` / approve response fields) — polish presentation only + +--- + +## Step 6 — Evidence hierarchy (copy + visual weight) + +Across all three screens, reinforce design-doc §34: + +1. Source scan +2. Entered / verified structured data +3. Verification / approval decision controls +4. Promotion outcome + +Do not let secondary panels overpower the scan or draft. + +--- + +## Success criteria + +- [ ] Entry, Verification, Approval use shell + dense split layout; sticky CTAs with design-doc labels +- [ ] SoD enforced in Verification UI; OCR badges on Entry/Verification when confidence present +- [ ] Approve & Promote uses confirmation copy about live promotion +- [ ] No new API calls beyond what stores already perform (except optional read-only list for queue rail using existing list/queue fetch) +- [ ] Component/view tests updated and `npm test` passes +- [ ] Manual: walk upload→entry→verify→approve on seed data still works end-to-end + +## Out of scope + +- OCR region click-to-highlight +- Multi-document batch progress (18/76) +- Switching queues to `work-queue/*` endpoints (Phase 18) +- Batch events audit panel (Phase 18) +- Intake / Live Capture / Dashboard restyle (Phase 17) + +## Verification + +1. `cd vigilcare-records-web && npm test` +2. Manual E2E with seeded users through Entry → Verification → Clinical Approval +3. Manual: same-user verify attempt shows SoD block +4. Spot-check against design-doc §§14–16 (ignore mockup infra/analytics clutter) + +## Gate + +Do not start [Phase 17](./phase-17-plan.md) until success criteria above are met. diff --git a/docs/plans/phase-17-plan.md b/docs/plans/phase-17-plan.md new file mode 100644 index 0000000..2e8c60e --- /dev/null +++ b/docs/plans/phase-17-plan.md @@ -0,0 +1,128 @@ +# Phase 17 — Supporting Screens + +## What exists + +From [Phases 14–16](./phase-16-plan.md): shell, tokens, primitives, redesigned Entry/Verification/Approval. + +Supporting views still use pre-redesign layout density and teal-era patterns (they inherit tokens if Phase 14 remapped utilities, but structure/copy need alignment): + +| View | File | Role | +|---|---|---| +| Intake | [`IntakeView.vue`](../../vigilcare-records-web/src/views/IntakeView.vue) | Upload, cover sheet lookup, assign | +| Cover Sheets | [`CoverSheetView.vue`](../../vigilcare-records-web/src/views/CoverSheetView.vue) | Generate / list / PDF | +| Live Capture | [`LiveCaptureView.vue`](../../vigilcare-records-web/src/views/LiveCaptureView.vue) | Bedside observations | +| Patient History | [`PatientHistoryView.vue`](../../vigilcare-records-web/src/views/PatientHistoryView.vue) | Digitization timeline | +| Queue Dashboard | [`QueueDashboardView.vue`](../../vigilcare-records-web/src/views/QueueDashboardView.vue) | `work-queue/overview` | +| FHIR Explorer | [`FhirExplorerView.vue`](../../vigilcare-records-web/src/views/FhirExplorerView.vue) | FHIR read UI | + +Design reference: [design-doc.md](../designs/design-doc.md) §§11–13, 17–20; §36 (dashboard: work first, no infra health). + +## What needs to be built + +Restyle and restructure these screens with **existing data and actions only**. No fake metrics, SSO, MEWS, or multi-doc chrome. + +Do not start Phase 18 until these screens meet success criteria. + +--- + +## Step 1 — Intake + +**[`IntakeView.vue`](../../vigilcare-records-web/src/views/IntakeView.vue)** (design-doc §12): + +- Main column (~70%): upload zone + batch details (type, track, patient link, cover sheet code) — existing fields +- Right (~30%): recent uploads / guidance +- States: idle, uploading, success, error via Phase 15 patterns +- Keep assign clerk dialog ([`AssignClerkDialog.vue`](../../vigilcare-records-web/src/components/AssignClerkDialog.vue)) + +Update [`__tests__/views/IntakeView.test.ts`](../../vigilcare-records-web/src/__tests__/views/IntakeView.test.ts) as needed. + +--- + +## Step 2 — Cover Sheets + +**[`CoverSheetView.vue`](../../vigilcare-records-web/src/views/CoverSheetView.vue)** (design-doc §13): + +- Generation form + preview + existing list table +- Clear primary CTA for generate / print PDF (existing endpoints) +- StatusBadge for any status columns +- Update [`__tests__/views/CoverSheetView.test.ts`](../../vigilcare-records-web/src/__tests__/views/CoverSheetView.test.ts) + +--- + +## Step 3 — Live Capture + +**[`LiveCaptureView.vue`](../../vigilcare-records-web/src/views/LiveCaptureView.vue)** (design-doc §17): + +- Keep New / Existing encounter modes and attestation checkbox flows already implemented +- Clearer section hierarchy: patient → encounter → observations → attestation → submit +- **Do not add:** password re-entry step, MEWS/critical alert side panels, fake “submission outcome” cards without API data +- Prefer table density for observations consistent with Phase 14 tokens + +--- + +## Step 4 — Patient History + +**[`PatientHistoryView.vue`](../../vigilcare-records-web/src/views/PatientHistoryView.vue)** (design-doc §18): + +- Search + timeline using existing digitization-history payload +- StatusBadge for batch statuses +- Audit trail presentation: actor / timestamp / event type already in payload — improve readability +- Promotion attribution: show names/roles from history response; do not invent “entry clerk promoted” if data shows approver (design-doc §36) + +--- + +## Step 5 — Queue Dashboard + +**[`QueueDashboardView.vue`](../../vigilcare-records-web/src/views/QueueDashboardView.vue)** (design-doc §§11, 19; §36): + +Data source remains `GET work-queue/overview` only: + +- `statusCounts` +- `averageTimeInQueueMinutes` +- `rejectRate` +- `oldestPendingVerificationMinutes` +- Existing batch list section if already loaded via batch list API + +**Prioritize work metrics** (pending entry, in entry, pending verification, oldest age, reject rate). + +**Must not add:** PostgreSQL / Redis / MinIO / FHIR API uptime cards, vanity trend sparklines without data, Quick Actions that deep-link nowhere. + +Supervisor framing is fine; this is the administrator dashboard today (`canSupervise`). + +--- + +## Step 6 — FHIR Explorer + +**[`FhirExplorerView.vue`](../../vigilcare-records-web/src/views/FhirExplorerView.vue)** (design-doc §20): + +- Visual polish only: shell, typography, tables, JSON panel +- Keep existing fhirClient behavior +- Update [`__tests__/views/FhirExplorerView.test.ts`](../../vigilcare-records-web/src/__tests__/views/FhirExplorerView.test.ts) if selectors change + +--- + +## Success criteria + +- [ ] All six views render inside AppShell with consistent tokens +- [ ] Intake/Cover Sheets usable for existing upload/generate flows +- [ ] Live Capture submit/attestation still works; no invented clinical alert UI +- [ ] Dashboard shows only overview-backed metrics (no infra health) +- [ ] Patient History timeline/audit readable; StatusBadges applied +- [ ] FHIR Explorer functional parity preserved +- [ ] `npm test` passes + +## Out of scope + +- Users admin, batch events panel, work-queue endpoint swap (Phase 18) +- Global search, notifications, reports, master data +- Changing Live Capture API to require password confirm if not already required by backend + +## Verification + +1. `cd vigilcare-records-web && npm test` +2. Manual smoke per role: intake upload, cover sheet generate, live capture observation, patient search/history, admin dashboard refresh, FHIR metadata/search +3. Confirm dashboard has **no** service-uptime widgets + +## Gate + +Do not start [Phase 18](./phase-18-plan.md) until success criteria above are met. diff --git a/docs/plans/phase-18-plan.md b/docs/plans/phase-18-plan.md new file mode 100644 index 0000000..8dce142 --- /dev/null +++ b/docs/plans/phase-18-plan.md @@ -0,0 +1,110 @@ +# Phase 18 — Surface Existing Unused APIs + +## What exists + +From [Phases 14–17](./phase-17-plan.md): redesigned UI chrome and screens. + +Backend already provides capabilities the web UI underuses or does not expose: + +| API | Controller | Current web usage | +|---|---|---| +| `GET /api/v1/digitization-batches/{id}/events` | [`DigitizationBatchesController`](../../VigilCareRecordsAPI/Controllers/DigitizationBatchesController.cs) | Not shown on workstation screens (history has embedded audit) | +| `GET /api/v1/work-queue/entry` | [`WorkQueueController`](../../VigilCareRecordsAPI/Controllers/WorkQueueController.cs) | Entry uses generic batch list + `assignedTo` | +| `GET /api/v1/work-queue/verification` | same | Verification filters `status: PENDING_VERIFICATION` via list | +| `GET /api/v1/work-queue/clinical-approval` | same | Approval filters status via list | +| `GET/POST/PATCH /api/v1/users`, reset-password | [`UsersController`](../../VigilCareRecordsAPI/Controllers/UsersController.cs) | List-by-role used for assign clerks; **no admin Users page** | + +Design reference: [design-doc.md](../designs/design-doc.md) §§19, 30, 35 (Users under Administration — only where API exists). + +## What needs to be built + +Wire these existing endpoints into the redesigned UI. **No new backend endpoints or behavior.** This is the last phase of the UI redesign track. + +--- + +## Step 1 — Batch audit / events panel + +Add a collapsible **Audit trail** panel on Entry / Verification / Approval (and optionally Intake batch detail) that loads: + +`GET digitization-batches/{id}/events?pageSize=…` + +- Cursor pagination if `hasMore` / cursor returned +- Display: event type, actor, timestamp, relevant payload summary +- Matches design-doc §30 (actor, role if present, timestamp, state transitions) + +Extend [`stores/batches.ts`](../../vigilcare-records-web/src/stores/batches.ts) with `fetchEvents(batchId, cursor?)`. Types in [`types/index.ts`](../../vigilcare-records-web/src/types/index.ts) as needed from API response shape. + +--- + +## Step 2 — Dedicated work-queue fetches + +Prefer age-sorted work queues for operator lists: + +| Screen | Endpoint | Roles (API) | +|---|---|---| +| Data Entry queue | `work-queue/entry` | `DATA_ENTRY_CLERK`, `ADMINISTRATOR` | +| Verification queue | `work-queue/verification` | `VERIFIER`, `CLINICAL_APPROVER`, `ADMINISTRATOR` | +| Clinical Approval queue | `work-queue/clinical-approval` | `CLINICAL_APPROVER`, `ADMINISTRATOR` | + +Implementation notes: + +- Add store methods or thin API helpers; map response items into existing `BatchList` props +- Preserve open-batch-by-id routes (`/entry/:batchId`, etc.) +- Keep overview dashboard on `work-queue/overview` (already used) + +Update batch store tests accordingly. + +--- + +## Step 3 — Administrator Users page + +New view e.g. [`UsersView.vue`](../../vigilcare-records-web/src/views/UsersView.vue): + +- Route `/users`, `meta.roles: ['ADMINISTRATOR']` +- Sidebar link under Administration (or after FHIR Explorer) when `canSupervise` / admin role +- Features backed by existing API: + - List users (`GET /users`, optional `?role=`) + - Create user (`POST /users`) + - Update fullName / role / isActive (`PATCH /users/{id}`) + - Reset password (`POST /users/{id}/reset-password`) +- Optional: self-service change password via `POST /users/me/change-password` from profile menu (nice-to-have if time) + +Use Phase 15 ConfirmDialog for reset-password. Forms: Phase 14 tokens. + +Update router guards tests for the new route. + +--- + +## Step 4 — Navigation and docs touch-up + +- AppShell: add **Users** for administrators only +- Do **not** add Workload / Reports / Master Data / Configuration / Audit Logs links (still no APIs) +- Update [plans README](./README.md) status for Phase 18 → Done when complete; PRD status table when implementing (not required in this docs-only authoring pass) + +--- + +## Success criteria + +- [x] Events panel loads and paginates audit events for an open batch +- [x] Entry / Verification / Approval queues use `work-queue/*` endpoints (oldest-first behavior matches API) +- [x] `/users` admin CRUD + reset password works against running API for `ADMINISTRATOR` +- [x] Sidebar shows Users only for admin; no dead Supervision links +- [x] `npm test` passes; add tests for Users view and events/queue store methods + +## Out of scope + +- Everything in [README deferred table](./README.md#deferred-needs-new-api-or-product-scope) +- New reporting/analytics endpoints +- Changing SoD or promotion rules on the server + +## Verification + +1. `cd vigilcare-records-web && npm test` +2. Manual: open batch → Audit trail shows create/assign/submit/verify events from seed or fresh workflow +3. Manual: compare queue order to API (`curl` work-queue vs UI) +4. Manual: as admin, create user, patch role, reset password; as new user, log in +5. Confirm non-admin cannot open `/users` (guard redirect) + +## Gate + +UI redesign track complete when success criteria pass. Further work requires new product phases (API + UI) for deferred design-doc items. diff --git a/docs/plans/phase-19-plan.md b/docs/plans/phase-19-plan.md new file mode 100644 index 0000000..945fd51 --- /dev/null +++ b/docs/plans/phase-19-plan.md @@ -0,0 +1,87 @@ +# Phase 19 — Bounds and Read-Path Hygiene + +## What exists + +- List endpoints accept `page` / `pageSize` without a service-layer clamp: [`BatchService.ListAsync`](../../VigilCareRecordsAPI/Services/BatchService.cs), [`WorkQueueService.BuildQueueResponseAsync`](../../VigilCareRecordsAPI/Services/WorkQueueService.cs), [`CoverSheetService.ListAsync`](../../VigilCareRecordsAPI/Services/CoverSheetService.cs). [`BatchEventService`](../../VigilCareRecordsAPI/Services/BatchEventService.cs) already clamps to 200. +- Cover-sheet create clamps `Count` to 100; [`GenerateBatchPdf`](../../VigilCareRecordsAPI/Controllers/CoverSheetController.cs) accepts unbounded [`BatchPdfRequest.CoverSheetIds`](../../VigilCareRecordsAPI/Models/Records/CoverSheet/BatchPdfRequest.cs). +- Read queries often omit `AsNoTracking`; [`VerificationService.VerifyAsync`](../../VigilCareRecordsAPI/Services/VerificationService.cs) includes unused `Events`. +- [`GetDocument`](../../VigilCareRecordsAPI/Controllers/DigitizationBatchesController.cs) calls full [`GetByIdAsync`](../../VigilCareRecordsAPI/Services/BatchService.cs) (drafts + observations). +- [`FhirJsonOutputFormatter`](../../VigilCareRecordsAPI/Infrastructure/Fhir/FhirJsonOutputFormatter.cs) constructs a Pretty serializer per response. + +Tracker: [performance-hardening-overview.md](./performance-hardening-overview.md). + +## What needs to be built + +Prevent single-request memory/CPU blowups and cut unnecessary EF tracking and over-fetch. Low risk; no MinIO/OCR/history pagination in this phase. + +Do not start [Phase 20](./phase-20-plan.md) until success criteria below pass. + +--- + +## Step 1 — Clamp pagination in services + +In `BatchService.ListAsync`, `WorkQueueService.BuildQueueResponseAsync`, and `CoverSheetService.ListAsync`: + +```csharp +pageSize = Math.Clamp(pageSize, 1, 100); +page = Math.Max(1, page); +``` + +Clamp in the **service** layer so all callers are safe. + +--- + +## Step 2 — Cap batch cover-sheet PDF IDs + +- Reject or truncate `CoverSheetIds` to max **100** (align with create clamp) in `CoverSheetController.GenerateBatchPdf` or `CoverSheetService.GetByIdsAsync`. +- Prefer `ValidationException` when count > 100 so clients get a clear error. + +--- + +## Step 3 — AsNoTracking and unused Includes + +- Add `AsNoTracking()` on read-only paths: batch list; cover-sheet lookups that do not mutate; promotion result reads where tracked entities are not updated. +- Remove `.Include(b => b.Events)` from `VerificationService.VerifyAsync` if Events are unused. +- Keep tracking on mutation paths (verify/approve/assign/promote). + +--- + +## Step 4 — Slim GetDocument + +- Stop calling `GetByIdAsync` for document streaming. +- Query only `DocumentRef` (and not-found) plus `ScannedDocuments.ContentType`. +- Preserve document-access audit behavior. + +--- + +## Step 5 — FHIR serializer reuse + +- Static/`Lazy` `FhirJsonSerializer` with `Pretty = false`. +- Avoid allocating a new serializer (and pretty whitespace) on every FHIR write. + +--- + +## Success criteria + +- [x] `pageSize=1000000` on batch list / work-queue / cover-sheet list returns ≤ 100 items +- [x] Batch PDF with > 100 IDs fails validation (or is hard-capped) — documented in API behavior +- [x] `GetDocument` does not load draft graphs; still returns 200 for seeded batches with objects +- [x] Verification still succeeds without loading Events collection +- [x] FHIR JSON responses are compact (not pretty-printed) +- [x] `dotnet test` on `VigilCareRecordsAPI.Tests` passes + +## Out of scope + +- MinIO async download / upload streaming (Phase 20) +- Patient history / `$everything` pagination (Phase 20) +- OCR changes (Phase 21) + +## Verification + +1. `dotnet test VigilCareRecordsAPI.Tests/VigilCareRecordsAPI.Tests.csproj` +2. Manual or test: list with oversized `pageSize`; GetDocument on a seeded batch; FHIR Patient read payload is single-line/compact JSON +3. Update overview finding statuses 5, 8, 10, 11 → Done when this phase merges + +## Gate + +Do not start [Phase 20](./phase-20-plan.md) until success criteria above are met. diff --git a/docs/plans/phase-20-plan.md b/docs/plans/phase-20-plan.md new file mode 100644 index 0000000..5c74217 --- /dev/null +++ b/docs/plans/phase-20-plan.md @@ -0,0 +1,88 @@ +# Phase 20 — Memory Safety (MinIO + Unbounded Clinical Payloads) + +## What exists + +- [`DocumentStorageService.DownloadAsync`](../../VigilCareRecordsAPI/Services/DocumentStorageService.cs) buffers the full object and uses sync `CopyTo` in the MinIO callback; no `CancellationToken` on the interface. +- Upload copies the full stream then hashes; `EnsureBucketAsync` runs on every upload. +- [`GetDocument`](../../VigilCareRecordsAPI/Controllers/DigitizationBatchesController.cs) calls `ObjectExistsAsync` then downloads. +- [`DigitizationHistoryService.GetPatientHistoryAsync`](../../VigilCareRecordsAPI/Services/DigitizationHistoryService.cs) loads all batches + drafts + events (tracked). +- [`FhirService.GetPatientEverythingAsync`](../../VigilCareRecordsAPI/Services/FhirService.cs) loads all encounters and observations. +- [`WorkQueueService.GetOverviewAsync`](../../VigilCareRecordsAPI/Services/WorkQueueService.cs) materializes every pending `UpdatedAt`. + +Requires [Phase 19](./phase-19-plan.md). Tracker: [performance-hardening-overview.md](./performance-hardening-overview.md). + +## What needs to be built + +Reduce peak RAM for document I/O and history/FHIR dumps. Keep returning `MemoryStream` from download for OCR compatibility; true HTTP pipe-through is out of scope unless required after measuring. + +Do not start [Phase 21](./phase-21-plan.md) until success criteria below pass. + +--- + +## Step 1 — Async MinIO download + CancellationToken + +- Add `CancellationToken` to `IDocumentStorageService` download/upload (and call sites). +- In `DownloadAsync`, use async copy inside the MinIO callback (`CopyToAsync` + CT). +- Propagate CT from controllers / OCR hosted service where already available. + +--- + +## Step 2 — Upload hashing and bucket ensure + +- Hash while buffering once (single `MemoryStream` pass) where practical. +- Ensure bucket once at bootstrap ([`AppBootstrapHostedService`](../../VigilCareRecordsAPI/BackgroundServices/AppBootstrapHostedService.cs)) and drop per-upload `EnsureBucketAsync`, or cache a process-lifetime “bucket ready” flag. + +--- + +## Step 3 — GetDocument without redundant StatObject + +- Remove `ObjectExistsAsync` when missing objects can be expressed as 404 from download failure / MinIO not-found. + +--- + +## Step 4 — Paginate patient digitization history + +- Add `page` / `pageSize` (default 20, max 50) to history API + service. +- Use `AsNoTracking`; project summaries. +- Cap audit trail size per entry (e.g. last N events) or defer full trail so payload stays bounded. +- Update DTO / controller / web client callers if they assume an unpaged full list. + +--- + +## Step 5 — FHIR `$everything` paging + +- Honor `_count` (default 100, max 500) with Bundle `next` link. +- Do not load the entire observation history in one query/response. + +--- + +## Step 6 — Work-queue overview SQL aggregates + +- Replace pending `UpdatedAt` `ToListAsync` with EF aggregates for average age and oldest pending (avg / min `UpdatedAt`). + +--- + +## Success criteria + +- [x] Download path uses async copy and accepts CT +- [x] Bucket ensure is not invoked on every upload +- [x] History returns `Entries.Count ≤ pageSize` with accurate total count metadata +- [x] `$everything?_count=10` returns ≤ 10 resource entries (plus paging metadata as designed) +- [x] Overview no longer materializes all pending timestamps in memory +- [x] GetDocument / OCR download still work in integration tests +- [x] `dotnet test` passes; Phase 11 FHIR script still green if run + +## Out of scope + +- Tesseract engine reuse / Azure singleton (Phase 21) +- Fuzzy match / seed N+1 (Phase 22) + +## Verification + +1. `dotnet test VigilCareRecordsAPI.Tests/VigilCareRecordsAPI.Tests.csproj` +2. `./scripts/run-vigilcare-records-phase-11-verification.sh` (optional but recommended) +3. Update overview findings 1, 3, 4, 7 (storage CT), 12, 13 → Done when this phase merges + +## Gate + +Do not start [Phase 21](./phase-21-plan.md) until success criteria above are met. diff --git a/docs/plans/phase-21-plan.md b/docs/plans/phase-21-plan.md new file mode 100644 index 0000000..5078c56 --- /dev/null +++ b/docs/plans/phase-21-plan.md @@ -0,0 +1,75 @@ +# Phase 21 — OCR Reliability + +## What exists + +- [`OcrProcessingService`](../../VigilCareRecordsAPI/BackgroundServices/OcrProcessingService.cs) polls with `Take(5)` and uses `stoppingToken` for queries/`Delay`, but download / OCR / prefill omit CT. +- [`AzureDocumentOcrService`](../../VigilCareRecordsAPI/Services/Ocr/AzureDocumentOcrService.cs) constructs `DocumentIntelligenceClient` per scoped resolve (`Program.cs` `AddScoped`). +- [`TesseractOcrService`](../../VigilCareRecordsAPI/Services/Ocr/TesseractOcrService.cs) builds a new `TesseractEngine` per document; [`ImagePreprocessor`](../../VigilCareRecordsAPI/Services/Ocr/ImagePreprocessor.cs) sync-copies PDF and allocates large BGRA rasters. +- [`OcrResult.RawText`](../../VigilCareRecordsAPI/Domain/Entities/OcrResult.cs) stores unbounded OCR text. + +Requires [Phase 20](./phase-20-plan.md). OCR remains opt-in (`Ocr:Enabled`, default false). Tracker: [performance-hardening-overview.md](./performance-hardening-overview.md). + +## What needs to be built + +Lower LOH/CPU spikes and make shutdown cooperative when OCR is enabled. + +Do not start [Phase 22](./phase-22-plan.md) until success criteria below pass. + +--- + +## Step 1 — CancellationToken through OCR pipeline + +- Extend `IOcrService.ExtractAsync(..., CancellationToken ct = default)`. +- Pass CT into `OcrDraftPreFiller.PreFillAsync` and MinIO download from `OcrProcessingService`. +- Azure analyze must observe CT; Tesseract path checks CT between preprocess and process. + +--- + +## Step 2 — Singleton Azure Document Intelligence client + +- Register `DocumentIntelligenceClient` as singleton in [`Program.cs`](../../VigilCareRecordsAPI/Program.cs) when provider is Azure. +- Inject into scoped `AzureDocumentOcrService` (thin wrapper). + +--- + +## Step 3 — Tesseract / ImagePreprocessor buffer reductions + +- Prefer async `CopyToAsync` for PDF buffering. +- Avoid redundant `ToArray()` where a single buffer suffices. +- Reuse one `TesseractEngine` per scoped service instance (hosted service remains sequential). +- Keep processing sequential (no Parallel fan-out). + +--- + +## Step 4 — Cap RawText persistence + +- Truncate `RawText` (e.g. 64 KB) or store null when only field confidences are needed by draft GET. +- Document the cap in the phase checklist / overview. + +--- + +## Success criteria + +- [x] Phase 13 verification script passes with OCR disabled +- [x] CT is on `IOcrService` / prefill / OCR hosted heavy path +- [x] Azure client is singleton when Azure provider is configured +- [x] Tesseract does not construct a new engine per page when the same scope processes one batch +- [x] Stored `RawText` length is capped (or omitted) +- [x] `dotnet test` passes + +## Out of scope + +- Enabling OCR by default +- Parallel OCR across batches +- Fuzzy / seed / PromoteAsync CT (Phase 22) + +## Verification + +1. `./scripts/run-vigilcare-records-phase-13-verification.sh` +2. `dotnet test VigilCareRecordsAPI.Tests/VigilCareRecordsAPI.Tests.csproj` +3. Optional live OCR (`VIGILCARE_OCR_LIVE=1`) when credentials exist +4. Update overview findings 2, 6, 7 (OCR CT), 16 → Done when this phase merges + +## Gate + +Do not start [Phase 22](./phase-22-plan.md) until success criteria above are met. diff --git a/docs/plans/phase-22-plan.md b/docs/plans/phase-22-plan.md new file mode 100644 index 0000000..5d306a1 --- /dev/null +++ b/docs/plans/phase-22-plan.md @@ -0,0 +1,70 @@ +# Phase 22 — Polish and Ops + +## What exists + +- [`PromotionService`](../../VigilCareRecordsAPI/Services/PromotionService.cs) loads all same-DOB patients for Levenshtein logging before creating a new patient. +- [`SeedDocumentStorage`](../../VigilCareRecordsAPI/Data/Seed/SeedDocumentStorage.cs) StatObject/Put per batch on bootstrap. +- `PromoteAsync` / seed paths used by hosted services omit `CancellationToken`. +- [`docker-compose.prod.yml`](../../docker-compose.prod.yml) sets API `memory: 1G` with no measured guidance comment. +- [`UserDirectoryService.ListByRoleAsync`](../../VigilCareRecordsAPI/Services/UserDirectoryService.cs) is unbounded. + +Requires [Phase 21](./phase-21-plan.md). Tracker: [performance-hardening-overview.md](./performance-hardening-overview.md). + +## What needs to be built + +Long-running / edge-case hardening and ops documentation. Do not raise the container memory limit with invented numbers — document how to measure with `dotnet-counters` and only change the limit if justified by measured peak. + +--- + +## Step 1 — Cap fuzzy same-DOB candidates + +- Before Levenshtein, `.Take(50)` (or equivalent) on same-DOB projection. +- Keep warning logs for near-misses within the capped set. + +--- + +## Step 2 — Seed MinIO loop + CT + +- Honor `CancellationToken` through seed document storage. +- Reduce N+1 pressure: skip exists checks when unnecessary, or batch/limit work; bootstrap must still succeed on empty and re-run environments. + +--- + +## Step 3 — PromoteAsync CancellationToken + +- Add CT to `IPromotionService.PromoteAsync` and pass from [`PromotionRetryService`](../../VigilCareRecordsAPI/BackgroundServices/PromotionRetryService.cs). +- Propagate into EF calls inside promote where practical. + +--- + +## Step 4 — Ops notes + user directory clamp + +- Add a short comment near the 1 G limit in `docker-compose.prod.yml` pointing at counters workflow in the overview (do not invent a new limit). +- Clamp `UserDirectoryService.ListByRoleAsync` with a sane max (e.g. 500) or document intentional unbounded small directories — prefer clamp for safety. + +--- + +## Success criteria + +- [x] Same-DOB fuzzy path never loads more than the configured Take cap +- [x] Seed bootstrap respects CT and does not regress empty-DB seed +- [x] Promotion retry still promotes with CT plumbed +- [x] User directory list is capped +- [x] Overview + this plan checklists updated; gap-analysis matrix rows 26–31 marked Done when Phases 19–22 complete +- [x] `dotnet test` passes + +## Out of scope + +- Premature GC mode changes +- Raising memory limit without measured peak evidence +- Frontend redesign + +## Verification + +1. `dotnet test VigilCareRecordsAPI.Tests/VigilCareRecordsAPI.Tests.csproj` +2. Smoke bootstrap against local compose +3. Mark overview Phase 22 + findings 9, 14, 15 → Done; mark Phases 19–22 complete in PRD / plans README when all merge + +## Gate + +Performance hardening stream complete when this phase and overview checklists are Done. diff --git a/docs/vigilcare-records-gap-analysis.md b/docs/vigilcare-records-gap-analysis.md index 0288251..43d3ae8 100644 --- a/docs/vigilcare-records-gap-analysis.md +++ b/docs/vigilcare-records-gap-analysis.md @@ -820,6 +820,14 @@ A batch stuck in `APPROVED` with exhausted retries is invisible in Prometheus da | 23 | No field-level draft audit | P5 | F | Open | | 24 | Integration test gaps | P5 | F | Done | | 25 | MetricsCollector missing retry gauges | P5 | F | Done | +| 26 | Unclamped pageSize / batch PDF ID lists | P2 | B | Done — Phase 19 | +| 27 | Missing AsNoTracking / GetDocument over-fetch / FHIR Pretty | P2 | B | Done — Phase 19 | +| 28 | MinIO full-buffer download + sync CopyTo | P2 | B | Done — Phase 20 | +| 29 | Unbounded patient history and FHIR `$everything` | P2 | B | Done — Phase 20 | +| 30 | OCR multi-buffer / Azure scoped client / missing CT | P2 | B | Done — Phase 21 | +| 31 | Fuzzy same-DOB load, seed MinIO N+1, PromoteAsync CT | P2 | B | Done — Phase 22 | + +Performance hardening plans: [plans/performance-hardening-overview.md](plans/performance-hardening-overview.md), [plans/phase-19-plan.md](plans/phase-19-plan.md)–[phase-22-plan.md](plans/phase-22-plan.md). --- diff --git a/docs/vigilcare-records-prd.md b/docs/vigilcare-records-prd.md index 385ac0a..df98ab8 100644 --- a/docs/vigilcare-records-prd.md +++ b/docs/vigilcare-records-prd.md @@ -6,6 +6,8 @@ **Phases 14–18 (UI redesign)** are planned: restyle and re-layout `vigilcare-records-web` against [designs/design-doc.md](designs/design-doc.md) without new backend behavior. Implementation guides: [plans/](plans/). +**Phases 19–22 (performance hardening)** address CPU/memory/reliability findings from the API performance audit. Tracker: [plans/performance-hardening-overview.md](plans/performance-hardening-overview.md). + | Phase | Scope | Status | |---|---|---| | 1 | Schema, auth, roles, batch CRUD, MinIO upload, status machine | Done | @@ -26,8 +28,12 @@ | 16 | UI redesign: Entry / Verification / Clinical Approval workstation layouts | Planned | | 17 | UI redesign: Intake, Cover Sheets, Live Capture, History, Dashboard, FHIR Explorer | Planned | | 18 | UI redesign: surface unused APIs (batch events, work queues, Users admin) | Done | +| 19 | Perf: pageSize/PDF clamps, AsNoTracking, slim GetDocument, FHIR serializer | Done | +| 20 | Perf: MinIO async/CT, history + `$everything` paging, overview aggregates | Done | +| 21 | Perf: OCR CT, Azure singleton client, buffer reductions, RawText cap | Done | +| 22 | Perf: fuzzy Take cap, seed N+1/CT, PromoteAsync CT, ops notes | Done | -**Verification scripts:** `./scripts/run-vigilcare-records-verification-p9.sh` (full workflow + metrics), `./scripts/run-vigilcare-records-phase-10-verification.sh`, `./scripts/run-vigilcare-records-phase-11-verification.sh`, `./scripts/run-vigilcare-records-phase-13-verification.sh`. Phases 14–18 verify via Vitest + manual checklists in each plan. +**Verification scripts:** `./scripts/run-vigilcare-records-verification-p9.sh` (full workflow + metrics), `./scripts/run-vigilcare-records-phase-10-verification.sh`, `./scripts/run-vigilcare-records-phase-11-verification.sh`, `./scripts/run-vigilcare-records-phase-13-verification.sh`. Phases 14–18 verify via Vitest + manual checklists in each plan. Phases 19–22 verify via `dotnet test` + checklists in each plan. See [README.md](../README.md) for API reference, quick start, and [digitization-workstation-guide.md](digitization-workstation-guide.md) for operator workflows. @@ -863,6 +869,19 @@ This phase connects Records to Clinical. Run against a VigilCareClinical Phase 2 --- +### Performance hardening roadmap (Phases 19–22) + +Backend remediations for unbounded queries, document buffering, OCR memory, and cancellation. Overview: [plans/performance-hardening-overview.md](plans/performance-hardening-overview.md). + +| Phase | Plan | Focus | +|---|---|---| +| 19 | [plans/phase-19-plan.md](plans/phase-19-plan.md) | Bounds and read-path hygiene | +| 20 | [plans/phase-20-plan.md](plans/phase-20-plan.md) | MinIO + history / FHIR memory safety | +| 21 | [plans/phase-21-plan.md](plans/phase-21-plan.md) | OCR reliability and cancellation | +| 22 | [plans/phase-22-plan.md](plans/phase-22-plan.md) | Polish, seed, promote CT, ops notes | + +--- + ## Deployment Notes (Small Island Context) - **Single-site tenant:** One hospital or health district per deployment. No cross-island federation in v1. @@ -905,7 +924,8 @@ This phase connects Records to Clinical. Run against a VigilCareClinical Phase 2 - [README.md](../README.md) — API reference, quick start, verification scripts, data models - [digitization-workstation-guide.md](digitization-workstation-guide.md) — clinical scenarios (backfill, live capture, corrections) -- [plans/](plans/) — phase implementation guides (Phases 14–18 UI redesign; Phase 1–13 plans not in repo) +- [plans/](plans/) — phase implementation guides (Phases 14–18 UI redesign; Phases 19–22 performance hardening; Phase 1–13 plans not in repo) +- [plans/performance-hardening-overview.md](plans/performance-hardening-overview.md) — audit finding → phase tracker - [designs/design-doc.md](designs/design-doc.md) — UI/UX design specification for the workstation redesign - [vigilcare-records-gap-analysis.md](vigilcare-records-gap-analysis.md) — post-phase hardening tracker and remaining open items - [vigilcare-clinical-api-prd.md](vigilcare-clinical-api-prd.md) — downstream alerting and observation ingest diff --git a/vigilcare-records-web/src/stores/batches.ts b/vigilcare-records-web/src/stores/batches.ts index ccdebbd..932dbb1 100644 --- a/vigilcare-records-web/src/stores/batches.ts +++ b/vigilcare-records-web/src/stores/batches.ts @@ -393,7 +393,7 @@ async function assignBatch(batchId: string, entryClerkUserId: string): Promise( - `patients/${patientId}/digitization-history`, + `patients/${patientId}/digitization-history?page=1&pageSize=50`, ) if (response.success && response.data) { return response.data diff --git a/vigilcare-records-web/src/types/index.ts b/vigilcare-records-web/src/types/index.ts index 737eb7c..0413f73 100644 --- a/vigilcare-records-web/src/types/index.ts +++ b/vigilcare-records-web/src/types/index.ts @@ -317,6 +317,9 @@ export interface PatientDigitizationHistoryResponse { promotedBatches: number supersededBatches: number pendingBatches: number + page: number + pageSize: number + totalPages: number entries: DigitizationHistoryEntry[] }