Harden API memory and CPU usage across Phases 19–22.
Bound list/PDF payloads, stream MinIO I/O with cancellation, paginate history and FHIR $everything, tighten OCR lifetimes/buffers, and add phase tracking docs.
This commit is contained in:
@@ -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<PatientDigitizationHistoryResponse> GetPatientHistoryAsync(Guid patientId)
|
||||
public async Task<PatientDigitizationHistoryResponse> 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<Guid, Guid>()
|
||||
: 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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user