Bound list/PDF payloads, stream MinIO I/O with cancellation, paginate history and FHIR $everything, tighten OCR lifetimes/buffers, and add phase tracking docs.
197 lines
7.7 KiB
C#
197 lines
7.7 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
|
|
public class DigitizationHistoryService : IDigitizationHistoryService
|
|
{
|
|
private const int MaxAuditEventsPerBatch = 50;
|
|
private readonly AppDbContext _db;
|
|
|
|
public DigitizationHistoryService(AppDbContext db)
|
|
{
|
|
_db = db;
|
|
}
|
|
|
|
public async Task<PatientDigitizationHistoryResponse> GetPatientHistoryAsync(
|
|
Guid patientId, int page = 1, int pageSize = 20)
|
|
{
|
|
pageSize = Math.Clamp(pageSize, 1, 50);
|
|
page = Math.Max(1, page);
|
|
|
|
var hasBatches = await _db.DigitizationBatches
|
|
.AsNoTracking()
|
|
.AnyAsync(b => b.PatientId == patientId);
|
|
|
|
if (!hasBatches)
|
|
throw new NotFoundException(
|
|
$"No digitization history found for patient {patientId}.",
|
|
"PATIENT_HISTORY_NOT_FOUND");
|
|
|
|
var statusCounts = await _db.DigitizationBatches
|
|
.AsNoTracking()
|
|
.Where(b => b.PatientId == patientId)
|
|
.GroupBy(b => b.Status)
|
|
.Select(g => new { Status = g.Key, Count = g.Count() })
|
|
.ToListAsync();
|
|
|
|
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 = 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();
|
|
|
|
var obsCountLookup = promotedPageIds.ToDictionary(
|
|
id => id,
|
|
id =>
|
|
{
|
|
var active = liveObservationCounts
|
|
.FirstOrDefault(x => x.SourceBatchId == id && !x.IsSuperseded)?.Count ?? 0;
|
|
var superseded = liveObservationCounts
|
|
.FirstOrDefault(x => x.SourceBatchId == id && x.IsSuperseded)?.Count ?? 0;
|
|
return (Active: active, Superseded: superseded);
|
|
});
|
|
|
|
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);
|
|
|
|
// 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);
|
|
supersededByLookup.TryGetValue(b.Id, out var supersededByBatchId);
|
|
|
|
return new DigitizationHistoryEntry(
|
|
BatchId: b.Id,
|
|
Status: b.Status.ToDbString(),
|
|
BatchType: b.BatchType.ToDbString(),
|
|
Track: b.Track.ToDbString(),
|
|
SupersedesBatchId: b.SupersedesBatchId,
|
|
IsCorrection: b.SupersedesBatchId.HasValue,
|
|
HasBeenSuperseded: hasBeenSuperseded,
|
|
SupersededByBatchId: hasBeenSuperseded ? supersededByBatchId : null,
|
|
DraftObservationCount: b.DraftObservationCount,
|
|
LiveObservationCount: counts.Active,
|
|
SupersededObservationCount: counts.Superseded,
|
|
CreatedAt: b.CreatedAt,
|
|
PromotedAt: b.PromotedAt,
|
|
PromotionEncounterId: b.PromotionEncounterId,
|
|
EnteredByUserId: b.EnteredByUserId,
|
|
EnteredByUserName: b.EnteredByUserName,
|
|
VerifiedByUserId: b.VerifiedByUserId,
|
|
VerifiedByUserName: b.VerifiedByUserName,
|
|
ApprovedByUserId: b.ApprovedByUserId,
|
|
ApprovedByUserName: b.ApprovedByUserName,
|
|
AuditTrail: auditByBatch.GetValueOrDefault(b.Id, [])
|
|
);
|
|
}).ToList();
|
|
|
|
return new PatientDigitizationHistoryResponse(
|
|
PatientId: patientId,
|
|
TotalBatches: totalBatches,
|
|
PromotedBatches: promotedBatches,
|
|
SupersededBatches: supersededBatchCount,
|
|
PendingBatches: pendingBatches,
|
|
Page: page,
|
|
PageSize: pageSize,
|
|
TotalPages: totalPages,
|
|
Entries: entries
|
|
);
|
|
}
|
|
}
|