using GozareshgirProgramManager.Application.Modules.Projects.DTOs; using GozareshgirProgramManager.Application.Modules.Projects.Extensions; using GozareshgirProgramManager.Domain.ProjectAgg.Entities; using GozareshgirProgramManager.Domain.ProjectAgg.Entities.Task.TaskSection; using GozareshgirProgramManager.Domain.ProjectAgg.Repositories; using GozareshgirProgramManager.Infrastructure.Persistence._Common; using GozareshgirProgramManager.Infrastructure.Persistence.Context; using Microsoft.EntityFrameworkCore; namespace GozareshgirProgramManager.Infrastructure.Persistence.Repositories; public class TaskSectionActivityRepository : RepositoryBase, ITaskSectionActivityRepository { private readonly ProgramManagerDbContext _programManagerDbContext; public TaskSectionActivityRepository(ProgramManagerDbContext programManagerDbContext) : base(programManagerDbContext) { _programManagerDbContext = programManagerDbContext; } public async Task> GetBySectionIdAsync(Guid sectionId) { return await _programManagerDbContext.TaskSectionActivities .Where(a => a.SectionId == sectionId).ToListAsync(); } public async Task> GetByUserIdAsync(long userId) { return await _programManagerDbContext.TaskSectionActivities .Where(x => x.UserId == userId).ToListAsync(); } public async Task> GetActiveByUserAsync(long userId) { return await _programManagerDbContext.TaskSectionActivities .Where(x => x.UserId == userId && x.IsActive) .ToListAsync(); } public async Task> GetByDateRangeAsync(DateTime from, DateTime to) { return await _programManagerDbContext.TaskSectionActivities .Where(x => x.EndDate >= from && x.StartDate <= to).ToListAsync(); } public async Task> GetByDateRangeUserIdAsync(DateTime from, DateTime to, long userId) { return await _programManagerDbContext.TaskSectionActivities .Where(x => x.EndDate >= from && x.StartDate <= to && x.UserId == userId).ToListAsync(); } public async Task GetTotalTimeSpentByUserInRangeAsync(long userId, DateTime from, DateTime to) { var data = await GetByDateRangeUserIdAsync(from, to, userId); return data.Aggregate(TimeSpan.Zero, (total, activity) => { var adjustedStart = activity.StartDate < from ? from : activity.StartDate; var adjustedEnd = activity.EndDate > to ? to : (activity.EndDate ?? to); return total.Add(adjustedEnd - adjustedStart); }); } public async Task> GetTotalTimeSpentPerUserInRangeAsync(DateTime from, DateTime to) { var data = await GetByDateRangeAsync(from, to); var result = data .GroupBy(x => x.UserId) .Select(group => { var totalTime = group.Aggregate(TimeSpan.Zero, (total, activity) => { var adjustedStart = activity.StartDate < from ? from : activity.StartDate; var adjustedEnd = activity.EndDate > to ? to : (activity.EndDate ?? to); return total.Add(adjustedEnd - adjustedStart); }); return (totalTime, group.Key); }) .ToList(); return result; } }