Analysis: one selected period, one set of numbers, on every page
ci / build-test (push) Successful in 2m31s

The dashboards told several stories at once. Overview asked for full
calendar years, meter detail for a fixed 12-month window that was really
13, Trends for 24 months with an Apply button, and the energy pages for
60. Each page derived "today" from UTC, so the first hours of a local day
belonged to yesterday. A missing tariff, a month nobody measured and a
genuine zero all rendered as 0. And a virtual meter -- the one thing the
spreadsheet leans on hardest -- was excluded from analysis outright:
MeterPeriodService returned null for it and the page offered a flow
diagram instead.

docs/DASHBOARD_ANALYSIS_CHANGE_BRIEF.md is the work order. Every choice it
left open is settled in docs/ANALYSIS_IMPLEMENTATION_NOTE.md as D-01..D-58
plus amendments A-01..A-30; code, tests and release notes cite those ids.

The analysis layer

Core/Analysis holds the pure rules: period presets resolved once in the
instance zone into a local date range and a half-open UTC range, bucket
plans, calendar-unit comparisons, coverage runs with a resolution class,
normalized quantities and units, the totals policy, the virtual formula
parser/validator/evaluator, and the cost calculator. "Now" comes from
TimeProvider; services never read the clock.

Normalization now writes, in the same transaction as consumption and by
diff, per-meter rollups by local day and month plus coverage runs and a
rollup state (AnalysisDataWriter). AnalysisReader answers a request from
those tables -- month rollups for month and year buckets, day rollups
otherwise, at most two partial edge days from consumption -- and
CostReader prices the result month by month. Pages, /api/v1 and the CSV
export read nothing else. The unused continuous aggregates are dropped.

The reader's statement count per request is constant whether it covers one
meter or a thousand. On a synthetic 1,000-meter, ten-year instance the
brief's target request (100 meters, ten years, monthly) takes 374 ms
against a two-second target, and the Overview went from 48,244 SQL
statements per load to 205.

Missing is not zero

Every bucket carries a status -- available, partial, missing, unresolved,
invalid, pending -- derived from coverage, never from the amount, with
provenance and a reason code beside it. A true zero is a number and a bar
on the baseline; an unknown bucket is a gap that says why; a month whose
data only exists monthly says so instead of inventing daily detail; a
scope with no tariff says "not priced" instead of 0. Rows whose interval
closes after now are reported separately rather than counted.

Virtual meters are analysis subjects

A virtual meter stores a canonical definition -- expression over m<id>
references, result kind, unit and cost rule -- validated on save and on
read for syntax, unknown or self references, loops and unit/kind rules.
It is evaluated on read from its sources' rollups over their joint
coverage: a missing source makes the bucket missing, an observed zero is
a valid input, a non-finite result is invalid with its dependency path,
and the page lists each source's contribution. Topology links are
topology only and never rewrite a saved calculation; expression-less
meters from older installs are converted once at startup. The editor has
Sum, Difference and Advanced modes with a live preview.

Totals and the bill

Per energy type the totals policy separates use, grid import, export,
generation and runtime, marks breakdown meters as breakdowns and virtual
meters as views, and never adds across units. The bill follows it: grid
import where there is one, separately priced subsections at their own
price, feed-in only on export meters, standing charges once per scope per
local day, manual costs once on their start day, categories as
non-overlapping covers whose composition reconciles to the bill. The
seeded demo's yearly totals now match the spreadsheet.

Pages and navigation

The period lives in the URL and every page reads the same contract, so a
link, a reload and the browser's Back button keep it. Shared components
carry it: page header with breadcrumbs, period toolbar, theme-aware chart
with an accessible table beside it, metric cards, comparison and
availability states, attention items that each link to the one action
that fixes them. Meter detail leads with an Analysis tab and resolves its
tabs by key; the energy page has Overview, History, Flow and Meters; the
old cost-only Trends page is a general Analysis page over portfolio, type,
category, meter or a meter comparison. Records tabs are paged server-side
instead of showing the latest 200. Everything is English and German,
light and dark, down to 360px.

Some figures change on purpose; docs/RELEASE_NOTES.md lists each one and
what the first start after the update does (it rebuilds all analysis data
before the web server listens). docs/SDD.md and CLAUDE.md describe the
system as it now is.

Tests: 1,733 Core and 746 integration, all green, plus an opt-in
performance suite with a synthetic 1,000-meter generator.
This commit is contained in:
Florian Schmidt
2026-09-20 10:29:13 +02:00
parent c0f52dbb6f
commit 8940ef25c3
384 changed files with 82753 additions and 4518 deletions
@@ -0,0 +1,466 @@
using MeterVault.Core.Analysis;
using MeterVault.Core.Analysis.Costing;
using MeterVault.Core.Analysis.Totals;
using MeterVault.Core.Analysis.Virtual;
using MeterVault.Core.Domain;
using MeterVault.Infrastructure.Analysis;
using MeterVault.Infrastructure.Costing;
using static MeterVault.Integration.Tests.Costing.CostSandbox;
namespace MeterVault.Integration.Tests.Costing;
/// <summary>
/// The cost engine against real rollups (D-34 D-41, brief §6.2, §11): missing versus free prices, gaps and unit
/// mismatches, standing charges once per scope, prices month by month whatever the bucket size, separately billed
/// subsections, virtual cost rules, feed-in credits, manual costs booked once, and the latest period with data.
/// Every test builds its own energy types and meters (never the portfolio, which other tests share) and removes them.
/// </summary>
[Collection("Timescale")]
public sealed class CostReaderTests(TimescaleFixture fx) : IAsyncLifetime
{
private CostSandbox _box = null!;
public Task InitializeAsync()
{
_box = new CostSandbox(fx);
return Task.CompletedTask;
}
public async Task DisposeAsync() => await _box.DisposeAsync();
[Fact]
public async Task A_missing_tariff_is_not_priced_and_a_zero_tariff_is_a_valid_zero()
{
// Brief §11 "Missing versus free tariff": a valid quantity without a required price has no cost; an explicit
// zero tariff costs exactly zero.
var (missingType, freeType) = (await _box.TypeAsync(), await _box.TypeAsync());
var missing = await _box.MonthlyAsync(missingType, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 80);
var free = await _box.MonthlyAsync(freeType, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 80);
await _box.TypePriceAsync(freeType, 0, D(2026, 1, 1));
var period = Custom(D(2026, 1, 1), D(2026, 2, 28));
var unpriced = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(missingType), period) { Bucket = BucketSize.Month });
Assert.Equal(CostStatus.NotPriced, unpriced.Total.Status);
Assert.Null(unpriced.Total.Cost);
Assert.True(unpriced.Total.IncludesNotPriced);
Assert.Equal(
new MissingPrice(TariffComponent.UnitPrice, CostStatus.NotPriced, TariffScope.EnergyType, missingType, missing, D(2026, 1, 1), D(2026, 2, 1)),
Assert.Single(unpriced.MissingPrices));
var attention = Assert.Single(unpriced.Attention);
Assert.Equal((CostAttentionKind.MissingPrice, (int?)missing), (attention.Kind, attention.MeterId));
Assert.False(attention.Price!.IsCredit);
// The quantity is still there; only its price is missing.
var line = Assert.Single(unpriced.Lines);
Assert.Equal([100d, 80d], line.Quantities);
Assert.Equal(180, line.TotalQuantity);
Assert.Equal(BillingBasis.Use, Assert.Single(unpriced.EnergyTypes).Basis);
var priced = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(freeType), period) { Bucket = BucketSize.Month });
CostAssert.Priced(0, priced.Total);
Assert.All(priced.Buckets, b => CostAssert.Priced(0, b));
Assert.Empty(priced.MissingPrices);
Assert.Equal(free, Assert.Single(priced.Lines).MeterId);
Assert.Equal("EUR", priced.Currency);
}
[Fact]
public async Task A_gap_in_a_price_history_makes_those_months_unavailable()
{
var type = await _box.TypeAsync();
var meter = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 100, 100, 100);
await _box.TypePriceAsync(type, 0.30, D(2026, 1, 1), to: D(2026, 1, 31));
await _box.TypePriceAsync(type, 0.40, D(2026, 3, 1));
var result = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), Custom(D(2026, 1, 1), D(2026, 4, 30))) { Bucket = BucketSize.Month });
Assert.Equal([CostStatus.Priced, CostStatus.PriceGap, CostStatus.Priced, CostStatus.Priced], result.Buckets.Select(b => b.Status));
Assert.Null(result.Buckets[1].Cost);
CostAssert.Cost(30, result.Buckets[0]);
Assert.Equal(CostStatus.Partial, result.Total.Status);
CostAssert.Cost(110, result.Total);
var gap = Assert.Single(result.MissingPrices);
Assert.Equal((CostStatus.PriceGap, TariffScope.EnergyType, (int?)type, (int?)meter, D(2026, 2, 1), D(2026, 2, 1)),
(gap.Reason, gap.Scope, gap.ScopeId, gap.MeterId, gap.FirstMonth, gap.LastMonth));
Assert.Contains(result.Attention, a => a.Kind == CostAttentionKind.MissingPrice && a.Price == gap);
}
[Fact]
public async Task A_price_in_another_unit_is_a_unit_mismatch_and_a_currency_follows_the_options()
{
var type = await _box.TypeAsync();
await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100);
var tariff = await _box.TypePriceAsync(type, 5, D(2026, 1, 1), unit: "EUR/m3");
var result = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), Month(2026, 1)) { Bucket = BucketSize.Month });
Assert.Equal(CostStatus.UnitMismatch, result.Total.Status);
Assert.Null(result.Total.Cost);
var mismatch = Assert.Single(result.MissingPrices);
Assert.Equal((CostStatus.UnitMismatch, (int?)tariff), (mismatch.Reason, mismatch.TariffId));
// D-43: the instance currency is the options'; a "EUR" price does not fit a CHF instance.
var swiss = await _box.Reader("CHF").ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), Month(2026, 1)) { Bucket = BucketSize.Month });
Assert.Equal("CHF", swiss.Currency);
Assert.Equal(CostStatus.UnitMismatch, swiss.Total.Status);
}
[Fact]
public async Task A_standing_charge_accrues_once_per_scope_and_a_meter_fee_on_its_meter()
{
// Two consumption roots of one type: the type's standing charge is one row, never one per meter (D-40).
var type = await _box.TypeAsync();
var first = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 100, 100);
var second = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 100, 100);
await _box.TypePriceAsync(type, 0.10, D(2026, 1, 1));
await _box.TariffAsync(TariffScope.EnergyType, type, TariffComponent.BasePrice, 31, "EUR/month", D(2026, 1, 1));
await _box.TariffAsync(TariffScope.Meter, second, TariffComponent.BasePrice, 5, "EUR/month", D(2026, 1, 1));
var quarter = Custom(D(2026, 1, 1), D(2026, 3, 31));
var bill = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), quarter) { Bucket = BucketSize.Month });
var row = Assert.Single(bill.StandingCharges);
Assert.Equal((TariffScope.EnergyType, (int?)type), (row.Scope, row.ScopeId));
CostAssert.Priced(93, row.Total);
Assert.Equal(D(2026, 1, 1), row.Service!.FirstDay);
Assert.All(row.Buckets, b => CostAssert.Priced(31, b));
// 600 kWh × 0.10 + 3 × 31 € + the second meter's own fee 3 × 5 €, on its line.
CostAssert.Priced(60 + 93 + 15, bill.Total);
Assert.Null(bill.Lines.Single(l => l.MeterId == first).Total.StandingCharge);
Assert.Equal(15, bill.Lines.Single(l => l.MeterId == second).Total.StandingCharge!.Value, 6);
// A meter's own cost carries its own fee, never the type's charge.
var own = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(second), quarter) { Bucket = BucketSize.Month });
Assert.Empty(own.StandingCharges);
CostAssert.Priced(30 + 15, own.Total);
Assert.Equal(MeterCostRule.BillLine, own.Meter!.Rule);
// A standing charge accrues per day: half of February is half of February's charge.
var half = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), Custom(D(2026, 2, 1), D(2026, 2, 14))) { Bucket = BucketSize.Day });
CostAssert.Cost(31 * 14 / 28d, Assert.Single(half.StandingCharges).Total);
}
[Fact]
public async Task The_bucket_size_never_changes_a_total_and_every_part_is_priced_in_its_month()
{
// D-36: a year with a price change on 1 July, at daily resolution. Year, month, week and day buckets all
// price January to June at 0.30 and July to December at 0.40 — a week across the change is split.
var type = await _box.TypeAsync();
await _box.DailyAsync(type, D(2025, 1, 1), D(2026, 1, 1), perDay: 10);
await _box.TypePriceAsync(type, 0.30, D(2025, 1, 1), to: D(2025, 6, 30));
await _box.TypePriceAsync(type, 0.40, D(2025, 7, 1));
const double expected = (181 * 10 * 0.30) + (184 * 10 * 0.40);
foreach (var (size, count) in new[] { (BucketSize.Year, 1), (BucketSize.Month, 12), (BucketSize.Week, 53), (BucketSize.Day, 365) })
{
var result = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), Year(2025)) { Bucket = size });
Assert.Equal(count, result.Buckets.Count);
CostAssert.Priced(expected, result.Total, 1e-6);
Assert.Equal(expected, result.Buckets.Sum(b => b.Cost!.Value), 6);
Assert.All(result.Buckets, b => Assert.Equal(BucketStatus.Available, b.Availability));
if (size == BucketSize.Week)
{
// Monday 30 June Sunday 6 July: one day at June's price, six at July's.
var index = result.Plan.Buckets.ToList().FindIndex(b => b.FirstDay == D(2025, 6, 30));
CostAssert.Cost((10 * 0.30) + (60 * 0.40), result.Buckets[index]);
}
}
}
[Fact]
public async Task A_monthly_import_prices_its_month_although_its_days_are_unresolved()
{
var type = await _box.TypeAsync();
await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 80);
await _box.TypePriceAsync(type, 0.10, D(2026, 1, 1));
var daily = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), Month(2026, 1)) { Bucket = BucketSize.Day });
Assert.Equal(31, daily.Buckets.Count);
Assert.All(daily.Buckets, b =>
{
Assert.Null(b.Cost);
Assert.Equal(BucketStatus.Unresolved, b.Availability);
});
CostAssert.Priced(10, daily.Total);
Assert.Equal(BucketStatus.Available, daily.Total.Availability);
// Auto chooses a size the data resolves, so the chart has values.
var auto = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), Custom(D(2026, 1, 1), D(2026, 2, 28))));
Assert.Equal(BucketSize.Month, auto.Plan.Size);
Assert.Equal([10d, 8d], auto.Buckets.Select(b => Math.Round(b.Cost!.Value, 9)));
}
[Fact]
public async Task A_retired_meter_is_a_known_zero_on_the_bill_and_missing_on_its_own_page()
{
// D-24: outside its service period a meter contributes a known zero to the bill, so a meter replaced at the end
// of January leaves the quarter's bill complete; its own page still shows no data after it was retired.
var type = await _box.TypeAsync();
var retired = await _box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), retiredAt: D(2026, 1, 31));
await _box.MonthlyReadingsAsync(retired, D(2026, 1, 1), 100);
var successor = await _box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 2, 1));
await _box.MonthlyReadingsAsync(successor, D(2026, 2, 1), 80, 90);
await _box.TypePriceAsync(type, 0.10, D(2026, 1, 1));
var quarter = Custom(D(2026, 1, 1), D(2026, 3, 31));
var bill = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), quarter) { Bucket = BucketSize.Month });
Assert.Equal([10d, 8d, 9d], bill.Buckets.Select(b => Math.Round(b.Cost!.Value, 9)));
Assert.All(bill.Buckets, b => Assert.Equal(BucketStatus.Available, b.Availability));
CostAssert.Priced(27, bill.Total);
Assert.Equal(BucketStatus.Available, bill.Total.Availability);
var own = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(retired), quarter) { Bucket = BucketSize.Month });
CostAssert.Priced(10, own.Total);
Assert.Equal(BucketStatus.Partial, own.Total.Availability);
Assert.Equal(BucketStatus.Missing, own.Buckets[1].Availability);
}
[Fact]
public async Task An_unpriced_line_does_not_coarsen_the_automatic_buckets()
{
// A delta meter reporting once a quarter resolves only years; it has no tariff, so it has no cost to chart and
// must not turn the priced monthly meter's chart into one yearly bar.
var type = await _box.TypeAsync();
var monthly = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 100, 100, 100, 100, 100);
await _box.MeterPriceAsync(monthly, 0.10, D(2026, 1, 1));
var quarterly = await _box.MeterAsync(type, MeterMode.DirectDelta, "kWh", D(2026, 1, 1));
await _box.ReadingsAsync(quarterly, (Midnight(2026, 1, 1), 0), (Midnight(2026, 4, 1), 300), (Midnight(2026, 7, 1), 300));
var half = Custom(D(2026, 1, 1), D(2026, 6, 30));
var result = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), half));
Assert.Equal(BucketSize.Month, result.Plan.Size);
Assert.Equal(6, result.Buckets.Count);
Assert.All(result.Buckets, b => Assert.Equal(10, b.Cost!.Value, 6));
Assert.Contains(result.MissingPrices, m => m.MeterId == quarterly && m.Reason == CostStatus.NotPriced);
}
[Fact]
public async Task A_separately_billed_subsection_is_priced_at_its_own_price_out_of_its_parent()
{
// D-35: house 300 kWh a month, a heat pump below it 100 kWh at its own 0.22 — billed (300 100) × 0.30 + 100 × 0.22.
var type = await _box.TypeAsync();
var house = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 300, 300);
var pump = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 100);
await _box.LinkAsync(house, pump);
await _box.TypePriceAsync(type, 0.30, D(2026, 1, 1));
await _box.MeterPriceAsync(pump, 0.22, D(2026, 1, 1));
var period = Custom(D(2026, 1, 1), D(2026, 2, 28));
var bill = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), period) { Bucket = BucketSize.Month });
CostAssert.Priced((400 * 0.30) + (200 * 0.22), bill.Total);
var houseLine = bill.Lines.Single(l => l.MeterId == house);
Assert.Equal(BillLineKind.UnitPrice, houseLine.Kind);
Assert.Equal([200d, 200d], houseLine.Quantities);
Assert.Equal(pump, Assert.Single(houseLine.Deductions).MeterId);
var pumpLine = bill.Lines.Single(l => l.MeterId == pump);
Assert.Equal(BillLineKind.OwnPrice, pumpLine.Kind);
CostAssert.Priced(44, pumpLine.Total);
var pumpCost = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(pump), period) { Bucket = BucketSize.Month });
Assert.Equal((MeterCostRule.BillLine, true), (pumpCost.Meter!.Rule, pumpCost.Meter.OnBill));
CostAssert.Priced(44, pumpCost.Total);
var houseCost = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(house), period) { Bucket = BucketSize.Month });
CostAssert.Priced(120, houseCost.Total);
}
[Fact]
public async Task Virtual_meters_are_costed_by_their_named_rule()
{
// D-39: a pure sum adds its sources' costs at their own prices; a linear formula with ownQuantity prices its
// quantity; a difference has no cost. The two rules differ when the sources are priced differently.
var type = await _box.TypeAsync();
var a = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 80);
var b = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 150, 120);
var generator = await _box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2026, 1, 1), 40, 50);
await _box.TypePriceAsync(type, 0.25, D(2026, 1, 1));
await _box.MeterPriceAsync(a, 0.20, D(2026, 1, 1));
await _box.MeterPriceAsync(b, 0.30, D(2026, 1, 1));
var sources = await _box.VirtualAsync(type, $"m{a} + m{b}", QuantityKind.Consumption, "kWh", VirtualCostRule.SourceCosts);
var own = await _box.VirtualAsync(type, $"m{a} + m{b}", QuantityKind.Consumption, "kWh", VirtualCostRule.OwnQuantity);
var difference = await _box.VirtualAsync(type, $"m{a} - m{b}", QuantityKind.Consumption, "kWh", VirtualCostRule.None);
var period = Custom(D(2026, 1, 1), D(2026, 2, 28));
async Task<CostAnalysis> CostOf(int meter) =>
await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(meter), period) { Bucket = BucketSize.Month });
var summed = await CostOf(sources);
Assert.Equal(MeterCostRule.SourceCosts, summed.Meter!.Rule);
Assert.False(summed.Meter.OnBill);
Assert.Equal([a, b], summed.Meter.SourceIds);
CostAssert.Priced((180 * 0.20) + (270 * 0.30), summed.Total);
Assert.All(summed.Lines, l => Assert.Equal(sources, l.ForMeterId));
var repriced = await CostOf(own);
Assert.Equal(MeterCostRule.OwnQuantity, repriced.Meter!.Rule);
CostAssert.Priced(450 * 0.25, repriced.Total);
Assert.Equal(own, Assert.Single(repriced.Lines).MeterId);
var none = await CostOf(difference);
Assert.Equal((MeterCostRule.None, MeterNotCostedReason.NoCostRule), (none.Meter!.Rule, none.Meter.NotCosted));
Assert.Empty(none.Lines);
Assert.Null(none.Total.Cost);
var generation = await CostOf(generator);
Assert.Equal((MeterCostRule.None, MeterNotCostedReason.Generation), (generation.Meter!.Rule, generation.Meter.NotCosted));
// The sources are the type's bill; the virtual views never add to it.
var bill = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), period) { Bucket = BucketSize.Month });
Assert.Equal([a, b], bill.Lines.Select(l => l.MeterId).Order());
CostAssert.Priced((180 * 0.20) + (270 * 0.30), bill.Total);
}
[Fact]
public async Task A_virtual_meter_counted_by_an_override_is_billed_by_its_cost_rule()
{
// D-23 + D-39: "always" puts a virtual pure sum on the bill in place of its sources; the bill then prices it by
// its rule — its sources at their own prices, or its own quantity — and never both. With the rule "none" it is
// left out and named.
const string always = "{\"totals\":\"always\"}";
var period = Custom(D(2026, 1, 1), D(2026, 2, 28));
async Task<(int A, int B, short Type)> SourcesAsync()
{
var type = await _box.TypeAsync();
var a = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 80);
var b = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 150, 120);
await _box.TypePriceAsync(type, 0.25, D(2026, 1, 1));
await _box.MeterPriceAsync(a, 0.20, D(2026, 1, 1));
await _box.MeterPriceAsync(b, 0.30, D(2026, 1, 1));
return (a, b, type);
}
async Task<CostAnalysis> BillOf(short type) =>
await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), period) { Bucket = BucketSize.Month });
var (a1, b1, bySources) = await SourcesAsync();
var summed = await _box.VirtualAsync(bySources, $"m{a1} + m{b1}", QuantityKind.Consumption, "kWh", VirtualCostRule.SourceCosts, always);
var sourcesBill = await BillOf(bySources);
Assert.Equal([a1, b1], sourcesBill.Lines.Select(l => l.MeterId).Order());
Assert.All(sourcesBill.Lines, l => Assert.Equal(summed, l.ForMeterId));
CostAssert.Priced((180 * 0.20) + (270 * 0.30), sourcesBill.Total);
var summedCost = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(summed), period) { Bucket = BucketSize.Month });
Assert.Equal((MeterCostRule.SourceCosts, true), (summedCost.Meter!.Rule, summedCost.Meter.OnBill));
var (a2, b2, byQuantity) = await SourcesAsync();
var own = await _box.VirtualAsync(byQuantity, $"m{a2} + m{b2}", QuantityKind.Consumption, "kWh", VirtualCostRule.OwnQuantity, always);
var ownBill = await BillOf(byQuantity);
Assert.Equal(own, Assert.Single(ownBill.Lines).MeterId);
CostAssert.Priced(450 * 0.25, ownBill.Total);
var (a3, b3, uncosted) = await SourcesAsync();
var none = await _box.VirtualAsync(uncosted, $"m{a3} + m{b3}", QuantityKind.Consumption, "kWh", VirtualCostRule.None, always);
var noneBill = await BillOf(uncosted);
Assert.Empty(noneBill.Lines);
Assert.Null(noneBill.Total.Cost);
Assert.Equal(none, Assert.Single(noneBill.Attention, x => x.Kind == CostAttentionKind.VirtualNotCosted).MeterId);
}
[Fact]
public async Task Export_is_credited_at_the_feed_in_price_and_a_missing_one_is_an_optional_credit()
{
var type = await _box.TypeAsync();
var grid = await _box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridImport));
var export = await _box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridExport));
await _box.MonthlyReadingsAsync(grid, D(2026, 1, 1), 300, 300);
await _box.MonthlyReadingsAsync(export, D(2026, 1, 1), 50, 50);
await _box.TypePriceAsync(type, 0.30, D(2026, 1, 1));
var period = Custom(D(2026, 1, 1), D(2026, 2, 28));
var noCredit = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), period) { Bucket = BucketSize.Month });
CostAssert.Priced(180, noCredit.Total);
var credit = Assert.Single(noCredit.MissingPrices);
Assert.True(credit.IsCredit);
Assert.Equal((CostStatus.NotPriced, (int?)export), (credit.Reason, credit.MeterId));
await _box.TariffAsync(TariffScope.EnergyType, type, TariffComponent.FeedIn, 0.08, "EUR/kWh", D(2026, 1, 1));
var credited = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), period) { Bucket = BucketSize.Month });
CostAssert.Priced(180 - 8, credited.Total);
Assert.Equal(180, credited.Total.Charges!.Value, 6);
Assert.Equal(8, credited.Total.FeedInCredit!.Value, 6);
Assert.Equal(BillLineKind.FeedIn, credited.Lines.Single(l => l.MeterId == export).Kind);
Assert.Empty(credited.MissingPrices);
}
[Fact]
public async Task Manual_costs_are_booked_once_on_their_start_day_wherever_they_belong()
{
// D-41: a manual cost on a meter belongs to that meter, its type and its categories — once each — and one
// dated after today is reported, not booked.
var type = await _box.TypeAsync();
var meter = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 100, 100);
await _box.TypePriceAsync(type, 0.10, D(2026, 1, 1));
var booked = await _box.ManualCostAsync(D(2026, 2, 10), 50, meterId: meter);
var later = await _box.ManualCostAsync(D(2026, 10, 1), 20, meterId: meter);
var category = await _box.CategoryAsync($"cost-{Guid.NewGuid():N}", 90, meters: [meter]);
var year = Year(2026);
foreach (var scope in new[] { CostScope.ForEnergyType(type), CostScope.ForMeter(meter), CostScope.ForCategory(category) })
{
var result = await _box.Reader().ReadAsync(new CostAnalysisRequest(scope, year) { Bucket = BucketSize.Month });
CostAssert.Priced(30 + 50, result.Total);
var booking = Assert.Single(result.ManualCosts.Bookings);
Assert.Equal((booked, D(2026, 2, 10), 1, 50d), (booking.ManualCostId, booking.Day, booking.BucketIndex, booking.Amount));
CostAssert.Priced(50, result.ManualCosts.Buckets[1]);
Assert.Equal([later], result.ManualCosts.AfterTodayIds);
Assert.Equal([later], Assert.Single(result.Attention, a => a.Kind == CostAttentionKind.ManualCostAfterToday).ManualCostIds);
}
var figure = (await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForCategory(category), year) { Bucket = BucketSize.Month })).Category!;
Assert.Contains(booked, figure.ManualCostIds);
Assert.Equal([meter], figure.Cover.BilledMeterIds);
}
[Fact]
public async Task The_latest_period_with_data_includes_manual_costs()
{
// D-19: metered data ends in February; a manual cost on the meter in April makes April the latest month.
var type = await _box.TypeAsync();
var meter = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 80);
await _box.TypePriceAsync(type, 0.10, D(2026, 1, 1));
var metered = await _box.Reader().GetAvailabilityAsync(CostScope.ForEnergyType(type), Now);
Assert.Equal(new LatestPeriod(D(2026, 2, 1), LatestPeriodBasis.Meters), metered.Latest);
await _box.ManualCostAsync(D(2026, 4, 10), 12, meterId: meter);
var withManual = await _box.Reader().GetAvailabilityAsync(CostScope.ForEnergyType(type), Now);
Assert.Equal(new LatestPeriod(D(2026, 4, 1), LatestPeriodBasis.Manual), withManual.Latest);
Assert.Equal((D(2026, 1, 1), D(2026, 4, 10)), (withManual.Range!.FirstDay, withManual.Range.LastDay));
// The priced result reports the same, whatever period it prices.
var result = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(meter), Preset(PeriodPreset.MonthToDate)));
Assert.Equal(withManual.Latest, result.Availability.Latest);
// A month with both is both.
await _box.ManualCostAsync(D(2026, 2, 3), 5, meterId: meter);
var both = await _box.Reader().GetAvailabilityAsync(CostScope.ForMeter(meter), new DateTimeOffset(2026, 3, 15, 12, 0, 0, TimeSpan.Zero));
Assert.Equal(new LatestPeriod(D(2026, 2, 1), LatestPeriodBasis.Both), both.Latest);
}
[Fact]
public async Task Unknown_scopes_and_too_many_points_are_refused_before_pricing()
{
var reader = _box.Reader();
Assert.Equal(CostRefusal.UnknownScope, (await reader.ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(-1), Month(2026, 1)))).Refusal);
Assert.Equal(CostRefusal.UnknownScope, (await reader.ReadAsync(new CostAnalysisRequest(CostScope.ForCategory(-1), Month(2026, 1)))).Refusal);
var days = await reader.ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, Preset(PeriodPreset.Last24Months)) { Bucket = BucketSize.Day });
Assert.Equal(CostRefusal.TooManyPoints, days.Refusal);
Assert.Equal(BucketSize.Week, days.Plan.Suggested);
Assert.Null(days.Total.Cost);
var other = PeriodResolver.Resolve(PeriodPreset.MonthToDate, null, null, Now, TimeZoneInfo.Utc);
await Assert.ThrowsAsync<ArgumentException>(() => reader.ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, other)));
}
}
@@ -11,7 +11,8 @@ namespace MeterVault.Integration.Tests.Costing;
/// <summary>
/// Reconciles the cost engine against the Wasser sheet's Kosten column (consumption × €/m³) and
/// checks category rollups and continuous-aggregate refresh (SDD §7.5, §5.4).
/// checks category rollups and the monthly consumption rollups that replaced the continuous
/// aggregates (SDD §7.5, D-17).
/// </summary>
[Collection("Timescale")]
public sealed class CostReconciliationTests(TimescaleFixture fx)
@@ -74,34 +75,30 @@ public sealed class CostReconciliationTests(TimescaleFixture fx)
}
[Fact]
public async Task Monthly_continuous_aggregate_refreshes_and_matches_base()
public async Task Monthly_rollup_equals_the_consumption_it_sums()
{
// D-17: the rollup written with the import, in the normalizer's zone (UTC here), is what month and year
// reads use — no refresh step, no lag, and the same total the consumption rows add up to.
await using var db = fx.CreateContext();
var meterId = await ImportWaterAsync(db);
// refresh_continuous_aggregate cannot run inside a transaction — use the raw connection.
var connection = db.Database.GetDbConnection();
await connection.OpenAsync();
await using (var cmd = connection.CreateCommand())
{
cmd.CommandText = "CALL refresh_continuous_aggregate('consumption_monthly', NULL, NULL);";
await cmd.ExecuteNonQueryAsync();
}
var months = await db.ConsumptionRollupMonths.AsNoTracking()
.Where(r => r.MeterId == meterId)
.ToDictionaryAsync(r => r.Month, r => r.Amount);
var rows = await db.Consumption.AsNoTracking().Where(c => c.MeterId == meterId).ToListAsync();
var byMonth = rows
.GroupBy(c => new DateOnly(c.Time.UtcDateTime.Year, c.Time.UtcDateTime.Month, 1))
.ToDictionary(g => g.Key, g => g.Sum(c => c.Amount));
double aggregated;
await using (var cmd = connection.CreateCommand())
{
cmd.CommandText =
"SELECT sum(amount) FROM consumption_monthly WHERE meter_id = @m " +
"AND (bucket AT TIME ZONE 'Europe/Berlin')::date = DATE '2022-12-01';";
var p = cmd.CreateParameter();
p.ParameterName = "m";
p.Value = meterId;
cmd.Parameters.Add(p);
aggregated = Convert.ToDouble(await cmd.ExecuteScalarAsync());
}
Assert.Equal(14d, months[new DateOnly(2022, 12, 1)], 6); // Dez 2022 consumption
Assert.Equal(byMonth.Keys.Order(), months.Keys.Order());
Assert.All(byMonth, m => Assert.Equal(m.Value, months[m.Key], 9));
Assert.Equal(14d, aggregated, 1); // Dez 2022 consumption
// The day table holds the same December, on the day the month row is filed.
var decemberDays = await db.ConsumptionRollups.AsNoTracking()
.Where(r => r.MeterId == meterId && r.Day >= new DateOnly(2022, 12, 1) && r.Day < new DateOnly(2023, 1, 1))
.SumAsync(r => r.Amount);
Assert.Equal(14d, decemberDays, 6);
await CleanupAsync(db, meterId);
}
@@ -0,0 +1,317 @@
using MeterVault.Core.Analysis;
using MeterVault.Core.Analysis.Costing;
using MeterVault.Core.Analysis.Totals;
using MeterVault.Core.Analysis.Virtual;
using MeterVault.Core.Domain;
using MeterVault.Infrastructure.Costing;
using static MeterVault.Integration.Tests.Costing.CostSandbox;
namespace MeterVault.Integration.Tests.Costing;
/// <summary>
/// Regressions from the cost review (R1 R6): costs that intervals longer than a month still allow, virtual source
/// costs priced the way each source's own scope is, meter fees on meters the bill has no line for, the months a grid
/// meter was not in service, and a priced consumer linked directly below the grid meter.
/// </summary>
[Collection("Timescale")]
public sealed class CostReviewFixTests(TimescaleFixture fx) : IAsyncLifetime
{
private CostSandbox _box = null!;
public Task InitializeAsync()
{
_box = new CostSandbox(fx);
return Task.CompletedTask;
}
public async Task DisposeAsync() => await _box.DisposeAsync();
// ------------------------------------------------------------------------------------------------ R5
[Fact]
public async Task A_quarterly_delta_meter_with_one_price_has_a_yearly_cost()
{
// R5 (D-36, D-14): read once a quarter, the meter cannot be cut into months, so no month has a cost. One price
// covers every month of every interval, though, so the year has one: 1,200 kWh × 0.10.
var type = await _box.TypeAsync();
var quarterly = await QuarterlyAsync(type);
await _box.TypePriceAsync(type, 0.10, D(2025, 1, 1));
var yearly = await BillAsync(type, Year(2025), BucketSize.Year);
CostAssert.Priced(120, yearly.Total);
CostAssert.Priced(120, Assert.Single(yearly.Buckets));
var monthly = await BillAsync(type, Year(2025), BucketSize.Month);
Assert.All(monthly.Buckets, b => Assert.Null(b.Cost));
Assert.All(monthly.Buckets, b => Assert.Equal(BucketStatus.Unresolved, b.Availability));
CostAssert.Priced(120, monthly.Total);
var auto = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), Year(2025)));
Assert.Equal(BucketSize.Year, auto.Plan.Size);
CostAssert.Priced(120, auto.Total);
var own = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(quarterly), Year(2025)) { Bucket = BucketSize.Year });
CostAssert.Priced(120, own.Total);
Assert.DoesNotContain(own.Attention, a => a.Kind == CostAttentionKind.PriceChangeInsideInterval);
}
[Fact]
public async Task A_price_change_inside_an_interval_leaves_the_span_unavailable_and_says_why()
{
// R5: the price rises from August; the July September interval spans both prices and cannot be split, so the
// year has no cost — never a confident one, never 0 — and the attention item names the meter.
var type = await _box.TypeAsync();
var quarterly = await QuarterlyAsync(type);
await _box.TypePriceAsync(type, 0.10, D(2025, 1, 1), to: D(2025, 7, 31));
await _box.TypePriceAsync(type, 0.20, D(2025, 8, 1));
var yearly = await BillAsync(type, Year(2025), BucketSize.Year);
Assert.Null(yearly.Total.Cost);
Assert.Equal(BucketStatus.Unresolved, yearly.Total.Availability);
var attention = Assert.Single(yearly.Attention, a => a.Kind == CostAttentionKind.PriceChangeInsideInterval);
Assert.Equal(quarterly, attention.MeterId);
Assert.Equal((D(2025, 1, 1), D(2025, 12, 1)), (attention.FirstMonth, attention.LastMonth));
}
// ------------------------------------------------------------------------------------------------ R1
[Fact]
public async Task A_sum_of_generation_meters_has_no_purchase_cost()
{
// R1 (D-34, D-39): the sources' own costs are "none (generation)", so their sum costs nothing — not 250 kWh at
// the purchase price.
var type = await _box.TypeAsync();
var s1 = await _box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2026, 1, 1), 100);
var s2 = await _box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2026, 1, 1), 150);
await _box.TypePriceAsync(type, 0.30, D(2026, 1, 1));
var sum = await _box.VirtualAsync(type, $"m{s1} + m{s2}", QuantityKind.Generation, "kWh", VirtualCostRule.SourceCosts);
var summed = await CostOfAsync(sum, Month(2026, 1));
Assert.Null(summed.Total.Cost);
Assert.Empty(summed.Lines);
Assert.Equal((MeterCostRule.None, MeterNotCostedReason.Generation), (summed.Meter!.Rule, summed.Meter.NotCosted));
// A generation sum is not costed by default either.
Assert.Equal(VirtualCostRule.None, VirtualValidator.DefaultCostRule(Formula.Parse($"m{s1} + m{s2}"), QuantityKind.Generation));
}
[Fact]
public async Task An_export_view_costs_its_source_s_feed_in_credit()
{
// R1: a view over the export meter adds the export meter's own cost — a feed-in credit, not a purchase.
var type = await _box.TypeAsync();
var grid = await _box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridImport));
var export = await _box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridExport));
await _box.MonthlyReadingsAsync(grid, D(2026, 1, 1), 300);
await _box.MonthlyReadingsAsync(export, D(2026, 1, 1), 50);
await _box.TypePriceAsync(type, 0.30, D(2026, 1, 1));
await _box.TariffAsync(TariffScope.EnergyType, type, TariffComponent.FeedIn, 0.08, "EUR/kWh", D(2026, 1, 1));
var view = await _box.VirtualAsync(type, $"m{export}", QuantityKind.Net, "kWh", VirtualCostRule.SourceCosts);
var own = await CostOfAsync(export, Month(2026, 1));
var viewed = await CostOfAsync(view, Month(2026, 1));
CostAssert.Priced(-4, own.Total);
CostAssert.Priced(-4, viewed.Total);
Assert.Equal(BillLineKind.FeedIn, Assert.Single(viewed.Lines).Kind);
}
// ------------------------------------------------------------------------------------------------ R2
[Fact]
public async Task Source_costs_follow_the_formula_and_never_price_a_subtrahend()
{
// R2 (D-39): a sum over a nested difference is not a sum of metered costs — pricing its tokens would add the
// subtrahend's cost (18 instead of 12). It is not costed, and says why. A repeated token counts by its weight.
var type = await _box.TypeAsync();
var a = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100);
var b = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 30);
var c = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 50);
await _box.TypePriceAsync(type, 0.10, D(2026, 1, 1));
var difference = await _box.VirtualAsync(type, $"m{a} - m{b}", QuantityKind.Consumption, "kWh", VirtualCostRule.None);
var nested = await _box.VirtualAsync(type, $"m{difference} + m{c}", QuantityKind.Consumption, "kWh", VirtualCostRule.SourceCosts);
var repeated = await _box.VirtualAsync(type, $"m{a} + m{a} - m{a} + m{b}", QuantityKind.Consumption, "kWh", VirtualCostRule.SourceCosts);
var overDifference = await CostOfAsync(nested, Month(2026, 1));
Assert.Null(overDifference.Total.Cost);
Assert.Empty(overDifference.Lines);
Assert.Equal((MeterCostRule.None, MeterNotCostedReason.SourcesNotPureSum), (overDifference.Meter!.Rule, overDifference.Meter.NotCosted));
var weighted = await CostOfAsync(repeated, Month(2026, 1));
CostAssert.Priced(13, weighted.Total);
Assert.Equal([a, b], weighted.Lines.Select(l => l.MeterId).Order());
// Nested pure sums are expanded to their sources, each once.
var inner = await _box.VirtualAsync(type, $"m{a} + m{b}", QuantityKind.Consumption, "kWh", VirtualCostRule.SourceCosts);
var outer = await _box.VirtualAsync(type, $"m{inner} + m{c}", QuantityKind.Consumption, "kWh", VirtualCostRule.SourceCosts);
CostAssert.Priced(18, (await CostOfAsync(outer, Month(2026, 1))).Total);
}
// ------------------------------------------------------------------------------------------------ R3
[Fact]
public async Task A_meter_fee_on_a_meter_without_a_bill_line_is_still_charged_on_its_meter()
{
// R3 (D-40): grid 100 kWh a month, the house behind it 150 kWh, a PV meter; fees of 2 €/month on the PV meter
// and 5 €/month on the house. The bill prices the grid import, and still charges both fees — each as its own
// row on its meter.
var type = await _box.TypeAsync();
var grid = await _box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridImport));
var house = await _box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.TotalLoad));
await _box.MonthlyReadingsAsync(grid, D(2026, 1, 1), 100, 100, 100);
await _box.MonthlyReadingsAsync(house, D(2026, 1, 1), 150, 150, 150);
await _box.LinkAsync(grid, house);
var pv = await _box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2026, 1, 1), 40, 40, 40);
await _box.TypePriceAsync(type, 0.30, D(2026, 1, 1));
await _box.TariffAsync(TariffScope.Meter, pv, TariffComponent.BasePrice, 2, "EUR/month", D(2026, 1, 1));
await _box.TariffAsync(TariffScope.Meter, house, TariffComponent.BasePrice, 5, "EUR/month", D(2026, 1, 1));
var quarter = Custom(D(2026, 1, 1), D(2026, 3, 31));
var bill = await BillAsync(type, quarter, BucketSize.Month);
CostAssert.Priced(90 + 6 + 15, bill.Total);
Assert.Equal([grid], bill.Lines.Select(l => l.MeterId));
Assert.Equal(
[(TariffScope.Meter, (int?)house, 15d), (TariffScope.Meter, (int?)pv, 6d)],
bill.StandingCharges.Select(r => (r.Scope, r.ScopeId, Math.Round(r.Total.Cost!.Value, 6))).OrderBy(r => r.Item2));
var pvOwn = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(pv), quarter) { Bucket = BucketSize.Month });
CostAssert.Priced(6, pvOwn.Total);
var houseOwn = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(house), quarter) { Bucket = BucketSize.Month });
CostAssert.Priced(135 + 15, houseOwn.Total);
// The portfolio's composition reconciles to the bill, the fees included.
var portfolio = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), quarter) { Bucket = BucketSize.Month });
CostAssert.Priced(111, portfolio.EnergyTypes.Single(t => t.EnergyTypeId == type).Total);
}
// ------------------------------------------------------------------------------------------------ R4
[Fact]
public async Task Months_before_the_grid_meter_was_installed_are_not_a_confident_zero_bill()
{
// R4 (D-34 + D-24): the house was measured from January, the grid meter only installed on 1 April. Before then
// the grid meter's known zero must not stand in for the bill: those months are unavailable, and say why.
var type = await _box.TypeAsync();
var house = await _box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2025, 1, 1), MeterMeta.WithRole("{}", MeterRoles.TotalLoad));
await _box.MonthlyReadingsAsync(house, D(2025, 1, 1), 100, 100, 100, 100, 100, 100);
var grid = await _box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2025, 4, 1), MeterMeta.WithRole("{}", MeterRoles.GridImport));
await _box.MonthlyReadingsAsync(grid, D(2025, 4, 1), 60, 60, 60);
await _box.LinkAsync(grid, house);
await _box.TypePriceAsync(type, 0.30, D(2025, 1, 1));
var q1 = await BillAsync(type, Custom(D(2025, 1, 1), D(2025, 3, 31)), BucketSize.Month);
Assert.Null(q1.Total.Cost);
Assert.NotEqual(BucketStatus.Available, q1.Total.Availability);
Assert.All(q1.Buckets, b => Assert.Null(b.Cost));
var gap = Assert.Single(q1.Attention, a => a.Kind == CostAttentionKind.BillingBasisGap);
Assert.Equal((grid, D(2025, 1, 1), D(2025, 3, 1)), (gap.MeterId!.Value, gap.FirstMonth, gap.LastMonth));
var q2 = await BillAsync(type, Custom(D(2025, 4, 1), D(2025, 6, 30)), BucketSize.Month);
CostAssert.Priced(54, q2.Total);
Assert.DoesNotContain(q2.Attention, a => a.Kind == CostAttentionKind.BillingBasisGap);
var half = await BillAsync(type, Custom(D(2025, 1, 1), D(2025, 6, 30)), BucketSize.Month);
Assert.Equal(54, half.Total.Cost!.Value, 6);
Assert.Equal(BucketStatus.Partial, half.Total.Availability);
}
[Fact]
public async Task Months_after_the_grid_meter_retired_without_a_successor_are_not_a_confident_zero_bill()
{
var type = await _box.TypeAsync();
var house = await _box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2025, 1, 1), MeterMeta.WithRole("{}", MeterRoles.TotalLoad));
await _box.MonthlyReadingsAsync(house, D(2025, 1, 1), [.. Enumerable.Repeat(100d, 12)]);
var grid = await _box.MeterAsync(
type, MeterMode.CumulativeCounter, "kWh", D(2025, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridImport), retiredAt: D(2025, 6, 30));
await _box.MonthlyReadingsAsync(grid, D(2025, 1, 1), 60, 60, 60, 60, 60, 60);
await _box.LinkAsync(grid, house);
await _box.TypePriceAsync(type, 0.30, D(2025, 1, 1));
var h1 = await BillAsync(type, Custom(D(2025, 1, 1), D(2025, 6, 30)), BucketSize.Month);
CostAssert.Priced(108, h1.Total);
var h2 = await BillAsync(type, Custom(D(2025, 7, 1), D(2025, 12, 31)), BucketSize.Month);
Assert.Null(h2.Total.Cost);
var gap = Assert.Single(h2.Attention, a => a.Kind == CostAttentionKind.BillingBasisGap);
Assert.Equal((grid, D(2025, 7, 1), D(2025, 12, 1)), (gap.MeterId!.Value, gap.FirstMonth, gap.LastMonth));
}
// ------------------------------------------------------------------------------------------------ R6
[Fact]
public async Task A_priced_consumer_linked_below_the_grid_meter_is_billed_at_its_own_price()
{
// R6 (D-35, Kaskade): grid 300 kWh a month, a heat pump behind it 100 kWh at its own 0.22, linked grid → pump:
// 2 × ((300 100) × 0.30 + 100 × 0.22) = 164, not the whole import at 0.30.
var type = await _box.TypeAsync();
var grid = await _box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridImport));
await _box.MonthlyReadingsAsync(grid, D(2026, 1, 1), 300, 300);
var pump = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 100);
await _box.LinkAsync(grid, pump);
await _box.TypePriceAsync(type, 0.30, D(2026, 1, 1));
await _box.MeterPriceAsync(pump, 0.22, D(2026, 1, 1));
var bill = await BillAsync(type, Custom(D(2026, 1, 1), D(2026, 2, 28)), BucketSize.Month);
CostAssert.Priced(164, bill.Total);
Assert.Equal([200d, 200d], bill.Lines.Single(l => l.MeterId == grid).Quantities);
Assert.Equal(BillLineKind.OwnPrice, bill.Lines.Single(l => l.MeterId == pump).Kind);
Assert.DoesNotContain(bill.Attention, a => a.Kind == CostAttentionKind.BillingConfiguration);
}
// ------------------------------------------------------------------------------------------------ acceptance review
[Fact]
public async Task A_category_whose_members_price_nothing_says_why_instead_of_reading_empty()
{
// D-39/D-42 keep a calculated view out of a category's cost; brief §4.3 asks for an explained result, not an empty
// one. A category holding only a costed consumption view (sourceCosts) prices nothing and says which members
// add nothing; one that also holds its metered source prices the source and says nothing.
var type = await _box.TypeAsync();
var a = await _box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2025, 1, 1), 100, 80);
await _box.TypePriceAsync(type, 0.30, D(2024, 1, 1));
var view = await _box.VirtualAsync(type, $"m{a}", QuantityKind.Consumption, "kWh", VirtualCostRule.SourceCosts);
var viewOnly = await _box.CategoryAsync($"view-only-{Guid.NewGuid():N}", 93, meters: [view]);
var withSource = await _box.CategoryAsync($"with-source-{Guid.NewGuid():N}", 94, meters: [a, view]);
var period = Custom(D(2025, 1, 1), D(2025, 2, 28));
// The view has a cost of its own: its source's.
CostAssert.Priced(54, (await CostOfAsync(view, period)).Total);
var alone = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForCategory(viewOnly), period) { Bucket = BucketSize.Month });
Assert.Null(alone.Total.Cost);
var note = Assert.Single(alone.Attention, x => x.Kind == CostAttentionKind.CategoryPricesNothing);
Assert.Equal(viewOnly, note.CategoryId);
Assert.Equal([view], note.MeterIds);
Assert.Equal(view, note.MeterId);
var both = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForCategory(withSource), period) { Bucket = BucketSize.Month });
CostAssert.Priced(54, both.Total);
Assert.DoesNotContain(both.Attention, x => x.Kind == CostAttentionKind.CategoryPricesNothing);
// The portfolio with its categories names it too, for the Overview.
var portfolio = await _box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, period) { Bucket = BucketSize.Month, IncludeCategories = true });
Assert.Contains(portfolio.Attention, x => x.Kind == CostAttentionKind.CategoryPricesNothing && x.CategoryId == viewOnly);
Assert.DoesNotContain(portfolio.Attention, x => x.Kind == CostAttentionKind.CategoryPricesNothing && x.CategoryId == withSource);
}
// ------------------------------------------------------------------------------------------------ helpers
private async Task<int> QuarterlyAsync(short type)
{
var meter = await _box.MeterAsync(type, MeterMode.DirectDelta, "kWh", D(2025, 1, 1));
await _box.ReadingsAsync(
meter,
(Midnight(2025, 1, 1), 0), (Midnight(2025, 4, 1), 300), (Midnight(2025, 7, 1), 300), (Midnight(2025, 10, 1), 300), (Midnight(2026, 1, 1), 300));
return meter;
}
private Task<CostAnalysis> BillAsync(short type, ResolvedPeriod period, BucketSize size) =>
_box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(type), period) { Bucket = size });
private Task<CostAnalysis> CostOfAsync(int meter, ResolvedPeriod period) =>
_box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(meter), period) { Bucket = BucketSize.Month });
}
@@ -0,0 +1,281 @@
using MeterVault.Core.Analysis;
using MeterVault.Core.Analysis.Costing;
using MeterVault.Core.Analysis.Virtual;
using MeterVault.Core.Domain;
using MeterVault.Core.Normalization;
using MeterVault.Infrastructure.Analysis;
using MeterVault.Infrastructure.Costing;
using MeterVault.Infrastructure.Normalization;
using MeterVault.Infrastructure.Options;
using MeterVault.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
namespace MeterVault.Integration.Tests.Costing;
/// <summary>
/// Builds what a cost test prices — its own energy types, meters with readings normalized in Berlin, tariffs, manual
/// costs and categories — on a frozen clock of 19 September 2026, 14:37 Berlin, and removes all of it again.
/// </summary>
internal sealed class CostSandbox(TimescaleFixture fx) : IAsyncDisposable
{
public const string BerlinId = "Europe/Berlin";
public static readonly TimeZoneInfo Berlin = TimeZoneInfo.FindSystemTimeZoneById(BerlinId);
/// <summary>The frozen "now" of every request (D-01), after the reference data ends (31 May 2026).</summary>
public static readonly DateTimeOffset Now = new DateTimeOffset(2026, 9, 19, 14, 37, 0, TimeSpan.FromHours(2)).ToUniversalTime();
private readonly List<int> _meters = [];
private readonly List<short> _types = [];
private readonly List<int> _tariffs = [];
private readonly List<int> _manualCosts = [];
private readonly List<int> _categories = [];
public TimescaleFixture Fixture => fx;
public static ResolvedPeriod Custom(DateOnly first, DateOnly last) => PeriodResolver.Resolve(PeriodPreset.Custom, first, last, Now, Berlin);
public static ResolvedPeriod Year(int year) => Custom(new DateOnly(year, 1, 1), new DateOnly(year, 12, 31));
public static ResolvedPeriod Month(int year, int month) =>
Custom(new DateOnly(year, month, 1), new DateOnly(year, month, DateTime.DaysInMonth(year, month)));
public static ResolvedPeriod Preset(PeriodPreset preset) => PeriodResolver.Resolve(preset, null, null, Now, Berlin);
public static DateTimeOffset Midnight(int year, int month, int day) => GapAttribution.LocalMidnight(new DateOnly(year, month, day), Berlin);
public static DateOnly D(int year, int month, int day) => new(year, month, day);
public CostReader Reader(string currency = "EUR")
{
var options = Microsoft.Extensions.Options.Options.Create(new MeterVaultOptions { TimeZone = BerlinId, Currency = currency });
return new CostReader(fx, new AnalysisReader(fx, options), options);
}
public async Task<short> TypeAsync(string unit = "kWh")
{
await using var db = fx.CreateContext();
var type = new EnergyType
{
Key = $"cost-{Guid.NewGuid():N}",
DisplayName = "Cost test",
BaseUnit = unit,
DefaultMode = MeterMode.CumulativeCounter,
};
db.EnergyTypes.Add(type);
await db.SaveChangesAsync();
_types.Add(type.Id);
return type.Id;
}
public async Task<int> MeterAsync(
short type, MeterMode mode, string unit, DateOnly? installedAt = null, string meta = "{}", DateOnly? retiredAt = null, string? name = null)
{
await using var db = fx.CreateContext();
var meter = new Meter
{
Name = name ?? $"cost-{Guid.NewGuid():N}",
EnergyTypeId = type,
Mode = mode,
Unit = unit,
InstalledAt = installedAt,
RetiredAt = retiredAt,
Meta = meta,
};
db.Meters.Add(meter);
await db.SaveChangesAsync();
_meters.Add(meter.Id);
return meter.Id;
}
/// <summary>
/// A counter installed on the 1st of <paramref name="firstMonth"/> whose consecutive local months book the given
/// amounts: one reading at each following local midnight of the 1st.
/// </summary>
public async Task<int> MonthlyAsync(short type, MeterMode mode, DateOnly firstMonth, params double[] months)
{
var meter = await MeterAsync(type, mode, "kWh", installedAt: firstMonth);
await MonthlyReadingsAsync(meter, firstMonth, months);
return meter;
}
/// <summary>Monthly readings on an existing meter, as <see cref="MonthlyAsync"/> writes them.</summary>
public async Task MonthlyReadingsAsync(int meter, DateOnly firstMonth, params double[] months)
{
var register = 0d;
var readings = new List<(DateTimeOffset, double)>();
for (var i = 0; i < months.Length; i++)
{
register += months[i];
var next = firstMonth.AddMonths(i + 1);
readings.Add((Midnight(next.Year, next.Month, 1), register));
}
await ReadingsAsync(meter, [.. readings]);
}
/// <summary>A counter installed on <paramref name="from"/> that rises by <paramref name="perDay"/> at every local midnight up to <paramref name="to"/>.</summary>
public async Task<int> DailyAsync(short type, DateOnly from, DateOnly to, double perDay)
{
var meter = await MeterAsync(type, MeterMode.CumulativeCounter, "kWh", installedAt: from);
var readings = new List<(DateTimeOffset, double)>();
var register = 0d;
for (var day = from.AddDays(1); day <= to; day = day.AddDays(1))
{
register += perDay;
readings.Add((Midnight(day.Year, day.Month, day.Day), register));
}
await ReadingsAsync(meter, [.. readings]);
return meter;
}
public async Task<int> VirtualAsync(short type, string expression, QuantityKind kind, string unit, VirtualCostRule rule, string meta = "{}")
{
meta = VirtualDefinitionJson.Write(meta, new VirtualDefinition(expression, kind, unit, rule));
var meter = await MeterAsync(type, MeterMode.Virtual, unit, meta: meta);
await RecomputeAsync(meter);
return meter;
}
public async Task LinkAsync(int from, int to)
{
await using var db = fx.CreateContext();
db.MeterLinks.Add(new MeterLink { FromMeterId = from, ToMeterId = to });
await db.SaveChangesAsync();
}
public async Task<int> TariffAsync(
TariffScope scope, int? scopeId, TariffComponent component, double value, string unit, DateOnly from, DateOnly? to = null)
{
await using var db = fx.CreateContext();
var tariff = new Tariff
{
ScopeType = scope,
ScopeId = scopeId,
Component = component,
Value = value,
Unit = unit,
ValidFrom = from,
ValidTo = to,
};
db.Tariffs.Add(tariff);
await db.SaveChangesAsync();
_tariffs.Add(tariff.Id);
return tariff.Id;
}
public Task<int> TypePriceAsync(short type, double value, DateOnly from, string unit = "EUR/kWh", DateOnly? to = null) =>
TariffAsync(TariffScope.EnergyType, type, TariffComponent.UnitPrice, value, unit, from, to);
public Task<int> MeterPriceAsync(int meter, double value, DateOnly from, string unit = "EUR/kWh") =>
TariffAsync(TariffScope.Meter, meter, TariffComponent.UnitPrice, value, unit, from);
public async Task<int> ManualCostAsync(DateOnly start, double amount, int? meterId = null, int? categoryId = null, string currency = "EUR")
{
await using var db = fx.CreateContext();
var cost = new ManualCost
{
MeterId = meterId,
CategoryId = categoryId,
PeriodStart = start,
PeriodEnd = start.AddMonths(1).AddDays(-1),
Amount = amount,
Currency = currency,
};
db.ManualCosts.Add(cost);
await db.SaveChangesAsync();
_manualCosts.Add(cost.Id);
return cost.Id;
}
public async Task<int> CategoryAsync(string name, int sort, int[]? meters = null, short[]? types = null)
{
await using var db = fx.CreateContext();
var category = new CostCategory { Name = name, Sort = sort };
foreach (var meter in meters ?? [])
{
category.Members.Add(new CostCategoryMember { MeterId = meter });
}
foreach (var type in types ?? [])
{
category.Members.Add(new CostCategoryMember { EnergyTypeId = type });
}
db.CostCategories.Add(category);
await db.SaveChangesAsync();
_categories.Add(category.Id);
return category.Id;
}
public async Task ReadingsAsync(int meterId, params (DateTimeOffset Time, double Value)[] readings)
{
await using (var db = fx.CreateContext())
{
db.Readings.AddRange(readings.Select(r => new Reading
{
MeterId = meterId,
Time = r.Time.ToUniversalTime(),
Value = r.Value,
Quality = ReadingQuality.Manual,
}));
await db.SaveChangesAsync();
}
await RecomputeAsync(meterId);
}
public async Task RecomputeAsync(params int[] meterIds)
{
await using var db = fx.CreateContext();
await using var tx = await db.Database.BeginTransactionAsync();
foreach (var id in meterIds)
{
await Normalization(db).RecomputeMeterAsync(id, null);
}
await db.SaveChangesAsync();
await tx.CommitAsync();
}
public static NormalizationService Normalization(MeterVaultDbContext db) =>
new(db, NormalizationEngine.CreateDefault(),
Microsoft.Extensions.Options.Options.Create(new MeterVaultOptions { TimeZone = BerlinId }),
new FixedTimeProvider(Now));
public async ValueTask DisposeAsync()
{
await using var db = fx.CreateContext();
var ids = _meters.ToArray();
await db.ManualCosts.Where(c => _manualCosts.Contains(c.Id)).ExecuteDeleteAsync();
await db.CostCategories.Where(c => _categories.Contains(c.Id)).ExecuteDeleteAsync();
await db.Tariffs.Where(t => _tariffs.Contains(t.Id)).ExecuteDeleteAsync();
await db.MeterLinks.Where(l => ids.Contains(l.FromMeterId) || ids.Contains(l.ToMeterId)).ExecuteDeleteAsync();
await db.Consumption.Where(c => ids.Contains(c.MeterId)).ExecuteDeleteAsync();
await db.Readings.Where(r => ids.Contains(r.MeterId)).ExecuteDeleteAsync();
await db.MeterEvents.Where(e => ids.Contains(e.MeterId)).ExecuteDeleteAsync();
await db.Meters.Where(m => ids.Contains(m.Id)).ExecuteDeleteAsync();
var types = _types.ToArray();
await db.EnergyTypes.Where(t => types.Contains(t.Id)).ExecuteDeleteAsync();
}
}
/// <summary>Assertions on cost figures.</summary>
internal static class CostAssert
{
public static void Cost(double expected, CostAmount amount, int precision = 6)
{
Assert.NotNull(amount.Cost);
Assert.Equal(expected, amount.Cost!.Value, precision);
}
/// <summary>Priced, with a value, and nothing unavailable in it (not-priced components may have been left out).</summary>
public static void Priced(double expected, CostAmount amount, double tolerance = 1e-6)
{
Assert.Equal(CostStatus.Priced, amount.Status);
Assert.NotNull(amount.Cost);
Assert.InRange(amount.Cost!.Value, expected - tolerance, expected + tolerance);
Assert.DoesNotContain(amount.MissingPrices, m => m.Reason is CostStatus.PriceGap or CostStatus.UnitMismatch);
}
}
@@ -0,0 +1,246 @@
using MeterVault.Core.Analysis;
using MeterVault.Core.Analysis.Costing;
using MeterVault.Core.Domain;
using MeterVault.Infrastructure.Analysis;
using MeterVault.Infrastructure.Costing;
using MeterVault.Infrastructure.Dashboard;
using MeterVault.Infrastructure.Import;
using MeterVault.Infrastructure.Options;
using MeterVault.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using static MeterVault.Integration.Tests.Costing.CostSandbox;
using static MeterVault.Integration.Tests.Reconciliation.ReconciliationSupport;
namespace MeterVault.Integration.Tests.Costing;
/// <summary>
/// The services behind the current pages, rerouted through the analysis reader and the cost engine: the overview's
/// KPIs, breakdown, difference and trend, and the energy page's cost. They keep their
/// signatures and show the corrected bill (D-34 D-42) on the frozen clock of <see cref="CostSandbox.Now"/>.
/// </summary>
/// <remarks>
/// The overview reads the whole instance, so every test starts from — and leaves — an instance
/// without meters, tariffs or manual costs (like <see cref="SeededBillTests"/>).
/// </remarks>
[Collection("Timescale")]
public sealed class DashboardServicesTests(TimescaleFixture fx) : IAsyncLifetime
{
private const int KostenTotal = 2;
private const int KostenStrom = 4;
public async Task InitializeAsync()
{
await using var db = fx.CreateContext();
await ClearDataAsync(db);
}
public async Task DisposeAsync()
{
await using var db = fx.CreateContext();
await ClearDataAsync(db);
}
[Fact]
public async Task The_seeded_overview_follows_the_bill()
{
// D-44 through the legacy services: "this year" is the sheet's 2026 (the data ends in May), "last year" its 2025,
// the latest month with data is May 2026, and the trend, the breakdown and the energy page all add up to the bill.
await LoadReferenceDataAsync();
var (costs, dashboard) = Services();
var sheet = ReadRows(Costs);
var monthly = OracleByMonth(sheet, dateColumn: 0, valueColumn: KostenTotal, firstDataRow: 1);
var summary = await dashboard.GetSummaryAsync(Now);
Assert.Equal(D(2026, 9, 19), summary.AsOf);
Assert.InRange(summary.Year.Current, 2940.19 - 0.02, 2940.19 + 0.02);
Assert.InRange(summary.Year.Previous, 7907.64 - 0.02, 7907.64 + 0.02);
Assert.True(summary.Year.DeltaPercentApplicable);
Assert.Equal((summary.Year.Current - summary.Year.Previous) / summary.Year.Previous * 100, summary.Year.DeltaPercent, 6);
// September and August 2026 have nothing to price: a zero against a zero, with no percentage.
Assert.Equal((0d, 0d), (summary.Month.Current, summary.Month.Previous));
Assert.False(summary.Month.DeltaPercentApplicable);
Assert.Equal(new LatestMonthWithData(D(2026, 5, 1), LatestPeriodBasis.Both), summary.LatestMonth);
Assert.InRange(summary.LatestMonthCost, monthly[D(2026, 5, 1)] - 0.02, monthly[D(2026, 5, 1)] + 0.02);
// The trend is the bill month by month, manual costs included (A09): each month is the sheet's Kosten.
var trend = await dashboard.GetMonthlyTrendAsync(D(2025, 1, 1), D(2026, 1, 1));
Assert.Equal(12, trend.Count);
AssertReconciles(trend.ToDictionary(p => p.Period, p => p.Cost), monthly, 0.02, "trend", minMatches: 12);
Assert.InRange(trend.Sum(p => p.Cost), 7907.64 - 0.02, 7907.64 + 0.02);
// The breakdown is the bill's composition: Strom (Netz × price), Wasser, Heizung — and nothing else priced.
var breakdown = await dashboard.GetCategoryBreakdownAsync(D(2025, 1, 1), D(2026, 1, 1));
Assert.Equal(["Heizung", "Strom", "Wasser"], breakdown.Select(s => s.Name).Order());
Assert.All(breakdown, s => Assert.Equal(CompositionSliceKind.Category, s.Kind));
Assert.InRange(breakdown.Sum(s => s.Cost), 7907.64 - 0.02, 7907.64 + 0.02);
// The energy page's cost is the type's bill, not every electricity meter summed (A04).
await using var db = fx.CreateContext();
var electricity = await db.EnergyTypes.Where(t => t.Key == "electricity").Select(t => t.Id).FirstAsync();
var strom = await costs.GetEnergyTypeCostAsync(electricity, Midnight(2025, 1, 1), Midnight(2026, 1, 1));
var stromSheet = OracleByMonth(sheet, 0, KostenStrom, 1).Where(m => m.Key.Year == 2025).Sum(m => m.Value);
Assert.Equal(CostStatus.Priced, strom.Status);
Assert.InRange(strom.Cost!.Value, stromSheet - 0.02, stromSheet + 0.02);
Assert.Equal(breakdown.Single(s => s.Name == "Strom").Cost, strom.Cost!.Value, 6);
}
[Fact]
public async Task The_breakdown_is_the_bill_s_composition_and_the_trend_adds_up_to_it()
{
await using var box = new CostSandbox(fx);
var (t1, t2) = (await box.TypeAsync(), await box.TypeAsync());
var a = await box.MonthlyAsync(t1, MeterMode.CumulativeCounter, D(2025, 1, 1), [.. Enumerable.Repeat(100d, 20)]);
await box.MonthlyAsync(t2, MeterMode.CumulativeCounter, D(2025, 1, 1), [.. Enumerable.Repeat(50d, 20)]);
await box.TypePriceAsync(t1, 0.10, D(2025, 1, 1));
await box.TypePriceAsync(t2, 0.20, D(2025, 1, 1));
await box.TariffAsync(TariffScope.Global, null, TariffComponent.BasePrice, 5, "EUR/month", D(2025, 1, 1));
var category = await box.CategoryAsync($"A {Guid.NewGuid():N}", 100, meters: [a]);
await box.ManualCostAsync(D(2026, 3, 10), 7);
var (_, dashboard) = Services();
// This year to now (19 September): a and b for January to August (their data ends on 1 September), the global
// standing charge for every day up to today, and the manual cost once.
var standing = (8 * 5) + (19 * 5 / 30d);
var breakdown = await dashboard.GetCategoryBreakdownAsync(D(2026, 1, 1), D(2026, 10, 19));
Assert.Equal(
[(CompositionSliceKind.Uncategorized, (int?)null, 80 + 7d), (CompositionSliceKind.Category, category, 80d), (CompositionSliceKind.StandingCharge, null, Math.Round(standing, 6))],
breakdown.Select(s => (s.Kind, s.CategoryId, Math.Round(s.Cost, 6))));
Assert.Equal(TariffScope.Global, breakdown[2].StandingCharge!.Scope);
Assert.Equal(string.Empty, breakdown[0].Name);
var summary = await dashboard.GetSummaryAsync(Now);
Assert.Equal(summary.Year.Current, breakdown.Sum(s => s.Cost), 6);
Assert.Equal(12 * 25d, summary.Year.Previous, 6);
// The trend: 2024 lies before both meters' install dates, so the bill of each of its months is a known zero (D-24)
// — a point at 0, not a gap. The months of this year add up to the year.
var trend = await dashboard.GetMonthlyTrendAsync(D(2024, 1, 1), D(2026, 10, 19));
Assert.Equal(D(2024, 1, 1), trend[0].Period);
Assert.Equal(33, trend.Count);
Assert.All(trend.Where(p => p.Period.Year == 2024), p => Assert.Equal(0, p.Cost));
Assert.Equal(25, trend.Single(p => p.Period == D(2025, 1, 1)).Cost, 6);
Assert.Equal(32, trend.Single(p => p.Period == D(2026, 3, 1)).Cost, 6);
Assert.Equal(19 * 5 / 30d, trend[^1].Cost, 6);
Assert.Equal(summary.Year.Current, trend.Where(p => p.Period.Year == 2026).Sum(p => p.Cost), 6);
}
[Fact]
public async Task A_month_nothing_was_measured_in_is_not_a_point_on_the_trend()
{
// A meter without an install date is unknown before its first reading, not zero; its type's standing charge only
// starts with its service. Those months are no points — not the known 0 the engine gives a charge not yet due.
await using var box = new CostSandbox(fx);
var type = await box.TypeAsync();
var meter = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh");
await box.ReadingsAsync(
meter, (new DateTimeOffset(2026, 2, 1, 8, 0, 0, TimeSpan.FromHours(1)), 0), (Midnight(2026, 3, 1), 100), (Midnight(2026, 4, 1), 250));
await box.TypePriceAsync(type, 0.10, D(2025, 1, 1));
await box.TariffAsync(TariffScope.EnergyType, type, TariffComponent.BasePrice, 5, "EUR/month", D(2025, 1, 1));
var (_, dashboard) = Services();
var trend = await dashboard.GetMonthlyTrendAsync(D(2025, 6, 1), D(2026, 5, 1));
// February: 100 kWh and the charge from the first data day; March: 150 kWh and the charge; April: the charge alone
// (the service runs on through a reading gap, D-40).
Assert.Equal(
[(D(2026, 2, 1), 15d), (D(2026, 3, 1), 20d), (D(2026, 4, 1), 5d)],
trend.Select(p => (p.Period, Math.Round(p.Cost, 6))));
}
[Fact]
public async Task The_difference_view_compares_the_same_elapsed_part_of_last_year()
{
// 10 kWh a day in 2025, 12 in 2026. This year to 19 September 14:37 is set against 1 January 19 September 14:37
// of 2025 (D-06), not against whole months or the whole year: 261 days each.
await using var box = new CostSandbox(fx);
var type = await box.TypeAsync();
var meter = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", installedAt: D(2025, 1, 1));
var readings = new List<(DateTimeOffset, double)>();
var register = 0d;
for (var day = D(2025, 1, 1); day < D(2026, 9, 19); day = day.AddDays(1))
{
register += day.Year == 2025 ? 10 : 12;
var next = day.AddDays(1);
readings.Add((Midnight(next.Year, next.Month, next.Day), register));
}
await box.ReadingsAsync(meter, [.. readings]);
await box.TypePriceAsync(type, 0.10, D(2025, 1, 1));
var category = await box.CategoryAsync($"D {Guid.NewGuid():N}", 100, meters: [meter]);
var (_, dashboard) = Services();
var rows = await dashboard.GetCategoryDifferenceAsync(D(2026, 1, 1), D(2025, 1, 1), D(2026, 10, 19));
var row = Assert.Single(rows);
Assert.Equal(category, row.CategoryId);
Assert.Equal(261 * 12 * 0.10, row.Current, 6);
Assert.Equal(261 * 10 * 0.10, row.Previous, 6);
Assert.True(row.DeltaPercentApplicable);
Assert.Equal(20, row.DeltaPercent, 6);
}
[Fact]
public async Task An_energy_type_costs_its_billed_meters_and_a_meter_its_own_rule()
{
// A04: the energy page summed every meter of the type — the grid, the house behind it and a subsection of the
// house. The type's bill is the grid import (D-34); each meter's own cost stays available as a view.
await using var box = new CostSandbox(fx);
var type = await box.TypeAsync();
var grid = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2025, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridImport));
var house = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2025, 1, 1), MeterMeta.WithRole("{}", MeterRoles.TotalLoad));
var car = await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2025, 1, 1), [.. Enumerable.Repeat(50d, 12)]);
var pv = await box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2025, 1, 1), [.. Enumerable.Repeat(250d, 12)]);
await box.MonthlyReadingsAsync(grid, D(2025, 1, 1), [.. Enumerable.Repeat(100d, 12)]);
await box.MonthlyReadingsAsync(house, D(2025, 1, 1), [.. Enumerable.Repeat(300d, 12)]);
await box.LinkAsync(house, car);
await box.TypePriceAsync(type, 0.10, D(2025, 1, 1));
var (costs, _) = Services();
var bill = await costs.GetEnergyTypeCostAsync(type, Midnight(2025, 1, 1), Midnight(2026, 1, 1));
Assert.Equal(1200 * 0.10, bill.Cost!.Value, 6);
var houseCosts = await costs.GetMeterCostsAsync(house, Midnight(2025, 1, 1), Midnight(2026, 1, 1));
Assert.Equal(12, houseCosts.Count);
Assert.All(houseCosts, c => Assert.Equal((300d, 30d), (c.Consumption, Math.Round(c.Cost, 6))));
// A generation meter reports generation, and is not costed.
var generation = await costs.GetMeterCostsAsync(pv, Midnight(2025, 1, 1), Midnight(2026, 1, 1));
Assert.All(generation, c => Assert.Equal((0d, 250d, 0d, QuantityKind.Generation), (c.Consumption, c.Generation, c.Cost, c.Kind)));
}
private (CostService Costs, DashboardService Dashboard) Services()
{
var clock = new FixedTimeProvider(Now);
var costs = new CostService(fx, Options(), clock);
return (costs, new DashboardService(fx, costs, clock));
}
private static Microsoft.Extensions.Options.IOptions<MeterVaultOptions> Options() =>
Microsoft.Extensions.Options.Options.Create(new MeterVaultOptions { TimeZone = BerlinId, Currency = "EUR" });
private async Task LoadReferenceDataAsync()
{
await using var db = fx.CreateContext();
var importer = new ReferenceDataImporter(db, new ImportService(db, Normalization(db)), new CsvImporter());
await importer.LoadAsync(Path.Combine(AppContext.BaseDirectory, "fixtures"));
}
private static async Task ClearDataAsync(MeterVaultDbContext db)
{
await db.MeterLinks.ExecuteDeleteAsync();
await db.Consumption.ExecuteDeleteAsync();
await db.Readings.ExecuteDeleteAsync();
await db.MeterEvents.ExecuteDeleteAsync();
await db.ManualCosts.ExecuteDeleteAsync();
await db.CostCategoryMembers.ExecuteDeleteAsync();
await db.Tariffs.ExecuteDeleteAsync();
await db.Tanks.ExecuteDeleteAsync();
await db.MeterSources.ExecuteDeleteAsync();
await db.Meters.ExecuteDeleteAsync();
await db.ImportBatches.ExecuteDeleteAsync();
}
}
@@ -0,0 +1,341 @@
using MeterVault.Core.Analysis;
using MeterVault.Core.Analysis.Costing;
using MeterVault.Core.Domain;
using MeterVault.Infrastructure.Analysis;
using MeterVault.Infrastructure.Costing;
using MeterVault.Infrastructure.Import;
using MeterVault.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Xunit.Abstractions;
using static MeterVault.Integration.Tests.Costing.CostSandbox;
using static MeterVault.Integration.Tests.Reconciliation.ReconciliationSupport;
namespace MeterVault.Integration.Tests.Costing;
/// <summary>
/// The whole bill (D-34 D-44): the seeded reference instance against the Kosten sheet's <c>Jahreskosten</c>, the
/// category composition that reconciles with it, standing charges once per scope, and an instance with nothing but
/// manual costs. The portfolio is everything in the database, so every test starts from — and leaves — an instance
/// without meters, tariffs or manual costs (like <see cref="DashboardRenderTests"/>).
/// </summary>
[Collection("Timescale")]
public sealed class SeededBillTests(TimescaleFixture fx, ITestOutputHelper output) : IAsyncLifetime
{
private const int KostenHeizung = 3;
private const int KostenStrom = 4;
private const int KostenWasser = 5;
public async Task InitializeAsync()
{
await using var db = fx.CreateContext();
await ClearDataAsync(db);
}
public async Task DisposeAsync()
{
await using var db = fx.CreateContext();
await ClearDataAsync(db);
}
[Fact]
public async Task The_seeded_yearly_bill_equals_the_sheet_s_Jahreskosten()
{
// D-44: with the tank unpriced and on a clock after the data ends (31 May 2026), the seeded bill is the sheet's
// yearly cost within 2 cents: Strom = Netz × price, water metered, Heizung from the imported manual costs.
await LoadReferenceDataAsync();
var reader = new CostSandbox(fx).Reader();
var sheet = ReadRows(Costs);
await using var db = fx.CreateContext();
var meters = await db.Meters.AsNoTracking().ToDictionaryAsync(m => m.Name, m => m.Id);
var types = await db.EnergyTypes.AsNoTracking().ToDictionaryAsync(t => t.Key, t => (int)t.Id);
var categories = await db.CostCategories.AsNoTracking().ToDictionaryAsync(c => c.Name, c => c.Id);
foreach (var (year, jahreskosten) in new[] { (2022, 421.52), (2025, 7907.64), (2026, 2940.19) })
{
var bill = await reader.ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, Year(year)) { Bucket = BucketSize.Month, IncludeCategories = true });
output.WriteLine(FormattableString.Invariant($"{year}: bill {bill.Total.Cost:F4} (sheet {jahreskosten:F2}), {bill.Total.Status}"));
// The yearly bill, with nothing unavailable in it: the tank is "not priced", an attention item only.
Assert.Equal(CostStatus.Priced, bill.Total.Status);
Assert.InRange(bill.Total.Cost!.Value, jahreskosten - 0.02, jahreskosten + 0.02);
Assert.All(bill.MissingPrices, m => Assert.Equal((CostStatus.NotPriced, (int?)meters["Öltank"]), (m.Reason, m.MeterId)));
Assert.Equal(bill.Total.Cost!.Value, bill.Buckets.Sum(b => b.Cost ?? 0), 6);
// Strom is the grid import alone, priced month by month: the sheet's Kosten = Netz × €/kWh.
var strom = bill.EnergyTypes.Single(t => t.EnergyTypeId == types["electricity"]);
Assert.Equal([meters["Zähler Netz"]], strom.LineMeterIds);
var netz = bill.Lines.Single(l => l.MeterId == meters["Zähler Netz"]);
for (var b = 0; b < bill.Buckets.Count; b++)
{
var month = bill.Plan.Buckets[b].FirstDay;
if (netz.Quantities[b] is { } kWh && netz.Buckets[b].Cost is { } cost)
{
Assert.Equal(kWh * StromPrice(month), cost, 6);
}
}
Assert.InRange(strom.Total.Cost!.Value - SheetSum(sheet, KostenStrom, year), -0.02, 0.02);
var wasser = bill.EnergyTypes.Single(t => t.EnergyTypeId == types["water"]);
Assert.InRange(wasser.Total.Cost!.Value - SheetSum(sheet, KostenWasser, year), -0.02, 0.02);
// Heizung comes from manual costs, each booked once.
var heizung = SheetSum(sheet, KostenHeizung, year);
Assert.InRange((bill.ManualCosts.Total.Cost ?? 0) - heizung, -0.02, 0.02);
Assert.Equal(bill.ManualCosts.Bookings.Count, bill.ManualCosts.Bookings.Select(m => m.ManualCostId).Distinct().Count());
Assert.All(bill.ManualCosts.Bookings, m => Assert.Equal(categories["Heizung"], m.CategoryId));
// The composition — disjoint categories, Uncategorized, standing charges — is the bill (D-42).
var composition = bill.Composition!;
Assert.Equal(bill.Total.Cost!.Value, composition.Total.Cost!.Value, 6);
for (var b = 0; b < bill.Buckets.Count; b++)
{
Assert.Equal(bill.Buckets[b].Cost ?? 0, composition.Buckets[b].Cost ?? 0, 6);
}
Assert.Equal(strom.Total.Cost, Slice(composition, categories["Strom"]).Total.Cost);
Assert.Equal(wasser.Total.Cost, Slice(composition, categories["Wasser"]).Total.Cost);
Assert.Equal(bill.ManualCosts.Total.Cost, Slice(composition, categories["Heizung"]).Total.Cost);
var uncategorized = composition.Slices.Single(s => s.Kind == CompositionSliceKind.Uncategorized);
Assert.Equal([meters["Öltank"]], uncategorized.MeterIds);
Assert.Null(uncategorized.Total.Cost);
Assert.All(composition.Categories, c => Assert.False(c.IsOverlappingView));
Assert.True(composition.DonutAllowed);
}
// Every seeded meter names how its own cost is formed (D-34, D-39).
var rules = new Dictionary<string, (MeterCostRule Rule, bool OnBill)>
{
["Zähler Netz"] = (MeterCostRule.BillLine, true),
["Zähler Haus"] = (MeterCostRule.UnitPriceView, false),
["Zähler Auto"] = (MeterCostRule.UnitPriceView, false),
["Zähler Solar 1"] = (MeterCostRule.None, false),
["Brenner"] = (MeterCostRule.None, false),
["Öltank"] = (MeterCostRule.BillLine, true),
["Summe Solar"] = (MeterCostRule.None, false),
};
foreach (var (name, expected) in rules)
{
var own = await reader.ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(meters[name]), Year(2025)) { Bucket = BucketSize.Month });
Assert.Equal(expected, (own.Meter!.Rule, own.Meter.OnBill));
}
// Summe Solar is generation: never a purchase cost (review R1, A-15) — not 4,750 kWh at 0.36 €.
var summe = await reader.ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(meters["Summe Solar"]), Year(2025)) { Bucket = BucketSize.Month });
Assert.Null(summe.Total.Cost);
Assert.Empty(summe.Lines);
Assert.Equal(MeterNotCostedReason.Generation, summe.Meter!.NotCosted);
var haus = await reader.ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(meters["Zähler Haus"]), Year(2025)) { Bucket = BucketSize.Month });
Assert.Equal(haus.Lines.Single().TotalQuantity!.Value * 0.36, haus.Total.Cost!.Value, 6);
var tank = await reader.ReadAsync(new CostAnalysisRequest(CostScope.ForMeter(meters["Öltank"]), Year(2025)) { Bucket = BucketSize.Month });
Assert.Equal(CostStatus.NotPriced, tank.Total.Status);
// Water, December 2022: 14 m³ × 5,00 € (D-56), through the Wasser category.
var december = await reader.ReadAsync(new CostAnalysisRequest(CostScope.ForCategory(categories["Wasser"]), Month(2022, 12)) { Bucket = BucketSize.Month });
CostAssert.Priced(70.00, december.Total, 0.005);
Assert.Equal([meters["Zähler Wasser"]], december.Category!.Cover.BilledMeterIds);
// 2023 and 2024 differ from the sheet by 3.78 € and 0.46 € (D-44): the sheet multiplies by unrounded prices it
// displays rounded (e.g. May 2023, 414,33 € for a 0,37 €/kWh month). Documented, not tuned away.
foreach (var (year, jahreskosten, difference) in new[] { (2023, 7904.46, 3.78), (2024, 6783.05, 0.46) })
{
var bill = await reader.ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, Year(year)) { Bucket = BucketSize.Month });
output.WriteLine(FormattableString.Invariant($"{year}: bill {bill.Total.Cost:F4} (sheet {jahreskosten:F2})"));
Assert.Equal(CostStatus.Priced, bill.Total.Status);
Assert.InRange(Math.Abs(bill.Total.Cost!.Value - jahreskosten), difference - 0.02, difference + 0.02);
}
// The bucket size never changes the year: months, weeks, the year as one bucket.
var watch = System.Diagnostics.Stopwatch.StartNew();
var monthly = await reader.ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, Year(2025)) { Bucket = BucketSize.Month });
output.WriteLine(FormattableString.Invariant($"portfolio 2025 by month: {watch.ElapsedMilliseconds} ms"));
foreach (var size in new[] { BucketSize.Year, BucketSize.Week })
{
var other = await reader.ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, Year(2025)) { Bucket = size });
Assert.Equal(monthly.Total.Cost!.Value, other.Total.Cost!.Value, 6);
Assert.Equal(CostStatus.Priced, other.Total.Status);
}
// Auto charts the bill by the resolution of what is priced: the monthly sheets, not the unpriced tank.
var auto = await reader.ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, Preset(PeriodPreset.Last24Months)));
Assert.Equal(BucketSize.Month, auto.Plan.Size);
Assert.Equal(24, auto.Buckets.Count);
// The latest period with data is May 2026, from meters and manual costs alike (D-19).
var latest = await reader.GetAvailabilityAsync(CostScope.Portfolio, Now);
Assert.Equal(new LatestPeriod(D(2026, 5, 1), LatestPeriodBasis.Both), latest.Latest);
}
[Fact]
public async Task Standing_charges_and_categories_compose_the_portfolio_bill()
{
await using var box = new CostSandbox(fx);
var (t1, t2, t3) = (await box.TypeAsync(), await box.TypeAsync(), await box.TypeAsync());
var a = await box.MonthlyAsync(t1, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 100, 100);
var b = await box.MonthlyAsync(t2, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 100, 100);
var grid = await box.MeterAsync(t3, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridImport));
var export = await box.MeterAsync(t3, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridExport));
await box.MonthlyReadingsAsync(grid, D(2026, 1, 1), 100, 100, 100);
await box.MonthlyReadingsAsync(export, D(2026, 1, 1), 1000, 1000, 1000);
foreach (var type in new[] { t1, t2, t3 })
{
await box.TypePriceAsync(type, 0.10, D(2026, 1, 1));
}
await box.TariffAsync(TariffScope.EnergyType, t3, TariffComponent.FeedIn, 0.08, "EUR/kWh", D(2026, 1, 1));
await box.TariffAsync(TariffScope.EnergyType, t1, TariffComponent.BasePrice, 3, "EUR/month", D(2026, 1, 1));
await box.TariffAsync(TariffScope.Global, null, TariffComponent.BasePrice, 10, "EUR/month", D(2026, 1, 1));
var viewA = await box.CategoryAsync($"A {Guid.NewGuid():N}", 100, meters: [a]);
var viewA2 = await box.CategoryAsync($"A2 {Guid.NewGuid():N}", 101, meters: [a]);
var typeB = await box.CategoryAsync($"B {Guid.NewGuid():N}", 102, types: [t2]);
var credit = await box.CategoryAsync($"X {Guid.NewGuid():N}", 103, meters: [export]);
var onMeter = await box.ManualCostAsync(D(2026, 2, 1), 25, meterId: b);
var onView = await box.ManualCostAsync(D(2026, 2, 1), 7, categoryId: viewA);
// Two categories that price nothing but share a manual cost (on a generator, never billed) cannot both be
// slices: the cost would be added twice.
var t4 = await box.TypeAsync();
var pv = await box.MonthlyAsync(t4, MeterMode.GenerationCounter, D(2026, 1, 1), 50, 50, 50);
var sharedG1 = await box.CategoryAsync($"G1 {Guid.NewGuid():N}", 104, meters: [pv]);
var sharedG2 = await box.CategoryAsync($"G2 {Guid.NewGuid():N}", 105, meters: [pv]);
var onPv = await box.ManualCostAsync(D(2026, 2, 1), 11, meterId: pv);
var quarter = Custom(D(2026, 1, 1), D(2026, 3, 31));
var bill = await box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, quarter) { Bucket = BucketSize.Month, IncludeCategories = true });
// Lines: a, b, the grid at 0.10 on 300 kWh each; the export credit 3000 × 0.08. Rows: the type's 3 × 3 €, the
// global 3 × 10 € — each once, however many meters are in service (D-40). Manual costs once each (D-41): 25 €
// on b goes with b's type, 7 € on a category with the portfolio.
Assert.Equal(
[(TariffScope.EnergyType, (int?)t1, 9d), (TariffScope.Global, (int?)null, 30d)],
bill.StandingCharges.Select(r => (r.Scope, r.ScopeId, Math.Round(r.Total.Cost!.Value, 6))));
CostAssert.Priced(90 - 240 + 9 + 30 + 25 + 7 + 11, bill.Total);
Assert.Equal([onMeter, onView, onPv], bill.ManualCosts.Bookings.Select(m => m.ManualCostId).Order());
Assert.Equal(D(2026, 1, 1), bill.StandingCharges[1].Service!.FirstDay);
Assert.Equal([39d, 55d, -210d, 11d], bill.EnergyTypes.Select(t => Math.Round(t.Total.Cost!.Value, 6)));
// A type's bill carries its own standing charge, never the global one.
var typeBill = await box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForEnergyType(t1), quarter) { Bucket = BucketSize.Month });
Assert.Equal((TariffScope.EnergyType, (int?)t1), (Assert.Single(typeBill.StandingCharges).Scope, typeBill.StandingCharges[0].ScopeId));
CostAssert.Priced(39, typeBill.Total);
// The composition: B (with b's manual cost) and X are slices, A and A2 share a's line (and t1's charge) and are
// views; a's line and A's manual cost go to Uncategorized with the grid, and the two charges no slice holds are
// rows of their own.
var composition = bill.Composition!;
Assert.Equal(bill.Total.Cost!.Value, composition.Total.Cost!.Value, 6);
Assert.Equal(30 + 25, Slice(composition, typeB).Total.Cost!.Value, 6);
Assert.Equal([onMeter], Slice(composition, typeB).ManualCostIds);
Assert.Equal(-240, Slice(composition, credit).Total.Cost!.Value, 6);
var uncategorized = composition.Slices.Single(s => s.Kind == CompositionSliceKind.Uncategorized);
Assert.Equal([a, grid], uncategorized.MeterIds);
Assert.Equal([onView, onPv], uncategorized.ManualCostIds);
Assert.Equal(60 + 7 + 11, uncategorized.Total.Cost!.Value, 6);
Assert.All(composition.Categories.Where(c => c.CategoryId == sharedG1 || c.CategoryId == sharedG2), c =>
{
Assert.True(c.IsOverlappingView);
Assert.Equal(11, c.Total.Cost!.Value, 6);
});
Assert.Equal([onPv], composition.Overlaps.Single(o => o.CategoryId == sharedG1 && o.OtherCategoryId == sharedG2).SharedManualCostIds);
Assert.Equal(
[(TariffScope.EnergyType, (int?)t1), (TariffScope.Global, (int?)null)],
composition.Slices.Where(s => s.Kind == CompositionSliceKind.StandingCharge).Select(s => (s.StandingCharge!.Scope, s.StandingCharge.ScopeId)));
Assert.DoesNotContain(composition.Slices, s => s.CategoryId == viewA || s.CategoryId == viewA2);
var figureA = composition.Categories.Single(c => c.CategoryId == viewA);
Assert.True(figureA.IsOverlappingView);
Assert.Equal([viewA2], figureA.OverlapsWith);
Assert.Equal(30 + 9 + 7, figureA.Total.Cost!.Value, 6);
var overlap = Assert.Single(composition.Overlaps, o => o.CategoryId == Math.Min(viewA, viewA2) && o.OtherCategoryId == Math.Max(viewA, viewA2));
Assert.Equal([a], overlap.SharedMeterIds);
Assert.Equal([new StandingChargeKey(TariffScope.EnergyType, t1)], overlap.SharedStandingCharges);
Assert.False(composition.Categories.Single(c => c.CategoryId == typeB).IsOverlappingView);
// A credit larger than its charges is a negative slice: signed bars, not a donut (D-42).
Assert.False(composition.DonutAllowed);
// The category on its own reads the same figure as in the composition.
var alone = await box.Reader().ReadAsync(new CostAnalysisRequest(CostScope.ForCategory(viewA), quarter) { Bucket = BucketSize.Month });
Assert.True(alone.Category!.IsOverlappingView);
Assert.Equal(figureA.Total.Cost, alone.Total.Cost);
}
[Fact]
public async Task A_manual_cost_only_instance_agrees_across_overview_trend_categories_and_latest_month()
{
// Brief §11: no meter at all, only manual costs — overview, trend, category breakdown and the latest month agree.
await using var box = new CostSandbox(fx);
var category = await box.CategoryAsync($"Manual {Guid.NewGuid():N}", 100);
var march = await box.ManualCostAsync(D(2026, 3, 5), 100, categoryId: category);
var loose = await box.ManualCostAsync(D(2026, 3, 20), 40);
var may = await box.ManualCostAsync(D(2026, 5, 10), 60, categoryId: category);
var reader = box.Reader();
var latest = await reader.GetAvailabilityAsync(CostScope.Portfolio, Now);
Assert.Equal(new LatestPeriod(D(2026, 5, 1), LatestPeriodBasis.Manual), latest.Latest);
var overview = await reader.ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, Month(2026, 5)));
CostAssert.Priced(60, overview.Total);
Assert.Equal(latest.Latest, overview.Availability.Latest);
Assert.Empty(overview.Lines);
var trend = await reader.ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, Preset(PeriodPreset.Last12Months)) { Bucket = BucketSize.Month, IncludeCategories = true });
Assert.Equal(12, trend.Buckets.Count);
var byMonth = trend.Plan.Buckets.Select((b, i) => (b.FirstDay, trend.Buckets[i].Cost)).ToDictionary(x => x.FirstDay, x => x.Cost);
Assert.Equal(140, byMonth[D(2026, 3, 1)]);
Assert.Equal(overview.Total.Cost, byMonth[D(2026, 5, 1)]);
Assert.Null(byMonth[D(2026, 4, 1)]);
CostAssert.Priced(200, trend.Total);
var composition = trend.Composition!;
Assert.Equal(160, Slice(composition, category).Total.Cost);
Assert.Equal([march, may], Slice(composition, category).ManualCostIds);
var uncategorized = composition.Slices.Single(s => s.Kind == CompositionSliceKind.Uncategorized);
Assert.Equal([loose], uncategorized.ManualCostIds);
Assert.Equal(40, uncategorized.Total.Cost);
Assert.Equal(200, composition.Total.Cost);
var alone = await reader.ReadAsync(new CostAnalysisRequest(CostScope.ForCategory(category), Preset(PeriodPreset.Last12Months)) { Bucket = BucketSize.Month });
CostAssert.Priced(160, alone.Total);
}
private async Task LoadReferenceDataAsync()
{
await using var db = fx.CreateContext();
var importer = new ReferenceDataImporter(db, new ImportService(db, Normalization(db)), new CsvImporter());
await importer.LoadAsync(Path.Combine(AppContext.BaseDirectory, "fixtures"));
}
/// <summary>The seeded electricity price on the 15th of a month (ReferenceDataImporter).</summary>
private static double StromPrice(DateOnly month) => month switch
{
_ when month >= D(2026, 1, 1) => 0.27,
_ when month >= D(2025, 1, 1) => 0.36,
_ when month >= D(2023, 11, 1) => 0.27,
_ when month >= D(2023, 5, 1) => 0.37,
_ when month >= D(2023, 1, 1) => 0.44,
_ => 0.16,
};
private static double SheetSum(IReadOnlyList<string[]> rows, int column, int year) =>
OracleByMonth(rows, dateColumn: 0, valueColumn: column, firstDataRow: 1).Where(m => m.Key.Year == year).Sum(m => m.Value);
private static CompositionSlice Slice(CategoryComposition composition, int categoryId) =>
composition.Slices.Single(s => s.Kind == CompositionSliceKind.Category && s.CategoryId == categoryId);
private static async Task ClearDataAsync(MeterVaultDbContext db)
{
await db.MeterLinks.ExecuteDeleteAsync();
await db.Consumption.ExecuteDeleteAsync();
await db.Readings.ExecuteDeleteAsync();
await db.MeterEvents.ExecuteDeleteAsync();
await db.ManualCosts.ExecuteDeleteAsync();
await db.CostCategoryMembers.ExecuteDeleteAsync();
await db.Tariffs.ExecuteDeleteAsync();
await db.Tanks.ExecuteDeleteAsync();
await db.MeterSources.ExecuteDeleteAsync();
await db.Meters.ExecuteDeleteAsync();
await db.ImportBatches.ExecuteDeleteAsync();
}
}