feat(dashboard): add date filter and stat groups components
- Implemented DashboardDateFilter component for selecting date ranges including custom options. - Created DashboardStatGroups component to display various statistical cards grouped by categories. - Added dashboard-chart-data module to handle chart specifications and data processing for dashboard charts. - Introduced Chart component with tooltip and legend functionalities for better data visualization.
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
namespace ERPCore.Dtos.Dashboard;
|
||||
|
||||
/// <summary>
|
||||
/// Every dataset behind the dashboard graphs, in one computed-on-read object (same idea as
|
||||
/// <see cref="DashboardStatsDto"/>). Time-based sets follow the From-To period the dashboard filter sends;
|
||||
/// "snapshot" sets (ageing, batches expiring, low stock, warranties) describe what is open now.
|
||||
/// Purchases-vs-sales by month and stock value by warehouse are already in <see cref="DashboardStatsDto"/>.
|
||||
/// </summary>
|
||||
public sealed record DashboardChartsDto(
|
||||
// Sales
|
||||
IReadOnlyList<DailySalesPointDto> DailySales,
|
||||
IReadOnlyList<ChartPointDto> PaymentSplit,
|
||||
IReadOnlyList<ChartPointDto> TopItems,
|
||||
IReadOnlyList<ChartPointDto> SalesByCategory,
|
||||
IReadOnlyList<ChartPointDto> SalesByCustomer,
|
||||
IReadOnlyList<DocumentStatusDto> DocumentStatus,
|
||||
// Money
|
||||
IReadOnlyList<ChartPointDto> CashInHandByDay,
|
||||
IReadOnlyList<ChartPointDto> ReceivablesAgeing,
|
||||
IReadOnlyList<ChartPointDto> PayablesAgeing,
|
||||
IReadOnlyList<ChartPointDto> ExpenseBreakdown,
|
||||
// Purchasing
|
||||
IReadOnlyList<ChartPointDto> TopVendors,
|
||||
// Stock
|
||||
IReadOnlyList<ChartPairDto> StockInVsOut,
|
||||
IReadOnlyList<ChartPointDto> BatchesExpiring,
|
||||
// HR
|
||||
IReadOnlyList<ChartPointDto> AttendanceMix,
|
||||
IReadOnlyList<ChartPointDto> PayrollCostByMonth,
|
||||
IReadOnlyList<ChartPointDto> LeaveStatus,
|
||||
// Service and production
|
||||
IReadOnlyList<ChartPairDto> TicketsOverTime,
|
||||
IReadOnlyList<ChartPointDto> ProductionStatus,
|
||||
IReadOnlyList<ChartPointDto> WarrantyExpiryByMonth);
|
||||
|
||||
/// <summary>One labelled value: a bar, a donut slice or a point on a line.</summary>
|
||||
public sealed record ChartPointDto(string Label, decimal Value);
|
||||
|
||||
/// <summary>Two values under one label (stock in/out by warehouse, tickets opened/resolved by day).</summary>
|
||||
public sealed record ChartPairDto(string Label, decimal First, decimal Second);
|
||||
|
||||
/// <summary>One day of the Daily Sales, Gross Profit and Expenses line chart.</summary>
|
||||
public sealed record DailySalesPointDto(string Label, decimal Sales, decimal GrossProfit, decimal Expenses);
|
||||
|
||||
/// <summary>Draft / Posted / Cancelled counts for one kind of document.</summary>
|
||||
public sealed record DocumentStatusDto(string Doc, int Draft, int Posted, int Cancelled);
|
||||
+11502
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,227 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional
|
||||
|
||||
namespace ERPCore.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddDashboardPermissions : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.InsertData(
|
||||
table: "sub_nav_items",
|
||||
columns: new[] { "SubNavItemId", "Code", "Href", "Icon", "Label", "NavItemId", "SortOrder" },
|
||||
values: new object[,]
|
||||
{
|
||||
{ 59, "dashboard.stock", "/dashboard", null, "Stock", 1, 1 },
|
||||
{ 60, "dashboard.procurement", "/dashboard", null, "Procurement", 1, 2 },
|
||||
{ 61, "dashboard.approvals", "/dashboard", null, "Approvals", 1, 3 },
|
||||
{ 62, "dashboard.sales", "/dashboard", null, "Sales", 1, 4 },
|
||||
{ 63, "dashboard.accounts", "/dashboard", null, "Accounts", 1, 5 },
|
||||
{ 64, "dashboard.hrm", "/dashboard", null, "Human Resources", 1, 6 },
|
||||
{ 65, "dashboard.production", "/dashboard", null, "Production", 1, 7 },
|
||||
{ 66, "dashboard.service", "/dashboard", null, "Service & Warranty", 1, 8 }
|
||||
});
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "permissions",
|
||||
columns: new[] { "PermissionId", "Code", "NavItemId", "SubNavItemId" },
|
||||
values: new object[,]
|
||||
{
|
||||
{ 72, "NAV:dashboard.stock", null, 59 },
|
||||
{ 73, "NAV:dashboard.procurement", null, 60 },
|
||||
{ 74, "NAV:dashboard.approvals", null, 61 },
|
||||
{ 75, "NAV:dashboard.sales", null, 62 },
|
||||
{ 76, "NAV:dashboard.accounts", null, 63 },
|
||||
{ 77, "NAV:dashboard.hrm", null, 64 },
|
||||
{ 78, "NAV:dashboard.production", null, 65 },
|
||||
{ 79, "NAV:dashboard.service", null, 66 }
|
||||
});
|
||||
|
||||
// Admin gets every new dashboard area. Any other role keeps what it could already see: it is granted
|
||||
// view on an area when it already holds a matching module permission (idempotent, like AddPoApprovalsNav).
|
||||
migrationBuilder.Sql("""
|
||||
INSERT IGNORE INTO `role_permissions` (`RoleId`, `PermissionId`, `Actions`)
|
||||
SELECT r.`RoleId`, p.`PermissionId`, 31
|
||||
FROM `roles` r
|
||||
JOIN `permissions` p ON p.`PermissionId` BETWEEN 72 AND 79
|
||||
WHERE LOWER(r.`Code`) = 'admin';
|
||||
""");
|
||||
|
||||
// stock: view for any role that could already reach the matching module.
|
||||
migrationBuilder.Sql("""
|
||||
INSERT IGNORE INTO `role_permissions` (`RoleId`, `PermissionId`, `Actions`)
|
||||
SELECT DISTINCT rp.`RoleId`, 72, 1
|
||||
FROM `role_permissions` rp
|
||||
JOIN `permissions` src ON src.`PermissionId` = rp.`PermissionId`
|
||||
WHERE src.`Code` = 'NAV:stock'
|
||||
OR src.`Code` LIKE 'NAV:stock.%';
|
||||
""");
|
||||
|
||||
// procurement: view for any role that could already reach the matching module.
|
||||
migrationBuilder.Sql("""
|
||||
INSERT IGNORE INTO `role_permissions` (`RoleId`, `PermissionId`, `Actions`)
|
||||
SELECT DISTINCT rp.`RoleId`, 73, 1
|
||||
FROM `role_permissions` rp
|
||||
JOIN `permissions` src ON src.`PermissionId` = rp.`PermissionId`
|
||||
WHERE src.`Code` = 'NAV:procurement'
|
||||
OR src.`Code` LIKE 'NAV:procurement.%'
|
||||
OR src.`Code` = 'NAV:receiving';
|
||||
""");
|
||||
|
||||
// approvals: view for any role that could already reach the matching module.
|
||||
migrationBuilder.Sql("""
|
||||
INSERT IGNORE INTO `role_permissions` (`RoleId`, `PermissionId`, `Actions`)
|
||||
SELECT DISTINCT rp.`RoleId`, 74, 1
|
||||
FROM `role_permissions` rp
|
||||
JOIN `permissions` src ON src.`PermissionId` = rp.`PermissionId`
|
||||
WHERE src.`Code` = 'NAV:settings.approvals'
|
||||
OR src.`Code` = 'NAV:procurement.po-approvals'
|
||||
OR src.`Code` = 'NAV:products.price-adjustments'
|
||||
OR src.`Code` = 'NAV:stock.wastage';
|
||||
""");
|
||||
|
||||
// sales: view for any role that could already reach the matching module.
|
||||
migrationBuilder.Sql("""
|
||||
INSERT IGNORE INTO `role_permissions` (`RoleId`, `PermissionId`, `Actions`)
|
||||
SELECT DISTINCT rp.`RoleId`, 75, 1
|
||||
FROM `role_permissions` rp
|
||||
JOIN `permissions` src ON src.`PermissionId` = rp.`PermissionId`
|
||||
WHERE src.`Code` = 'NAV:sales'
|
||||
OR src.`Code` LIKE 'NAV:sales.%'
|
||||
OR src.`Code` = 'NAV:sales-returns';
|
||||
""");
|
||||
|
||||
// accounts: view for any role that could already reach the matching module.
|
||||
migrationBuilder.Sql("""
|
||||
INSERT IGNORE INTO `role_permissions` (`RoleId`, `PermissionId`, `Actions`)
|
||||
SELECT DISTINCT rp.`RoleId`, 76, 1
|
||||
FROM `role_permissions` rp
|
||||
JOIN `permissions` src ON src.`PermissionId` = rp.`PermissionId`
|
||||
WHERE src.`Code` = 'NAV:accounts.bank-deposits'
|
||||
OR src.`Code` = 'NAV:accounts.expenses';
|
||||
""");
|
||||
|
||||
// hrm: view for any role that could already reach the matching module.
|
||||
migrationBuilder.Sql("""
|
||||
INSERT IGNORE INTO `role_permissions` (`RoleId`, `PermissionId`, `Actions`)
|
||||
SELECT DISTINCT rp.`RoleId`, 77, 1
|
||||
FROM `role_permissions` rp
|
||||
JOIN `permissions` src ON src.`PermissionId` = rp.`PermissionId`
|
||||
WHERE src.`Code` = 'NAV:hrm'
|
||||
OR src.`Code` LIKE 'NAV:hrm.%';
|
||||
""");
|
||||
|
||||
// production: view for any role that could already reach the matching module.
|
||||
migrationBuilder.Sql("""
|
||||
INSERT IGNORE INTO `role_permissions` (`RoleId`, `PermissionId`, `Actions`)
|
||||
SELECT DISTINCT rp.`RoleId`, 78, 1
|
||||
FROM `role_permissions` rp
|
||||
JOIN `permissions` src ON src.`PermissionId` = rp.`PermissionId`
|
||||
WHERE src.`Code` = 'NAV:production'
|
||||
OR src.`Code` LIKE 'NAV:production.%';
|
||||
""");
|
||||
|
||||
// service: view for any role that could already reach the matching module.
|
||||
migrationBuilder.Sql("""
|
||||
INSERT IGNORE INTO `role_permissions` (`RoleId`, `PermissionId`, `Actions`)
|
||||
SELECT DISTINCT rp.`RoleId`, 79, 1
|
||||
FROM `role_permissions` rp
|
||||
JOIN `permissions` src ON src.`PermissionId` = rp.`PermissionId`
|
||||
WHERE src.`Code` = 'NAV:help'
|
||||
OR src.`Code` = 'NAV:sales'
|
||||
OR src.`Code` LIKE 'NAV:sales.%';
|
||||
""");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.Sql("DELETE FROM `role_permissions` WHERE `PermissionId` BETWEEN 72 AND 79;");
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "permissions",
|
||||
keyColumn: "PermissionId",
|
||||
keyValue: 72);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "permissions",
|
||||
keyColumn: "PermissionId",
|
||||
keyValue: 73);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "permissions",
|
||||
keyColumn: "PermissionId",
|
||||
keyValue: 74);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "permissions",
|
||||
keyColumn: "PermissionId",
|
||||
keyValue: 75);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "permissions",
|
||||
keyColumn: "PermissionId",
|
||||
keyValue: 76);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "permissions",
|
||||
keyColumn: "PermissionId",
|
||||
keyValue: 77);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "permissions",
|
||||
keyColumn: "PermissionId",
|
||||
keyValue: 78);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "permissions",
|
||||
keyColumn: "PermissionId",
|
||||
keyValue: 79);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "sub_nav_items",
|
||||
keyColumn: "SubNavItemId",
|
||||
keyValue: 59);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "sub_nav_items",
|
||||
keyColumn: "SubNavItemId",
|
||||
keyValue: 60);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "sub_nav_items",
|
||||
keyColumn: "SubNavItemId",
|
||||
keyValue: 61);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "sub_nav_items",
|
||||
keyColumn: "SubNavItemId",
|
||||
keyValue: 62);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "sub_nav_items",
|
||||
keyColumn: "SubNavItemId",
|
||||
keyValue: 63);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "sub_nav_items",
|
||||
keyColumn: "SubNavItemId",
|
||||
keyValue: 64);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "sub_nav_items",
|
||||
keyColumn: "SubNavItemId",
|
||||
keyValue: 65);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "sub_nav_items",
|
||||
keyColumn: "SubNavItemId",
|
||||
keyValue: 66);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using ERPCore.Infra.Auth;
|
||||
using ERPCore.Services.Interfaces;
|
||||
|
||||
namespace ERPCore.Services;
|
||||
|
||||
/// <summary>
|
||||
/// The dashboard shows figures from many modules, but a role only holds some of them. Settings -> Roles has a
|
||||
/// "Dashboard" row with one switch per area (<c>dashboard.stock</c>, <c>dashboard.sales</c>, ...), seeded like every
|
||||
/// other nav permission. Each stat card and graph belongs to one area, and its figure is only computed when the
|
||||
/// caller's role holds that area - so a role never receives a number it was not given, and the queries for it are
|
||||
/// never run. Same rule as <see cref="NavAuthorizationHandler"/>: administrators pass everything, everyone else
|
||||
/// needs the role's permission.
|
||||
/// </summary>
|
||||
internal static class DashboardAccess
|
||||
{
|
||||
public static async Task<bool> CanAsync(this INavPermissionService nav, ICurrentUser user, string navCode, CancellationToken ct = default)
|
||||
=> user.IsAdmin || await nav.HasAccessAsync(user.RoleId, navCode, ct);
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
using System.Globalization;
|
||||
using ERPCore.Domain.Entities;
|
||||
using ERPCore.Domain.Enums;
|
||||
using ERPCore.Dtos.Common;
|
||||
using ERPCore.Dtos.Dashboard;
|
||||
using ERPCore.Infra.Auth;
|
||||
using ERPCore.Repositories.Interfaces;
|
||||
using ERPCore.Services.Interfaces;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
|
||||
namespace ERPCore.Services;
|
||||
|
||||
/// <summary>
|
||||
/// The datasets behind the dashboard graphs, pulled straight from each domain's repository like
|
||||
/// <see cref="DashboardService"/> - grouped and summed in SQL, only the small result comes back. Daily sales and
|
||||
/// cash reuse the day-end report and cash-in-hand services so the graphs agree with those screens.
|
||||
/// </summary>
|
||||
public sealed class DashboardChartsService : IDashboardChartsService
|
||||
{
|
||||
private readonly IRepository<SalesInvoice> _salesInvoices;
|
||||
private readonly IRepository<SalesInvoiceLine> _salesLines;
|
||||
private readonly IRepository<SalesSlip> _salesSlips;
|
||||
private readonly IRepository<PurchaseInvoice> _purchaseInvoices;
|
||||
private readonly IRepository<Expense> _expenses;
|
||||
private readonly IRepository<StockLedger> _ledger;
|
||||
private readonly IRepository<Warehouse> _warehouses;
|
||||
private readonly IRepository<Item> _items;
|
||||
private readonly IRepository<Batch> _batches;
|
||||
private readonly IRepository<AttendanceRecord> _attendance;
|
||||
private readonly IRepository<PayrollLine> _payrollLines;
|
||||
private readonly IRepository<LeaveRequest> _leaveRequests;
|
||||
private readonly IRepository<SupportTicket> _tickets;
|
||||
private readonly IRepository<ProductionRun> _productionRuns;
|
||||
private readonly IRepository<WarrantyRegistration> _warranties;
|
||||
private readonly IDayEndReportService _dayEnd;
|
||||
private readonly ICashInHandService _cash;
|
||||
private readonly BusinessDayClock _clock;
|
||||
private readonly IMemoryCache _cache;
|
||||
private readonly ICurrentUser _user;
|
||||
private readonly INavPermissionService _nav;
|
||||
|
||||
// Bars / slices shown before the rest are folded into "Other".
|
||||
private const int TopN = 5;
|
||||
private const int TopItemsN = 10;
|
||||
private const int PayrollMonths = 12;
|
||||
// The day-end and cash services cap a range at 92 days; daily graphs never need fewer than a week to read.
|
||||
private const int MaxDailyDays = 92;
|
||||
private const int MinDailyDays = 7;
|
||||
private static readonly TimeSpan CacheTtl = TimeSpan.FromSeconds(30);
|
||||
|
||||
public DashboardChartsService(
|
||||
IRepository<SalesInvoice> salesInvoices, IRepository<SalesInvoiceLine> salesLines, IRepository<SalesSlip> salesSlips,
|
||||
IRepository<PurchaseInvoice> purchaseInvoices, IRepository<Expense> expenses, IRepository<StockLedger> ledger,
|
||||
IRepository<Warehouse> warehouses, IRepository<Item> items, IRepository<Batch> batches,
|
||||
IRepository<AttendanceRecord> attendance, IRepository<PayrollLine> payrollLines, IRepository<LeaveRequest> leaveRequests,
|
||||
IRepository<SupportTicket> tickets, IRepository<ProductionRun> productionRuns, IRepository<WarrantyRegistration> warranties,
|
||||
IDayEndReportService dayEnd, ICashInHandService cash, BusinessDayClock clock, IMemoryCache cache, ICurrentUser user, INavPermissionService nav)
|
||||
{
|
||||
_salesInvoices = salesInvoices;
|
||||
_salesLines = salesLines;
|
||||
_salesSlips = salesSlips;
|
||||
_purchaseInvoices = purchaseInvoices;
|
||||
_expenses = expenses;
|
||||
_ledger = ledger;
|
||||
_warehouses = warehouses;
|
||||
_items = items;
|
||||
_batches = batches;
|
||||
_attendance = attendance;
|
||||
_payrollLines = payrollLines;
|
||||
_leaveRequests = leaveRequests;
|
||||
_tickets = tickets;
|
||||
_productionRuns = productionRuns;
|
||||
_warranties = warranties;
|
||||
_dayEnd = dayEnd;
|
||||
_cash = cash;
|
||||
_clock = clock;
|
||||
_cache = cache;
|
||||
_user = user;
|
||||
_nav = nav;
|
||||
}
|
||||
|
||||
public async Task<DashboardChartsDto> GetChartsAsync(int? branchId, DateOnly? from = null, DateOnly? to = null, CancellationToken ct = default)
|
||||
{
|
||||
// Same short per-user cache as the stat cards (see DashboardService): repeat loads and filter flips are instant.
|
||||
var key = $"dashboard-charts:{_user.UserId}:{branchId}:{from}:{to}";
|
||||
if (_cache.TryGetValue(key, out DashboardChartsDto? cached) && cached is not null) return cached;
|
||||
|
||||
var charts = await ComputeAsync(branchId, from, to, ct);
|
||||
_cache.Set(key, charts, CacheTtl);
|
||||
return charts;
|
||||
}
|
||||
|
||||
/// <summary>Whether the caller's role may reach the screen a graph belongs to; see <see cref="DashboardAccess"/>.</summary>
|
||||
private Task<bool> CanAsync(string navCode, CancellationToken ct) => _nav.CanAsync(_user, navCode, ct);
|
||||
|
||||
private async Task<DashboardChartsDto> ComputeAsync(int? branchId, DateOnly? from, DateOnly? to, CancellationToken ct)
|
||||
{
|
||||
// Each graph belongs to a dashboard area (Settings -> Roles -> Dashboard: stock, procurement, sales, accounts, hrm,
|
||||
// production, service). A role without the area's permission gets an empty set and the queries are not run
|
||||
// (administrators pass every check) - see DashboardAccess.
|
||||
var canDayEnd = await CanAsync("dashboard.sales", ct);
|
||||
var canSalesInvoices = await CanAsync("dashboard.sales", ct);
|
||||
var canService = await CanAsync("dashboard.service", ct);
|
||||
var canBankDeposits = await CanAsync("dashboard.accounts", ct);
|
||||
var canExpenses = await CanAsync("dashboard.accounts", ct);
|
||||
var canProcurement = await CanAsync("dashboard.procurement", ct);
|
||||
var canLedger = await CanAsync("dashboard.stock", ct);
|
||||
var canStock = await CanAsync("dashboard.stock", ct);
|
||||
var canAttendance = await CanAsync("dashboard.hrm", ct);
|
||||
var canPayroll = await CanAsync("dashboard.hrm", ct);
|
||||
var canLeave = await CanAsync("dashboard.hrm", ct);
|
||||
var canProduction = await CanAsync("dashboard.production", ct);
|
||||
|
||||
// Sequential awaits: these repositories share one scoped DbContext, which cannot run concurrent operations.
|
||||
// "Today" and day boundaries follow the business time zone, like the day-end report and cash in hand.
|
||||
var today = _clock.Today;
|
||||
var periodFrom = from ?? to ?? today;
|
||||
var periodTo = to ?? periodFrom;
|
||||
if (periodTo < periodFrom) (periodFrom, periodTo) = (periodTo, periodFrom);
|
||||
// Timestamps are compared against the business day's UTC bounds; plain document / attendance dates against
|
||||
// midnight-to-midnight.
|
||||
var fromAt = _clock.ToUtc(periodFrom);
|
||||
var toBefore = _clock.ToUtc(periodTo.AddDays(1));
|
||||
var fromDay = periodFrom.ToDateTime(TimeOnly.MinValue);
|
||||
var toDayEnd = periodTo.AddDays(1).ToDateTime(TimeOnly.MinValue);
|
||||
|
||||
// Day-by-day graphs: the period itself, widened to a readable week and capped at what the services allow.
|
||||
var dailyTo = periodTo;
|
||||
var dailyFrom = periodFrom;
|
||||
if (dailyTo.DayNumber - dailyFrom.DayNumber + 1 < MinDailyDays) dailyFrom = dailyTo.AddDays(-(MinDailyDays - 1));
|
||||
if (dailyTo.DayNumber - dailyFrom.DayNumber + 1 > MaxDailyDays) dailyFrom = dailyTo.AddDays(-(MaxDailyDays - 1));
|
||||
|
||||
// ---- Sales: daily figures and payment split come from the day-end report.
|
||||
var dailySales = new List<DailySalesPointDto>();
|
||||
var paymentSplit = new List<ChartPointDto>();
|
||||
if (canDayEnd)
|
||||
{
|
||||
var daily = await _dayEnd.GetDailyAsync(dailyFrom, dailyTo, branchId, ct);
|
||||
dailySales = daily.Days
|
||||
.Select(d => new DailySalesPointDto(DayLabel(d.Date), d.TotalSales, d.GrossProfit, d.ExpenseTotal))
|
||||
.ToList();
|
||||
paymentSplit = new List<ChartPointDto>
|
||||
{
|
||||
new("Cash", daily.Totals.PaidByCash),
|
||||
new("Card", daily.Totals.PaidByCard),
|
||||
new("Bank / cheque", daily.Totals.PaidByOther),
|
||||
};
|
||||
}
|
||||
|
||||
var topItems = new List<ChartPointDto>();
|
||||
IReadOnlyList<ChartPointDto> salesByCategory = new List<ChartPointDto>();
|
||||
var salesByCustomer = new List<ChartPointDto>();
|
||||
if (canSalesInvoices)
|
||||
{
|
||||
var invoices = _salesInvoices.Query().AsNoTracking()
|
||||
.Where(i => i.Status == SalesInvoiceStatus.Posted && i.InvoiceDate >= fromAt && i.InvoiceDate < toBefore);
|
||||
if (branchId is not null) invoices = invoices.Where(i => i.BranchId == branchId);
|
||||
|
||||
var lines = _salesLines.Query().AsNoTracking()
|
||||
.Where(l => l.SalesInvoice!.Status == SalesInvoiceStatus.Posted
|
||||
&& l.SalesInvoice.InvoiceDate >= fromAt && l.SalesInvoice.InvoiceDate < toBefore);
|
||||
if (branchId is not null) lines = lines.Where(l => l.SalesInvoice!.BranchId == branchId);
|
||||
|
||||
var topItemRows = await lines
|
||||
.GroupBy(l => l.ItemId)
|
||||
.Select(g => new { ItemId = g.Key, Total = g.Sum(x => x.LineTotal) })
|
||||
.OrderByDescending(x => x.Total)
|
||||
.Take(TopItemsN)
|
||||
.ToListAsync(ct);
|
||||
var itemIds = topItemRows.Select(r => r.ItemId).ToList();
|
||||
var itemNames = await _items.Query().AsNoTracking()
|
||||
.Where(i => itemIds.Contains(i.ItemId))
|
||||
.ToDictionaryAsync(i => i.ItemId, i => i.Name, ct);
|
||||
topItems = topItemRows.Select(r => new ChartPointDto(itemNames.GetValueOrDefault(r.ItemId, $"#{r.ItemId}"), r.Total)).ToList();
|
||||
|
||||
var categoryRows = await lines
|
||||
.GroupBy(l => l.Item!.Category!.Name)
|
||||
.Select(g => new { Name = g.Key, Total = g.Sum(x => x.LineTotal) })
|
||||
.OrderByDescending(x => x.Total)
|
||||
.ToListAsync(ct);
|
||||
salesByCategory = TopWithOther(categoryRows.Select(r => new ChartPointDto(r.Name, r.Total)), TopN);
|
||||
|
||||
var customerRows = await invoices
|
||||
.GroupBy(i => i.CustomerSnapshotName)
|
||||
.Select(g => new { Name = g.Key, Total = g.Sum(x => x.GrandTotal) })
|
||||
.OrderByDescending(x => x.Total)
|
||||
.Take(TopN)
|
||||
.ToListAsync(ct);
|
||||
salesByCustomer = customerRows.Select(r => new ChartPointDto(r.Name, r.Total)).ToList();
|
||||
}
|
||||
|
||||
var documentStatus = await GetDocumentStatusAsync(branchId, fromAt, toBefore, fromDay, toDayEnd, periodFrom, periodTo, ct);
|
||||
|
||||
// ---- Money
|
||||
var cashInHandByDay = canBankDeposits
|
||||
? (await _cash.GetRangeAsync(dailyFrom, dailyTo, branchId, ct)).Select(c => new ChartPointDto(DayLabel(c.Date), c.Closing)).ToList()
|
||||
: new List<ChartPointDto>();
|
||||
var receivablesAgeing = canSalesInvoices ? await GetReceivablesAgeingAsync(branchId, ct) : new List<ChartPointDto>();
|
||||
var payablesAgeing = canProcurement ? await GetPayablesAgeingAsync(branchId, ct) : new List<ChartPointDto>();
|
||||
|
||||
IReadOnlyList<ChartPointDto> expenseBreakdown = new List<ChartPointDto>();
|
||||
if (canExpenses)
|
||||
{
|
||||
var expenses = _expenses.Query().AsNoTracking()
|
||||
.Where(e => e.Status == ExpenseStatus.Posted && e.ExpenseDate >= periodFrom && e.ExpenseDate <= periodTo);
|
||||
if (branchId is not null) expenses = expenses.Where(e => e.BranchId == branchId);
|
||||
var expenseRows = await expenses
|
||||
.GroupBy(e => e.Category!.Name)
|
||||
.Select(g => new { Name = g.Key, Total = g.Sum(x => x.Amount) })
|
||||
.OrderByDescending(x => x.Total)
|
||||
.ToListAsync(ct);
|
||||
expenseBreakdown = TopWithOther(expenseRows.Select(r => new ChartPointDto(r.Name, r.Total)), TopN);
|
||||
}
|
||||
|
||||
// ---- Purchasing
|
||||
var topVendors = new List<ChartPointDto>();
|
||||
if (canProcurement)
|
||||
{
|
||||
var purchases = _purchaseInvoices.Query().AsNoTracking()
|
||||
.Where(i => i.Status == PurchaseInvoiceStatus.Posted && i.VendorInvoiceDate >= fromDay && i.VendorInvoiceDate < toDayEnd);
|
||||
if (branchId is not null) purchases = purchases.Where(i => i.BranchId == branchId);
|
||||
var vendorRows = await purchases
|
||||
.GroupBy(i => i.VendorSnapshotName)
|
||||
.Select(g => new { Name = g.Key, Total = g.Sum(x => x.GrandTotal) })
|
||||
.OrderByDescending(x => x.Total)
|
||||
.Take(TopN)
|
||||
.ToListAsync(ct);
|
||||
topVendors = vendorRows.Select(r => new ChartPointDto(r.Name, r.Total)).ToList();
|
||||
}
|
||||
|
||||
// ---- Stock
|
||||
var stockInVsOut = canLedger ? await GetStockInVsOutAsync(branchId, fromAt, toBefore, ct) : new List<ChartPairDto>();
|
||||
var batchesExpiring = canStock ? await GetBatchesExpiringAsync(today, ct) : new List<ChartPointDto>();
|
||||
|
||||
// ---- HR
|
||||
var attendanceMix = new List<ChartPointDto>();
|
||||
if (canAttendance)
|
||||
{
|
||||
var attendance = _attendance.Query().AsNoTracking()
|
||||
.Where(a => a.AttendanceDate >= fromDay && a.AttendanceDate < toDayEnd);
|
||||
if (branchId is not null) attendance = attendance.Where(a => a.Employee!.BranchId == branchId);
|
||||
var attendanceRows = await attendance
|
||||
.GroupBy(a => a.AttendanceStatus)
|
||||
.Select(g => new { Status = g.Key, Count = g.Count() })
|
||||
.ToListAsync(ct);
|
||||
attendanceMix = attendanceRows.Select(r => new ChartPointDto(Spaced(r.Status.ToString()), r.Count)).ToList();
|
||||
}
|
||||
|
||||
var payrollCostByMonth = canPayroll ? await GetPayrollCostAsync(branchId, today, ct) : new List<ChartPointDto>();
|
||||
|
||||
var leaveStatus = new List<ChartPointDto>();
|
||||
if (canLeave)
|
||||
{
|
||||
var leaves = _leaveRequests.Query().AsNoTracking().Where(l => l.CreatedAt >= fromAt && l.CreatedAt < toBefore);
|
||||
var leaveRows = await leaves.GroupBy(l => l.Status).Select(g => new { Status = g.Key, Count = g.Count() }).ToListAsync(ct);
|
||||
leaveStatus = leaveRows.Select(r => new ChartPointDto(Spaced(r.Status.ToString()), r.Count)).ToList();
|
||||
}
|
||||
|
||||
// ---- Service and production
|
||||
var ticketsOverTime = canService ? await GetTicketsOverTimeAsync(dailyFrom, dailyTo, ct) : new List<ChartPairDto>();
|
||||
|
||||
var productionStatus = new List<ChartPointDto>();
|
||||
if (canProduction)
|
||||
{
|
||||
var runs = _productionRuns.Query().AsNoTracking().Where(r => r.CreatedAt >= fromAt && r.CreatedAt < toBefore);
|
||||
if (branchId is not null) runs = runs.Where(r => r.Warehouse!.BranchId == branchId);
|
||||
var runRows = await runs.GroupBy(r => r.Status).Select(g => new { Status = g.Key, Count = g.Count() }).ToListAsync(ct);
|
||||
productionStatus = runRows.Select(r => new ChartPointDto(Spaced(r.Status.ToString()), r.Count)).ToList();
|
||||
}
|
||||
|
||||
var warrantyExpiryByMonth = canService ? await GetWarrantyExpiryAsync(today, ct) : new List<ChartPointDto>();
|
||||
|
||||
return new DashboardChartsDto(
|
||||
dailySales, paymentSplit, topItems, salesByCategory, salesByCustomer, documentStatus,
|
||||
cashInHandByDay, receivablesAgeing, payablesAgeing, expenseBreakdown,
|
||||
topVendors,
|
||||
stockInVsOut, batchesExpiring,
|
||||
attendanceMix, payrollCostByMonth, leaveStatus,
|
||||
ticketsOverTime, productionStatus, warrantyExpiryByMonth);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ helpers
|
||||
|
||||
private static string DayLabel(DateOnly? d) => d is null ? "" : d.Value.ToString("d MMM", CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>"InProgress" -> "In progress", "HalfDay" -> "Half day".</summary>
|
||||
private static string Spaced(string name)
|
||||
{
|
||||
var chars = new List<char>();
|
||||
for (var i = 0; i < name.Length; i++)
|
||||
{
|
||||
if (i > 0 && char.IsUpper(name[i])) chars.Add(' ');
|
||||
chars.Add(i > 0 && char.IsUpper(name[i]) ? char.ToLowerInvariant(name[i]) : name[i]);
|
||||
}
|
||||
return new string(chars.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>The biggest <paramref name="n"/> rows as they are, everything smaller folded into one "Other" slice.</summary>
|
||||
private static IReadOnlyList<ChartPointDto> TopWithOther(IEnumerable<ChartPointDto> sortedDescending, int n)
|
||||
{
|
||||
var all = sortedDescending.ToList();
|
||||
if (all.Count <= n) return all;
|
||||
var top = all.Take(n).ToList();
|
||||
top.Add(new ChartPointDto("Other", all.Skip(n).Sum(p => p.Value)));
|
||||
return top;
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<DocumentStatusDto>> GetDocumentStatusAsync(
|
||||
int? branchId, DateTime fromAt, DateTime toBefore, DateTime fromDay, DateTime toDayEnd, DateOnly periodFrom, DateOnly periodTo,
|
||||
CancellationToken ct)
|
||||
{
|
||||
// One row per kind of document, and only for the modules the caller may reach.
|
||||
var canSalesInvoices = await CanAsync("dashboard.sales", ct);
|
||||
var canProcurement = await CanAsync("dashboard.procurement", ct);
|
||||
var canExpenses = await CanAsync("dashboard.accounts", ct);
|
||||
|
||||
// Sales invoices and slips number their statuses from 1 (Draft=1, Posted=2, Cancelled=3); purchase invoices
|
||||
// and expenses from 0. Each is mapped through its own enum, never by position.
|
||||
int Count<T>(IEnumerable<(int Status, int N)> rows, T status) where T : struct, Enum
|
||||
=> rows.Where(r => r.Status == Convert.ToInt32(status)).Sum(r => r.N);
|
||||
|
||||
var result = new List<DocumentStatusDto>();
|
||||
|
||||
if (canSalesInvoices)
|
||||
{
|
||||
var invoices = _salesInvoices.Query().AsNoTracking().Where(i => i.InvoiceDate >= fromAt && i.InvoiceDate < toBefore);
|
||||
if (branchId is not null) invoices = invoices.Where(i => i.BranchId == branchId);
|
||||
var inv = (await invoices.GroupBy(i => i.Status).Select(g => new { Status = (int)g.Key, N = g.Count() }).ToListAsync(ct))
|
||||
.Select(r => (r.Status, r.N)).ToList();
|
||||
|
||||
var slips = _salesSlips.Query().AsNoTracking().Where(s => s.SlipDate >= fromAt && s.SlipDate < toBefore);
|
||||
if (branchId is not null) slips = slips.Where(s => s.Warehouse!.BranchId == branchId);
|
||||
var slp = (await slips.GroupBy(s => s.Status).Select(g => new { Status = (int)g.Key, N = g.Count() }).ToListAsync(ct))
|
||||
.Select(r => (r.Status, r.N)).ToList();
|
||||
|
||||
result.Add(new("Sales invoices", Count(inv, SalesInvoiceStatus.Draft), Count(inv, SalesInvoiceStatus.Posted), Count(inv, SalesInvoiceStatus.Cancelled)));
|
||||
result.Add(new("Sales slips", Count(slp, SalesSlipStatus.Draft), Count(slp, SalesSlipStatus.Posted), Count(slp, SalesSlipStatus.Cancelled)));
|
||||
}
|
||||
|
||||
if (canProcurement)
|
||||
{
|
||||
var purchases = _purchaseInvoices.Query().AsNoTracking().Where(i => i.VendorInvoiceDate >= fromDay && i.VendorInvoiceDate < toDayEnd);
|
||||
if (branchId is not null) purchases = purchases.Where(i => i.BranchId == branchId);
|
||||
var pur = (await purchases.GroupBy(i => i.Status).Select(g => new { Status = (int)g.Key, N = g.Count() }).ToListAsync(ct))
|
||||
.Select(r => (r.Status, r.N)).ToList();
|
||||
|
||||
result.Add(new("Purchase invoices", Count(pur, PurchaseInvoiceStatus.Draft), Count(pur, PurchaseInvoiceStatus.Posted), Count(pur, PurchaseInvoiceStatus.Cancelled)));
|
||||
}
|
||||
|
||||
if (canExpenses)
|
||||
{
|
||||
var expenses = _expenses.Query().AsNoTracking().Where(e => e.ExpenseDate >= periodFrom && e.ExpenseDate <= periodTo);
|
||||
if (branchId is not null) expenses = expenses.Where(e => e.BranchId == branchId);
|
||||
var exp = (await expenses.GroupBy(e => e.Status).Select(g => new { Status = (int)g.Key, N = g.Count() }).ToListAsync(ct))
|
||||
.Select(r => (r.Status, r.N)).ToList();
|
||||
|
||||
result.Add(new("Expenses", Count(exp, ExpenseStatus.Draft), Count(exp, ExpenseStatus.Posted), Count(exp, ExpenseStatus.Cancelled)));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Unpaid Posted invoices bucketed by how old the invoice is. Neither invoice type carries a due date,
|
||||
/// so age runs from the invoice date (the same approach DashboardService uses for "overdue").</summary>
|
||||
private async Task<IReadOnlyList<ChartPointDto>> GetReceivablesAgeingAsync(int? branchId, CancellationToken ct)
|
||||
{
|
||||
var open = _salesInvoices.Query().AsNoTracking().Where(i => i.Status == SalesInvoiceStatus.Posted && i.BalanceAmount > 0);
|
||||
if (branchId is not null) open = open.Where(i => i.BranchId == branchId);
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
var d30 = now.AddDays(-30);
|
||||
var d60 = now.AddDays(-60);
|
||||
var d90 = now.AddDays(-90);
|
||||
return new List<ChartPointDto>
|
||||
{
|
||||
new("0-30 days", await open.Where(i => i.InvoiceDate >= d30).SumAsync(i => (decimal?)i.BalanceAmount, ct) ?? 0m),
|
||||
new("31-60 days", await open.Where(i => i.InvoiceDate < d30 && i.InvoiceDate >= d60).SumAsync(i => (decimal?)i.BalanceAmount, ct) ?? 0m),
|
||||
new("61-90 days", await open.Where(i => i.InvoiceDate < d60 && i.InvoiceDate >= d90).SumAsync(i => (decimal?)i.BalanceAmount, ct) ?? 0m),
|
||||
new("90+ days", await open.Where(i => i.InvoiceDate < d90).SumAsync(i => (decimal?)i.BalanceAmount, ct) ?? 0m),
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<ChartPointDto>> GetPayablesAgeingAsync(int? branchId, CancellationToken ct)
|
||||
{
|
||||
var open = _purchaseInvoices.Query().AsNoTracking().Where(i => i.Status == PurchaseInvoiceStatus.Posted && i.BalanceAmount > 0);
|
||||
if (branchId is not null) open = open.Where(i => i.BranchId == branchId);
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
var d30 = now.AddDays(-30);
|
||||
var d60 = now.AddDays(-60);
|
||||
var d90 = now.AddDays(-90);
|
||||
return new List<ChartPointDto>
|
||||
{
|
||||
new("0-30 days", await open.Where(i => i.VendorInvoiceDate >= d30).SumAsync(i => (decimal?)i.BalanceAmount, ct) ?? 0m),
|
||||
new("31-60 days", await open.Where(i => i.VendorInvoiceDate < d30 && i.VendorInvoiceDate >= d60).SumAsync(i => (decimal?)i.BalanceAmount, ct) ?? 0m),
|
||||
new("61-90 days", await open.Where(i => i.VendorInvoiceDate < d60 && i.VendorInvoiceDate >= d90).SumAsync(i => (decimal?)i.BalanceAmount, ct) ?? 0m),
|
||||
new("90+ days", await open.Where(i => i.VendorInvoiceDate < d90).SumAsync(i => (decimal?)i.BalanceAmount, ct) ?? 0m),
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<ChartPairDto>> GetStockInVsOutAsync(int? branchId, DateTime fromAt, DateTime toBefore, CancellationToken ct)
|
||||
{
|
||||
var ledger = _ledger.Query().AsNoTracking().Where(l => l.CreatedAt >= fromAt && l.CreatedAt < toBefore);
|
||||
if (branchId is not null)
|
||||
{
|
||||
var branchWarehouses = _warehouses.Query().Where(w => w.BranchId == branchId).Select(w => w.WarehouseId);
|
||||
ledger = ledger.Where(l => branchWarehouses.Contains(l.WarehouseId));
|
||||
}
|
||||
|
||||
var rows = await ledger
|
||||
.GroupBy(l => new { l.WarehouseId, l.Direction })
|
||||
.Select(g => new { g.Key.WarehouseId, g.Key.Direction, Qty = g.Sum(x => x.QtyBase) })
|
||||
.ToListAsync(ct);
|
||||
var codes = await _warehouses.Query().AsNoTracking().ToDictionaryAsync(w => w.WarehouseId, w => w.Code, ct);
|
||||
|
||||
return rows
|
||||
.GroupBy(r => r.WarehouseId)
|
||||
.Select(g => new ChartPairDto(
|
||||
codes.GetValueOrDefault(g.Key, $"#{g.Key}"),
|
||||
g.Where(r => r.Direction == Direction.In).Sum(r => r.Qty),
|
||||
g.Where(r => r.Direction == Direction.Out).Sum(r => r.Qty)))
|
||||
.OrderByDescending(p => p.First + p.Second)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<ChartPointDto>> GetBatchesExpiringAsync(DateOnly today, CancellationToken ct)
|
||||
{
|
||||
var batches = _batches.Query().AsNoTracking().Where(b => b.ExpiryDate != null && b.ExpiryDate >= today);
|
||||
var d30 = today.AddDays(30);
|
||||
var d60 = today.AddDays(60);
|
||||
var d90 = today.AddDays(90);
|
||||
return new List<ChartPointDto>
|
||||
{
|
||||
new("Next 30 days", await batches.CountAsync(b => b.ExpiryDate <= d30, ct)),
|
||||
new("31-60 days", await batches.CountAsync(b => b.ExpiryDate > d30 && b.ExpiryDate <= d60, ct)),
|
||||
new("61-90 days", await batches.CountAsync(b => b.ExpiryDate > d60 && b.ExpiryDate <= d90, ct)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Net salary of Approved / Locked payroll runs for each of the last <see cref="PayrollMonths"/> months.</summary>
|
||||
private async Task<IReadOnlyList<ChartPointDto>> GetPayrollCostAsync(int? branchId, DateOnly today, CancellationToken ct)
|
||||
{
|
||||
var start = new DateOnly(today.Year, today.Month, 1).AddMonths(-(PayrollMonths - 1));
|
||||
var startKey = start.Year * 100 + start.Month;
|
||||
|
||||
var lines = _payrollLines.Query().AsNoTracking()
|
||||
.Where(l => (l.PayrollRun!.Status == PayrollRunStatus.Approved || l.PayrollRun.Status == PayrollRunStatus.Locked)
|
||||
&& l.PayrollRun.PeriodYear * 100 + l.PayrollRun.PeriodMonth >= startKey);
|
||||
if (branchId is not null) lines = lines.Where(l => l.PayrollRun!.BranchId == branchId);
|
||||
|
||||
var rows = await lines
|
||||
.GroupBy(l => new { l.PayrollRun!.PeriodYear, l.PayrollRun.PeriodMonth })
|
||||
.Select(g => new { g.Key.PeriodYear, g.Key.PeriodMonth, Total = g.Sum(x => x.NetSalary) })
|
||||
.ToListAsync(ct);
|
||||
var byMonth = rows.ToDictionary(r => (r.PeriodYear, r.PeriodMonth), r => r.Total);
|
||||
|
||||
return Enumerable.Range(0, PayrollMonths)
|
||||
.Select(i => start.AddMonths(i))
|
||||
.Select(m => new ChartPointDto(m.ToString("MMM", CultureInfo.InvariantCulture), byMonth.GetValueOrDefault((m.Year, m.Month))))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>Tickets opened and tickets resolved on each day of the window. A ticket carries no resolved date, so
|
||||
/// the time it was last updated while Resolved stands in for it.</summary>
|
||||
private async Task<IReadOnlyList<ChartPairDto>> GetTicketsOverTimeAsync(DateOnly from, DateOnly to, CancellationToken ct)
|
||||
{
|
||||
var fromAt = _clock.ToUtc(from);
|
||||
var toBefore = _clock.ToUtc(to.AddDays(1));
|
||||
|
||||
var opened = await _tickets.Query().AsNoTracking()
|
||||
.Where(t => t.CreatedAt >= fromAt && t.CreatedAt < toBefore)
|
||||
.Select(t => t.CreatedAt)
|
||||
.ToListAsync(ct);
|
||||
var resolved = await _tickets.Query().AsNoTracking()
|
||||
.Where(t => t.Status == TicketStatus.Resolved && t.UpdatedAt != null && t.UpdatedAt >= fromAt && t.UpdatedAt < toBefore)
|
||||
.Select(t => t.UpdatedAt!.Value)
|
||||
.ToListAsync(ct);
|
||||
|
||||
var openedByDay = opened.GroupBy(d => _clock.LocalDay(d)).ToDictionary(g => g.Key, g => g.Count());
|
||||
var resolvedByDay = resolved.GroupBy(d => _clock.LocalDay(d)).ToDictionary(g => g.Key, g => g.Count());
|
||||
|
||||
return Enumerable.Range(0, to.DayNumber - from.DayNumber + 1)
|
||||
.Select(i => from.AddDays(i))
|
||||
.Select(d => new ChartPairDto(DayLabel(d), openedByDay.GetValueOrDefault(d), resolvedByDay.GetValueOrDefault(d)))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>Active warranty registrations by the month they end, for the next six months.</summary>
|
||||
private async Task<IReadOnlyList<ChartPointDto>> GetWarrantyExpiryAsync(DateOnly today, CancellationToken ct)
|
||||
{
|
||||
var start = new DateOnly(today.Year, today.Month, 1);
|
||||
var end = start.AddMonths(6);
|
||||
var ends = await _warranties.Query().AsNoTracking()
|
||||
.Where(w => w.Status == WarrantyStatus.Active && w.EndDate >= start && w.EndDate < end)
|
||||
.Select(w => w.EndDate)
|
||||
.ToListAsync(ct);
|
||||
var byMonth = ends.GroupBy(d => (d.Year, d.Month)).ToDictionary(g => g.Key, g => g.Count());
|
||||
|
||||
return Enumerable.Range(0, 6)
|
||||
.Select(i => start.AddMonths(i))
|
||||
.Select(m => new ChartPointDto(m.ToString("MMM", CultureInfo.InvariantCulture), byMonth.GetValueOrDefault((m.Year, m.Month))))
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using ERPCore.Dtos.Dashboard;
|
||||
|
||||
namespace ERPCore.Services.Interfaces;
|
||||
|
||||
/// <summary>Datasets for the dashboard graphs.</summary>
|
||||
public interface IDashboardChartsService
|
||||
{
|
||||
/// <param name="from">Start of the period for the time-based graphs (default: today).</param>
|
||||
/// <param name="to">End of the period, inclusive (default: <paramref name="from"/>, else today).</param>
|
||||
Task<DashboardChartsDto> GetChartsAsync(int? branchId, DateOnly? from = null, DateOnly? to = null, CancellationToken ct = default);
|
||||
}
|
||||
Reference in New Issue
Block a user