using Data.SeaHavenIndustries; using Data.SeaHavenIndustries.Enums; using Microsoft.EntityFrameworkCore; using SeaHaven.DataServices.Helpers; using SeaHaven.DataServices.Interfaces; namespace SeaHaven.DataServices.Implementation { public class DashboardDataService : IDashboardDataService { private readonly ApplicationDbContext _context; public DashboardDataService(ApplicationDbContext context) { _context = context; } public async Task GetWorkOrderCountsAsync( int? accountId, CancellationToken cancellationToken) { var query = _context.workOrders.Where(w => w.istemplate != true); if (accountId is int scopedAccountId) { query = query.Where(w => w.AccountId == scopedAccountId); } var total = await query.CountAsync(cancellationToken); var open = await query.CountAsync(w => w.Status == "Open" || w.Status == "In Progress" || w.Status == "On Hold", cancellationToken); var notDispatched = await query.CountAsync(w => (w.Status == "Open") && (w.AssignTo == null || w.AssignTo == ""), cancellationToken); var completed = await query.CountAsync(w => w.Status == "Done", cancellationToken); return new DashboardCounts { Total = total, Open = open, NotDispatched = notDispatched, Completed = completed }; } public async Task> GetDashboardWorkOrdersAsync( int? accountId, string? dispatcherId, DateOnly? dateFrom, DateOnly? dateTo, CancellationToken cancellationToken) { var query = WorkOrderBoardQueryFilters.ApplyBaseScope(_context.workOrders.AsNoTracking()); if (accountId is int scopedAccountId) query = WorkOrderBoardQueryFilters.ApplyAccountScope(query, scopedAccountId); if (dispatcherId != null) query = query.Where(w => w.AssignTo == dispatcherId); if (dateFrom is DateOnly from && dateTo is DateOnly to) { var fromDate = from.ToDateTime(TimeOnly.MinValue); var toDateExclusive = to.AddDays(1).ToDateTime(TimeOnly.MinValue); query = query.Where(w => w.ScheduledDate >= fromDate && w.ScheduledDate < toDateExclusive); } return await query .Select(w => new DashboardWorkOrder( w.Id, w.AssignTo, w.WorkOrderType, w.LifecycleStatus, w.LegacyStatus ?? w.Status, w.ScheduledDate, w.OriginalDate, w.CompletedDate)) .ToListAsync(cancellationToken); } } }