shoc-backend/SeaHaven.DataServices/Implementation/WorkOrderIngestDataService.cs
Alexandre Brandizzi a32471d4c0 Serialize sync cancels and vendor uplift requests on the work order lock
The legacy ingest batch holds the per-work-order lock, taken in id order,
for every work order it may cancel until the batch commits. A vendor
uplift request now runs under the same lock. Uplift creation on both
routes refuses a work order cancelled by either lifecycle or status text,
so a request can neither slip past a cancel nor land after one.
2026-09-25 19:37:08 -03:00

71 lines
2.9 KiB
C#

using Data.SeaHavenIndustries;
using Data.SeaHavenIndustries.Enums;
using Microsoft.EntityFrameworkCore;
using SeaHaven.DataServices.Helpers;
using SeaHaven.DataServices.Interfaces;
namespace SeaHaven.DataServices.Implementation
{
public class WorkOrderIngestDataService : IWorkOrderIngestDataService
{
private readonly ApplicationDbContext _context;
public WorkOrderIngestDataService(ApplicationDbContext context)
{
_context = context;
}
public async Task<int> GetMaxWorkOrderIdAsync(CancellationToken cancellationToken)
=> await _context.workOrders.MaxAsync(w => (int?)w.Id, cancellationToken) ?? 0;
public Task<WorkOrder?> GetTrackedByExternalIdAsync(string externalWorkOrderId, CancellationToken cancellationToken)
=> _context.workOrders.FirstOrDefaultAsync(w => w.ExternalWorkOrderId == externalWorkOrderId, cancellationToken);
public void TrackWorkOrder(WorkOrder workOrder)
=> _context.workOrders.Add(workOrder);
public Task<Locations?> FindLocationAsync(string name, CancellationToken cancellationToken)
=> _context.Locations.FirstOrDefaultAsync(l => l.Name == name || l.Title == name, cancellationToken);
public async Task AddAndSaveLocationAsync(Locations location, CancellationToken cancellationToken)
{
_context.Locations.Add(location);
await _context.SaveChangesAsync(cancellationToken);
}
public Task<int> StageCancelPendingUpliftsAsync(int workOrderId, CancellationToken cancellationToken)
=> PendingUpliftCancellation.StageAsync(
_context,
workOrderId,
actorId: null,
actorType: AuditActorType.Sync.ToString(),
DateTime.UtcNow,
cancellationToken);
public async Task<IReadOnlyList<int>> GetWorkOrderIdsByExternalIdsAsync(
IReadOnlyCollection<string> externalWorkOrderIds,
CancellationToken cancellationToken)
=> await _context.workOrders
.AsNoTracking()
.Where(w => w.ExternalWorkOrderId != null && externalWorkOrderIds.Contains(w.ExternalWorkOrderId))
.Select(w => w.Id)
.ToListAsync(cancellationToken);
public Task ExecuteTransactionalAsync(
IReadOnlyCollection<int> lockedWorkOrderIds,
Func<CancellationToken, Task> work,
CancellationToken cancellationToken)
=> WorkOrderMutationLock.RunManyAsync(
_context,
lockedWorkOrderIds,
async ct =>
{
await work(ct);
return true;
},
cancellationToken);
public Task SaveAsync(CancellationToken cancellationToken)
=> _context.SaveChangesAsync(cancellationToken);
}
}