Co-authored-by: Claudio Schaad <c.schaad@pog.ch> Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
57 lines
2.4 KiB
C#
57 lines
2.4 KiB
C#
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 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.Bill, 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();
|
||
}
|
||
}
|
||
}
|