using NTP.Application.Abstractions;
using NTP.Domain.Grains.Permits;
namespace NTP.Application.Grains.Permits;
/// A permit that jobs/GRAINS_Close_Old_Permits.cfm closes.
public sealed class OldPermitRow
{
public long Id { get; set; }
public string? Status { get; set; }
}
public interface IPermitJobsRepository
{
/// The four groups of jobs/GRAINS_Close_Old_Permits.cfm (see the repository for the rules).
Task> GetOldPermitsToCloseAsync(CancellationToken ct = default);
/// Sets CLOSE only while the permit still has the status it was found with; returns the rows changed.
Task CloseAsync(long permitId, string previousStatus, CancellationToken ct = default);
}
public interface IPermitJobsService
{
/// jobs/GRAINS_Close_Old_Permits.cfm. Returns the number of permits closed.
Task CloseOldPermitsAsync(CancellationToken ct = default);
}
public sealed class PermitJobsService(IPermitJobsRepository repo, IEventLogger events, IUnitOfWork uow) : IPermitJobsService
{
public async Task CloseOldPermitsAsync(CancellationToken ct = default)
{
var rows = await repo.GetOldPermitsToCloseAsync(ct);
var seen = new HashSet();
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;
}
}