AccountingNext/Schaad.Accounting.Common/Models/BillChartFilter.cs
Claudio Schaad 8b1661d7b6 Default to yearly periods on Analyse, Strom and Wasser
- Analyse: the default period is now "Jahr" (was "Monat" for a single
  year, "Quartal" otherwise); a period in the URL still wins.
- Strom/Wasser: BillChartFilter defaults to calendar years instead of
  per bill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 22:26:51 +01:00

57 lines
2.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq;
namespace Schaad.Accounting.Models
{
/// <summary>
/// What the charts on the Strom and Wasser pages show: how the bills are grouped (calendar year
/// by default) and which years. A null <see cref="FromYear"/>/<see cref="ToYear"/> means from the first/to the last
/// year with a bill, so a newly added bill shows up without touching the filter.
/// </summary>
public record BillChartFilter(BillPeriodKind Kind = BillPeriodKind.Year, int? FromYear = null, int? ToYear = null)
{
/// <summary>The years any bill touches, from the first to the last; empty without bills.</summary>
public static List<int> YearsOf<T>(IEnumerable<T> bills) where T : IPeriodBill<T>
{
var list = bills.ToList();
if (list.Count == 0)
{
return [];
}
var first = list.Min(b => b.PeriodFrom.Year);
var last = list.Max(b => b.PeriodTo.Year);
return Enumerable.Range(first, Math.Max(last - first, 0) + 1).ToList();
}
/// <summary>The selected years, clamped to <paramref name="years"/> (which must not be empty).</summary>
public (int From, int To) RangeIn(IReadOnlyList<int> years)
{
var from = Math.Clamp(FromYear ?? years[0], years[0], years[^1]);
var to = Math.Clamp(ToYear ?? years[^1], years[0], years[^1]);
return from <= to ? (from, to) : (to, from);
}
/// <summary>True if the filter covers all of <paramref name="years"/>.</summary>
public bool CoversAll(IReadOnlyList<int> years) => RangeIn(years) == (years[0], years[^1]);
/// <summary>
/// Groups the bills by <see cref="Kind"/> and keeps the periods that overlap the selected
/// years. A bill (or calendar period) reaching into the range is kept whole, e.g. the bill
/// 1.7.2023–30.6.2024 for the range 2024–2024.
/// </summary>
public List<BillPeriod<T>> Apply<T>(IEnumerable<T> bills) where T : class, IPeriodBill<T>, new()
{
var list = bills.ToList();
var years = YearsOf(list);
if (years.Count == 0)
{
return [];
}
var (from, to) = RangeIn(years);
return BillPeriod<T>.FromBills(list, Kind)
.Where(p => p.From.Year <= to && p.To.Year >= from)
.ToList();
}
}
}