using Hcs.WebApp.Data.Hcs; using Hcs.WebApp.Services; using Hcs.WebApp.Utils; namespace Hcs.WebApp.BackgroundServices.CampaignManagers { public abstract class ManagerBase( IServiceScopeFactory scopeFactory, OperationExecutionState operationExecutionState, ResultWaitState resultWaitState, Campaign campaign) : IManager { protected readonly IServiceScope scope = scopeFactory.CreateScope(); protected readonly OperationExecutionState operationExecutionState = operationExecutionState; protected readonly ResultWaitState resultWaitState = resultWaitState; protected readonly Campaign campaign = campaign; private HeadquartersService? headquartersService; protected HeadquartersService HeadquartersService => headquartersService ??= scope.ServiceProvider.GetRequiredService(); protected abstract int StepCount { get; } public Campaign Campaign => campaign; public IManager.ManagerState State { get; protected set; } = IManager.ManagerState.Created; public event Action? OnCampaignProgressStep; public abstract Task ProcessAsync(); public async Task EndWithFailAsync(Exception e) { await HeadquartersService.SetCampaignEndedWithFailAsync(campaign.Id, e.CombineMessages()); State = IManager.ManagerState.Ended; } protected async Task ProgressStepAsync(int step) { using var context = HeadquartersService.GetNewContext(); await ProgressStepAsync(context, step); } protected async Task ProgressStepAsync(HcsDbContext context, int step) { campaign.Step = step; campaign.Progress = (step + 1) / StepCount; await HeadquartersService.UpdateCampaignStepAndProgressAsync(context, campaign); OnCampaignProgressStep?.Invoke(campaign); } } }