NTP_V2/src/NTP.Application/Grains/Permits/PermitJobsService.cs

51 lines
2.0 KiB
C#

using NTP.Application.Abstractions;
using NTP.Domain.Grains.Permits;
namespace NTP.Application.Grains.Permits;
/// <summary>A permit that jobs/GRAINS_Close_Old_Permits.cfm closes.</summary>
public sealed class OldPermitRow
{
public long Id { get; set; }
public string? Status { get; set; }
}
public interface IPermitJobsRepository
{
/// <summary>The four groups of jobs/GRAINS_Close_Old_Permits.cfm (see the repository for the rules).</summary>
Task<IReadOnlyList<OldPermitRow>> GetOldPermitsToCloseAsync(CancellationToken ct = default);
/// <summary>Sets CLOSE only while the permit still has the status it was found with; returns the rows changed.</summary>
Task<int> CloseAsync(long permitId, string previousStatus, CancellationToken ct = default);
}
public interface IPermitJobsService
{
/// <summary>jobs/GRAINS_Close_Old_Permits.cfm. Returns the number of permits closed.</summary>
Task<int> CloseOldPermitsAsync(CancellationToken ct = default);
}
public sealed class PermitJobsService(IPermitJobsRepository repo, IEventLogger events, IUnitOfWork uow) : IPermitJobsService
{
public async Task<int> CloseOldPermitsAsync(CancellationToken ct = default)
{
var rows = await repo.GetOldPermitsToCloseAsync(ct);
var seen = new HashSet<long>();
var closed = 0;
foreach (var row in rows)
{
// the legacy query is a UNION ALL: one permit can appear in several groups and was then closed (and logged) several times
if (!seen.Add(row.Id)) continue;
var previous = row.Status ?? string.Empty;
var done = await uow.ExecuteInTransactionAsync(async token =>
{
if (await repo.CloseAsync(row.Id, previous, token) == 0) return false; // its status changed since the query
await events.LogAsAsync("SYSTEM", null, row.Id, previous, PermitStatus.Closed, PermitEventType.Override, "System Close.", ct: token);
return true;
}, ct);
if (done) closed++;
}
return closed;
}
}