using System.Linq; using GozareshgirProgramManager.Application._Common.Interfaces; using GozareshgirProgramManager.Application._Common.Models; using GozareshgirProgramManager.Domain.ProjectAgg.Entities; using GozareshgirProgramManager.Domain.ProjectAgg.Enums; using Microsoft.EntityFrameworkCore; namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.AutoUpdateDeployStatus; public record AutoUpdateDeployStatusCommand : IBaseCommand; public class AutoUpdateDeployStatusCommandHandler : IBaseCommandHandler { private readonly IProgramManagerDbContext _dbContext; public AutoUpdateDeployStatusCommandHandler(IProgramManagerDbContext dbContext) { _dbContext = dbContext; } public async Task Handle(AutoUpdateDeployStatusCommand request, CancellationToken cancellationToken) { // Fetch all sections whose phase is still marked as not completed var sections = await _dbContext.TaskSections .Include(ts => ts.Task) .ThenInclude(t => t.Phase) .Where(ts => ts.Task.Phase.DeployStatus == ProjectDeployStatus.NotCompleted) .ToListAsync(cancellationToken); if (sections.Count == 0) return OperationResult.Success(); var phasesToUpdate = sections .GroupBy(ts => ts.Task.PhaseId) .Where(g => g.All(s => s.Status == TaskSectionStatus.Completed)) .Select(g => g.First().Task.Phase) .Distinct() .ToList(); if (phasesToUpdate.Count == 0) return OperationResult.Success(); foreach (var phase in phasesToUpdate) { phase.UpdateDeployStatus(ProjectDeployStatus.PendingDevDeploy); } await _dbContext.SaveChangesAsync(cancellationToken); return OperationResult.Success(); } }