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,101 @@
using MeterVault.Core.Analysis;
using MeterVault.Infrastructure.Dashboard;
namespace MeterVault.Integration.Tests.Specialized;
/// <summary>
/// The pure arithmetic behind the Solar view's derived figures (brief §4.3, A05): an input without data makes the bucket
/// unknown while an observed zero is a valid input; partial stays partial; a total never subtracts two totals over
/// different stretches of time; units are never mixed (D-20); a change needs the same buckets on both sides (D-07).
/// </summary>
public sealed class SolarFiguresTests
{
private static BucketValue Ok(double value) => BucketValue.Available(value, Provenance.Imported);
private static BucketValue Part(double value) => new(value, BucketStatus.Partial, Provenance.Imported, ValueIssue.PartialCoverage);
private static readonly BucketValue None = BucketValue.Missing();
[Fact]
public void An_observed_zero_is_an_input_and_a_missing_value_is_not()
{
var zero = SolarService.Combine(Ok(300), Ok(0), -1);
Assert.Equal((300d, BucketStatus.Available), (zero.Value, zero.Status));
Assert.True(zero.Provenance.HasFlag(Provenance.Derived));
var missing = SolarService.Combine(Ok(300), None, -1);
Assert.Equal(((double?)null, BucketStatus.Missing, ValueIssue.MissingSource), (missing.Value, missing.Status, missing.Issue));
var neither = SolarService.Combine(None, None, -1);
Assert.Equal((BucketStatus.Missing, ValueIssue.NoCoverage), (neither.Status, neither.Issue));
var partial = SolarService.Combine(Part(300), Ok(100), -1);
Assert.Equal((200d, BucketStatus.Partial), (partial.Value, partial.Status));
// Being prepared or too coarse decides the status, even beside a missing input.
var pending = SolarService.Combine(None, new BucketValue(null, BucketStatus.Pending, Provenance.None, ValueIssue.AnalysisPending), -1);
Assert.Equal(BucketStatus.Pending, pending.Status);
var coarse = SolarService.Combine(new BucketValue(null, BucketStatus.Unresolved, Provenance.Imported, ValueIssue.CoarseResolution), Ok(1), 1);
Assert.Equal((BucketStatus.Unresolved, ValueIssue.CoarseResolution), (coarse.Status, coarse.Issue));
}
[Fact]
public void A_total_is_taken_over_the_buckets_both_inputs_know_unless_both_are_complete()
{
// Load known February and March (700), import known January to March (800): the difference of the totals would
// be 100; over the months both know it is 300, partial.
List<BucketValue> load = [None, Ok(400), Ok(300)];
List<BucketValue> import = [Ok(400), Ok(300), Ok(100)];
var a = new SolarFigure(SolarBasis.Measured, "kWh", load, Part(700)) { InputUnits = ["kWh"] };
var b = new SolarFigure(SolarBasis.Measured, "kWh", import, Ok(800)) { InputUnits = ["kWh"] };
var self = SolarService.Derive(SolarBasis.LoadMinusImport, a, b, -1);
Assert.Equal([null, 100d, 200d], self.Values.Select(v => v.Value));
Assert.Equal((300d, BucketStatus.Partial), (self.Total.Value, self.Total.Status));
// Both complete: the totals decide (a monthly import resolves the period even where it does not resolve days).
var whole = SolarService.CombineTotal(Ok(700), Ok(400), -1, [new BucketValue(null, BucketStatus.Unresolved, Provenance.None)]);
Assert.Equal((300d, BucketStatus.Available), (whole.Value, whole.Status));
}
[Fact]
public void Figures_in_different_units_are_never_combined()
{
var generation = new SolarFigure(SolarBasis.Measured, "Wh", [Ok(5000)], Ok(5000)) { InputUnits = ["Wh"] };
var export = new SolarFigure(SolarBasis.Measured, "kWh", [Ok(1)], Ok(1)) { InputUnits = ["kWh"] };
var self = SolarService.Derive(SolarBasis.GenerationMinusExport, generation, export, -1);
Assert.True(self.UnitsDiffer);
Assert.Equal(["Wh", "kWh"], self.InputUnits);
Assert.Equal(((double?)null, BucketStatus.Invalid), (self.Total.Value, self.Total.Status));
Assert.Equal(BucketStatus.Invalid, SolarService.Share(self, generation).Status);
Assert.Equal(BucketStatus.Invalid, SolarService.Share(export, generation).Status);
}
[Fact]
public void A_share_needs_a_positive_base_and_says_when_it_is_partial()
{
var part = new SolarFigure(SolarBasis.Measured, "kWh", [Ok(30), None], Part(30)) { InputUnits = ["kWh"] };
var whole = new SolarFigure(SolarBasis.Measured, "kWh", [Ok(60), Ok(40)], Ok(100)) { InputUnits = ["kWh"] };
var share = SolarService.Share(part, whole);
Assert.Equal((50d, BucketStatus.Partial), (share.Value, share.Status));
var zero = new SolarFigure(SolarBasis.Measured, "kWh", [Ok(0)], Ok(0)) { InputUnits = ["kWh"] };
Assert.Equal(BucketStatus.Invalid, SolarService.Share(zero, zero).Status);
}
[Fact]
public void A_change_compares_the_same_complete_buckets_on_both_sides()
{
// Complete totals: between them. Otherwise only the pairs complete on both sides (here the first).
Assert.Equal(20, SolarService.MatchedChange(Ok(120), [Ok(120)], Ok(100), [Ok(100)]).Absolute);
var matched = SolarService.MatchedChange(Part(150), [Ok(120), Part(30)], Ok(200), [Ok(100), Ok(100)]);
Assert.Equal((20d, 20d), (matched.Absolute, matched.Percent));
Assert.False(SolarService.MatchedChange(Part(30), [None, Part(30)], Ok(200), [Ok(100), Ok(100)]).IsAvailable);
Assert.False(SolarService.MatchedChange(Ok(1), [Ok(1)], null, null).IsAvailable);
}
}