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,253 @@
@* The bill's composition (brief §7.1 item 5, D-42): the disjoint cost categories, Uncategorized and the standing
charges no category holds — rows that add up to the bill, manual costs in them exactly once. A donut only when every
slice is ≥ 0 (DonutAllowed); a credit larger than its charges is drawn as signed bars around zero instead. Categories
that overlap another (a view on the bill) are listed apart, as views, and never added up. Setting up categories is
never required: without any, the whole bill is Uncategorized, and a hint says how to split it. *@
<MudPaper Outlined="true" Elevation="0" Class="pa-4 mv-ov-panel">
<div class="mv-ov-panel__head">
<h2 class="mud-typography mud-typography-h6 mv-ov-panel__title">@S.Overview_Composition</h2>
</div>
@if (_rows.Count == 0)
{
<MudText Typo="Typo.body2" Class="mv-muted">@S.Overview_CompositionEmpty</MudText>
}
else
{
@if (_donut.Count > 1)
{
<OverviewDonut Slices="_donut" Currency="@View.Currency" Title="@S.Overview_Composition" />
}
else if (_signed)
{
<MudText Typo="Typo.caption" Class="mv-muted d-block mb-1">@S.Overview_SignedBarsNote</MudText>
}
<MudTable T="Row" Items="_rows" Dense="true" Hover="true" Elevation="0" Breakpoint="Breakpoint.Sm" Class="mv-ov-composition"
RowClassFunc="@((row, _) => row.IsTotal ? "mv-ov-total" : string.Empty)">
<HeaderContent>
<MudTh>@S.Dashboard_ColCategory</MudTh>
@if (_signed)
{
<MudTh><span class="mv-sr-only">@S.Overview_SignedBars</span></MudTh>
}
<MudTh Class="mv-num">@S.AnalysisTable_Cost</MudTh>
@if (!_signed)
{
<MudTh Class="mv-num">@S.Overview_Share</MudTh>
}
</HeaderContent>
<RowTemplate Context="row">
<MudTd DataLabel="@S.Dashboard_ColCategory">
<span>
<span class="mv-ov-swatch" style="@SwatchStyle(row)" aria-hidden="true"></span>
@if (row.Href is not null)
{
<MudLink Href="@row.Href" Typo="Typo.body2">@row.Name</MudLink>
}
else
{
<span>@row.Name</span>
}
</span>
</MudTd>
@if (_signed)
{
<MudTd DataLabel="@S.Overview_SignedBars" Class="mv-ov-bars-cell">
@if (!row.IsTotal)
{
<span class="mv-ov-bars" aria-hidden="true">
<span class="mv-ov-bars__neg"><span class="mv-ov-bars__bar" style="@BarStyle(row.Amount, negative: true)"></span></span>
<span class="mv-ov-bars__pos"><span class="mv-ov-bars__bar" style="@BarStyle(row.Amount, negative: false)"></span></span>
</span>
}
</MudTd>
}
<MudTd DataLabel="@S.AnalysisTable_Cost" Class="@(row.Status.IsKnown ? "mv-num" : "mv-num mv-unknown")">
@if (row.Status.IsKnown)
{
<span title="@row.Status.Detail">
<span class="mv-ov-amount">@Format.Money(row.Amount, View.Currency)</span>
@if (!row.Status.IsComplete)
{
<span class="mv-cell-secondary d-block">@row.Chip</span>
}
</span>
}
else
{
<span title="@row.Status.Detail">@row.Status.Status</span>
}
</MudTd>
@if (!_signed)
{
<MudTd DataLabel="@S.Overview_Share" Class="mv-num">@(row.Share is { } share ? Format.Number(share * 100, 1) + " %" : row.IsTotal ? string.Empty : Format.Unknown)</MudTd>
}
</RowTemplate>
</MudTable>
}
@if (_views.Count > 0)
{
<h3 class="mud-typography mud-typography-subtitle2 mt-4 mb-1">@S.Overview_Views</h3>
<MudText Typo="Typo.caption" Class="mv-muted d-block mb-1">@S.Overview_ViewsNote</MudText>
<div class="mv-table-scroll" role="region" aria-label="@S.Overview_Views" tabindex="0">
<MudSimpleTable Dense="true" Class="mv-ov-composition">
<tbody>
@foreach (var view in _views)
{
<tr>
<th scope="row" class="mv-row-label">
<MudLink Href="@view.Href" Typo="Typo.body2">@view.Name</MudLink>
@if (view.Overlaps is not null)
{
<div class="mv-cell-secondary">@view.Overlaps</div>
}
</th>
<td class="mv-num @(view.Status.IsKnown ? null : "mv-unknown")">
@(view.Status.IsKnown ? Format.Money(view.Amount, View.Currency) : view.Status.Status)
</td>
</tr>
}
</tbody>
</MudSimpleTable>
</div>
}
@if (View.Data.Setup?.FirstGap is CostSetupGap.NoCategories or CostSetupGap.NoMembers)
{
<MudText Typo="Typo.body2" Class="mv-muted mt-3">
@(View.Data.Setup.FirstGap == CostSetupGap.NoCategories ? S.Dashboard_SetupNoCategories : S.Dashboard_SetupNoMembers)
<MudLink Href="/admin/categories" Typo="Typo.body2">@S.Nav_CostCategories</MudLink>
</MudText>
}
</MudPaper>
@code {
/// <summary>The committed Overview.</summary>
[Parameter, EditorRequired]
public OverviewView View { get; set; } = null!;
private sealed record Row(string Name, string? Href, string? Color, double? Amount, FigureStatus Status, double? Share)
{
/// <summary>The bill's total, the last line.</summary>
public bool IsTotal { get; init; }
/// <summary>What qualifies a known amount: the quantities' state for a priced one, else its price coverage.</summary>
public string Chip { get; init; } = Status.Status;
/// <summary>The slice's place among the donut's slices, for its palette colour.</summary>
public int? DonutIndex { get; set; }
}
private sealed record ViewRow(string Name, string Href, double? Amount, FigureStatus Status, string? Overlaps);
private CategoryComposition? _composition;
private List<Row> _rows = [];
private List<ViewRow> _views = [];
private IReadOnlyList<OverviewDonutSlice> _donut = [];
private bool _signed;
private double _maxAbs;
private object? _builtFrom;
protected override void OnParametersSet()
{
// Built once per committed value: the donut re-keys only for a new list.
if (ReferenceEquals(_builtFrom, View))
{
return;
}
_builtFrom = View;
_composition = View.Data.Cost.Composition;
_rows = [];
_views = [];
_donut = [];
if (_composition is not { } composition)
{
return;
}
var data = View.Data;
_signed = !composition.DonutAllowed;
var positive = composition.Slices.Sum(s => s.Total.Cost is { } c && c > 0 ? c : 0);
foreach (var slice in composition.Slices)
{
var status = FigureText.Of(slice.Total);
var category = slice.CategoryId is { } id ? composition.Categories.FirstOrDefault(c => c.CategoryId == id) : null;
// A slice with nothing in it (a category without members) is not a row; one that could not be priced is, and
// so is a category whose members price nothing (calculated views, generation, A-22): it says so.
if (!status.IsKnown && slice.Total.Status == CostStatus.Priced)
{
if (category?.Cover is not { CoverMeterIds.Count: 0, AnalysisOnlyMeterIds.Count: > 0 })
{
continue;
}
status = new FigureStatus(false, false, true, S.Overview_CategoryPricesNothing, S.Overview_CategoryPricesNothingDetail, string.Empty);
}
var href = slice.CategoryId is { } categoryId ? AnalysisLinks.Analysis(QueryScope.ForCategory(categoryId), AnalysisMetric.Cost, View.Query) : null;
var amount = status.IsKnown ? slice.Total.Cost : null;
double? share = !_signed && amount is { } a && positive > CategoryComposition.DonutTolerance ? a / positive : null;
_rows.Add(new Row(OverviewText.SliceName(slice, composition, data.EnergyTypes, data.MeterNames), href, OverviewDonutSlice.SafeColor(category?.ColorHex), amount, status, share)
{
Chip = OverviewText.CostQualifier(slice.Total, status),
});
}
_maxAbs = _rows.Select(r => Math.Abs(r.Amount ?? 0)).DefaultIfEmpty(0).Max();
if (!_signed)
{
var inDonut = _rows.Where(r => r.Amount is > CategoryComposition.DonutTolerance).ToList();
for (var i = 0; i < inDonut.Count; i++)
{
inDonut[i].DonutIndex = i;
}
_donut = [.. inDonut.Select(r => new OverviewDonutSlice(r.Name, r.Amount!.Value, r.Color))];
}
if (_rows.Count > 0)
{
var totalStatus = FigureText.Of(composition.Total);
_rows.Add(new Row(S.Overview_BillTotal, null, null, totalStatus.IsKnown ? composition.Total.Cost : null, totalStatus, null)
{
IsTotal = true,
Chip = OverviewText.CostQualifier(composition.Total, totalStatus),
});
}
var names = composition.Categories.ToDictionary(c => c.CategoryId, c => c.Name);
foreach (var category in composition.Categories.Where(c => c.IsOverlappingView))
{
var status = FigureText.Of(category.Total);
var others = category.OverlapsWith.Select(o => names.GetValueOrDefault(o)).OfType<string>().ToList();
_views.Add(new ViewRow(
category.Name,
AnalysisLinks.Analysis(QueryScope.ForCategory(category.CategoryId), AnalysisMetric.Cost, View.Query),
status.IsKnown ? category.Total.Cost : null,
status,
others.Count > 0 ? Loc.F(S.Overview_ViewOverlaps, string.Join(", ", others)) : category.Cover.LiesOutsideBill ? S.Overview_ViewOutsideBill : null));
}
}
/// <summary>The swatch of a donut slice: its category's colour, else the palette hue the donut gives it (same order).</summary>
private string SwatchStyle(Row row) =>
_donut.Count <= 1 || row.DonutIndex is not { } index ? "visibility:hidden"
: "background:" + (row.Color ?? OverviewDonutSlice.PaletteVariable(index));
/// <summary>The width of a signed bar in its half: the share of the largest amount either way.</summary>
private string BarStyle(double? amount, bool negative)
{
if (amount is not { } value || _maxAbs <= 0 || (negative ? value >= 0 : value <= 0))
{
return "width:0";
}
var percent = Math.Abs(value) / _maxAbs * 100;
return string.Create(System.Globalization.CultureInfo.InvariantCulture, $"width:{percent:0.#}%");
}
}