Files
vigilcare-clinical/VigilCareClinicalAPI/BackgroundServices/Reconciliation/PendingOrdersCheck.cs
T
Trent 68a2ab3204
CI / changes (push) Successful in 17s
CI / frontend (push) Skipped
CI / backend (push) Successful in 15m10s
Fix Kafka retry seek, bound buffers, and cut hot-path CPU/memory waste (Phases 41–44).
Stop consumers from committing past failed offsets, harden Rabbit/DataLake/gateway backpressure, dispose JsonDocument/MinIO correctly, and batch expensive DB/HTTP paths. Track progress in docs/performance.
2026-11-30 21:32:43 +08:00

105 lines
3.6 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
public sealed class PendingOrdersCheck
{
public static readonly ReconciliationCheckType CheckType = ReconciliationCheckType.PendingOrderNoResult;
private readonly AppDbContext _db;
private readonly ReconciliationPublisher _publisher;
private readonly ReconciliationJobOptions _opts;
private readonly ILogger<PendingOrdersCheck> _logger;
public PendingOrdersCheck(
AppDbContext db,
ReconciliationPublisher publisher,
IOptions<ReconciliationJobOptions> opts,
ILogger<PendingOrdersCheck> logger)
{
_db = db;
_publisher = publisher;
_opts = opts.Value;
_logger = logger;
}
public async Task<int> RunAsync(CancellationToken ct)
{
var cutoff = DateTimeOffset.UtcNow
.AddHours(-_opts.PendingOrderThresholdHours);
var staleOrders = await _db.Orders
.Where(o => (o.Status == OrderStatus.Pending || o.Status == OrderStatus.InProgress)
&& o.OrderedAt < cutoff
&& o.ResultedAt == null)
.Select(o => new
{
o.Id,
o.EncounterId,
o.OrderType,
o.Description,
o.OrderedAt,
PatientId = o.Encounter!.PatientId,
})
.ToListAsync(ct);
if (!staleOrders.Any())
{
_logger.LogDebug("[RECONCILIATION] Check2 — no stale pending orders");
return 0;
}
var byEncounter = staleOrders
.GroupBy(o => new { o.EncounterId, o.PatientId })
.ToList();
var encounterIds = byEncounter.Select(g => g.Key.EncounterId).ToList();
var alreadyOpen = (await _db.ReconciliationAlerts
.AsNoTracking()
.Where(r => r.CheckType == CheckType
&& r.ResolvedAt == null
&& r.EncounterId != null
&& encounterIds.Contains(r.EncounterId.Value))
.Select(r => r.EncounterId!.Value)
.ToListAsync(ct))
.ToHashSet();
var created = new List<ReconciliationAlert>();
foreach (var group in byEncounter)
{
if (alreadyOpen.Contains(group.Key.EncounterId)) continue;
var lines = group.Select(o =>
$" [{o.OrderType.ToDbString()}] {o.Description} (ordered {o.OrderedAt:u}, "
+ $"pending {(DateTimeOffset.UtcNow - o.OrderedAt).TotalHours:F1}h) ID={o.Id}");
var details = $"{group.Count()} order(s) pending without result for encounter "
+ $"{group.Key.EncounterId}:\n{string.Join("\n", lines)}";
var rec = new ReconciliationAlert
{
Id = Guid.NewGuid(),
CheckType = CheckType,
EncounterId = group.Key.EncounterId,
PatientId = group.Key.PatientId,
Details = details,
CreatedAt = DateTimeOffset.UtcNow,
};
_db.ReconciliationAlerts.Add(rec);
created.Add(rec);
_logger.LogWarning(
"[RECONCILIATION] {CheckType} — encounter {EncounterId}: {Count} stale order(s)",
CheckType, group.Key.EncounterId, group.Count());
}
if (created.Count > 0)
{
await _db.SaveChangesAsync(ct);
foreach (var rec in created)
await _publisher.PublishAsync(rec, ct);
}
return created.Count;
}
}