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
+101 -190
View File
@@ -1,215 +1,126 @@
@page "/consumables"
@using MeterVault.App.Components.Pages.Specialized
@using MeterVault.Core.Analysis
@implements IDisposable
@inject NavigationManager Nav
@inject InstanceClock Clock
@inject ConsumableService ConsumablesSvc
@inject Microsoft.Extensions.Options.IOptions<MeterVault.Infrastructure.Options.MeterVaultOptions> Options
@using MudBlazor
@inject ILogger<Consumables> Logger
<PageTitle>MeterVault — @S.Consumables_PageTitle</PageTitle>
@* Tanks & consumables (brief §7.5, D-54): the shared header, toolbar and missing-data semantics around every tank's
specialised measures. Each tank keeps its state now — the last dipstick as measured, the contents estimated from it,
the forecast as a projection — apart from the selected period, which has its own usage, deliveries, burner runtime,
cost and, for a period that is over, the contents at its end. *@
<div class="d-flex align-center justify-space-between mb-4 flex-wrap" style="gap:1rem">
<MudText Typo="Typo.h4">@S.Nav_Consumables</MudText>
<MudSelect T="int" Value="_months" ValueChanged="OnRangeChanged" Label="@S.Common_Range" Dense="true" Style="max-width:200px">
<MudSelectItem T="int" Value="12">@S.Common_RangeLast12Months</MudSelectItem>
<MudSelectItem T="int" Value="24">@S.Common_RangeLast24Months</MudSelectItem>
<MudSelectItem T="int" Value="60">@S.Common_RangeLast5Years</MudSelectItem>
<MudSelectItem T="int" Value="1200">@S.Common_RangeAllTime</MudSelectItem>
</MudSelect>
</div>
<PageHeader Title="@S.Nav_Consumables" Description="@S.Consumables_Description">
<Breadcrumbs>
<AnalysisBreadcrumbs Query="_query" Current="@S.Nav_Consumables" />
</Breadcrumbs>
</PageHeader>
@* A consumable meter without a tank has no capacity or calibration, so it cannot be summarised —
but it must not just be missing from the page, with nothing saying where it went. *@
@foreach (var meter in _unconfigured)
@if (_query is not null)
{
<MudAlert Severity="Severity.Warning" Class="mb-3">
@Loc.F(S.Consumables_TankNotConfigured, meter.Name)
<MudButton Size="Size.Small" Variant="Variant.Text" Color="Color.Warning" Class="ml-2"
Href="@MeterLinks.Detail(meter.MeterId, action: MeterLinks.ActionEdit)">@S.MeterDetail_SetUpTank</MudButton>
</MudAlert>
<PeriodToolbar Query="_query" Period="_state.Value?.Analysis.Period" Plan="_state.Value?.Analysis.Plan" Defaults="Defaults"
QueryChanged="OnQueryChanged" ExportHref="@_state.Value?.ExportHref" Class="mb-4" />
}
@if (_items is null)
{
<MudProgressLinear Indeterminate="true" Color="Color.Primary" />
}
else if (_items.Count == 0 && _unconfigured.Count == 0)
{
<MudAlert Severity="Severity.Info">
@S.Consumables_NoMetersLead <b>@MeterMode.ConsumableBalance.Display()</b> @S.Consumables_NoMetersTail
<MudLink Href="/meters">@S.Nav_Meters</MudLink>@S.Consumables_NoMetersOrImport
<MudLink Href="/import">@S.Nav_Import</MudLink>.
</MudAlert>
}
else
{
@foreach (var item in _items)
<LoadPanel State="_state" OnRetry="RetryAsync" Context="view">
@* A consumable meter without a tank has no capacity or calibration, so it cannot be summarised — but it must not just
be missing from the page, with nothing saying where it went. *@
@foreach (var meter in view.Analysis.Unconfigured)
{
<MudPaper Class="pa-4 mb-4" Elevation="2">
@* The actions for a tank are the ones done standing next to it, so they sit on its card. *@
<div class="d-flex align-center flex-wrap mb-3" style="gap:.5rem">
<MudLink Href="@MeterLinks.Detail(item.MeterId)" Typo="Typo.h6">@item.Name</MudLink>
<MudSpacer />
<MudButton Size="Size.Small" Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Straighten"
Href="@MeterLinks.Event(item.MeterId, MeterEventType.TankLevel)">@S.MeterDetail_RecordTankLevel</MudButton>
<MudButton Size="Size.Small" Variant="Variant.Outlined" Color="Color.Primary" StartIcon="@Icons.Material.Filled.LocalShipping"
Href="@MeterLinks.Event(item.MeterId, MeterEventType.Delivery)">@S.Consumables_RecordDelivery</MudButton>
</div>
<MudGrid>
<MudItem xs="12" md="4">
<MudText Typo="Typo.overline" Color="Color.Secondary">@S.Consumables_TankLevel</MudText>
<MudText Typo="Typo.h5">
@(item.CurrentLevel is { } l ? $"{Format.Number(l, 0)} {item.Unit}" : "—")
</MudText>
<MudProgressLinear Color="@FillColor(item.FillFraction)" Value="@(item.FillFraction * 100)" Class="my-2" Size="Size.Large" />
<MudText Typo="Typo.caption" Color="Color.Secondary">
@Loc.F(S.Consumables_FillOfCapacity, Format.Number(item.FillFraction * 100, 0), Format.Number(item.Capacity, 0), item.Unit)
@if (item.PhysicalLevel is { } cm && item.PhysicalUnit is "cm")
{
<text> · @Format.Number(cm, 0) cm</text>
}
@if (item.LevelAsOf is { } asOf)
{
<text> · @Loc.F(S.Consumables_AsOf, Local(asOf).ToString("yyyy-MM-dd"))</text>
}
</MudText>
</MudItem>
<MudItem xs="12" md="8">
<MudGrid>
<MudItem xs="6" sm="3">
<MudText Typo="Typo.overline" Color="Color.Secondary">@S.Consumables_UsedRange</MudText>
<MudText Typo="Typo.subtitle1">@Format.Number(item.ConsumptionInRange, 0) @item.Unit</MudText>
</MudItem>
<MudItem xs="6" sm="3">
<MudText Typo="Typo.overline" Color="Color.Secondary">@S.Consumables_BurnerRuntime</MudText>
<MudText Typo="Typo.subtitle1">@(item.BurnerHours is { } h ? $"{Format.Number(h, 0)} h" : "—")</MudText>
</MudItem>
<MudItem xs="6" sm="3">
<MudText Typo="Typo.overline" Color="Color.Secondary">@S.Consumables_EffectiveRate</MudText>
<MudText Typo="Typo.subtitle1">
@if (item.FixedRate is { } fr)
{
<text>@Format.Number(fr, 2) @item.Unit/h</text>
}
else if (item.EffectiveRate is { } er)
{
<text>@Format.Number(er, 2) @item.Unit/h</text>
}
else
{
<text>—</text>
}
</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">@item.RateMode.Display()</MudText>
</MudItem>
<MudItem xs="6" sm="3">
<MudText Typo="Typo.overline" Color="Color.Secondary">@S.Common_CostRange</MudText>
<MudText Typo="Typo.subtitle1">@Format.Euro(item.CostInRange)</MudText>
</MudItem>
<MudItem xs="12" sm="6">
<MudText Typo="Typo.overline" Color="Color.Secondary">@S.Consumables_ForecastEmpty</MudText>
<MudText Typo="Typo.subtitle1">
@(item.ForecastEmpty is { } fe ? fe.ToString("yyyy-MM-dd") : "—")
@if (item.AveragePerDay is { } apd)
{
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="d-inline">
@Loc.F(S.Consumables_PerDay, Format.Number(apd, 1), item.Unit)
</MudText>
}
</MudText>
</MudItem>
</MudGrid>
</MudItem>
<MudItem xs="12" md="7">
<MudText Typo="Typo.subtitle2" Class="mb-2">@S.Consumables_ConsumptionByMonth</MudText>
<SeriesChart Series="@ChartFor(item)" Decimals="0" Height="260" />
</MudItem>
<MudItem xs="12" md="5">
<MudText Typo="Typo.subtitle2" Class="mb-2">@Loc.F(S.Consumables_DeliveriesCount, item.Deliveries.Count)</MudText>
@if (item.Deliveries.Count == 0)
{
<MudText Typo="Typo.body2" Color="Color.Secondary">@S.Consumables_NoDeliveries</MudText>
}
else
{
<div style="max-height:260px; overflow-y:auto">
<MudSimpleTable Dense="true" Hover="true">
<thead>
<tr><th>@S.Common_Date</th><th style="text-align:right">@S.Common_Amount</th></tr>
</thead>
<tbody>
@foreach (var delivery in item.Deliveries)
{
<tr>
<td>@Local(delivery.Time).ToString("yyyy-MM-dd")</td>
<td style="text-align:right">@Format.Number(delivery.Amount, 0) @(delivery.Unit ?? item.Unit)</td>
</tr>
}
</tbody>
</MudSimpleTable>
</div>
}
</MudItem>
</MudGrid>
</MudPaper>
<MudAlert Severity="Severity.Warning" Class="mb-3">
@Loc.F(S.Consumables_TankNotConfigured, meter.Name)
<MudButton Size="Size.Small" Variant="Variant.Text" Color="Color.Warning" Class="ml-2"
Href="@MeterLinks.Detail(meter.MeterId, action: MeterLinks.ActionEdit)">@S.Consumables_SetUpTank</MudButton>
</MudAlert>
}
}
@if (view.Analysis.Tanks.Count == 0 && view.Analysis.Unconfigured.Count == 0)
{
<div class="mv-empty" role="status">
<MudIcon Icon="@Icons.Material.Outlined.PropaneTank" Class="mv-empty__icon" aria-hidden="true" />
<div class="mv-empty__body">
<MudText Typo="Typo.subtitle1">@S.Consumables_NoTanksTitle</MudText>
<MudText Typo="Typo.body2" Class="mv-muted">@Loc.F(S.Consumables_NoTanksHelp, MeterMode.ConsumableBalance.Display())</MudText>
<div class="d-flex flex-wrap mt-2" style="gap:.5rem">
<MudButton Variant="Variant.Outlined" Color="Color.Primary" Size="Size.Small" Href="/meters">@S.Nav_Meters</MudButton>
<MudButton Variant="Variant.Text" Color="Color.Primary" Size="Size.Small" Href="/import">@S.Nav_Import</MudButton>
</div>
</div>
</div>
}
else if (!view.Analysis.IsRefused)
{
@foreach (var tank in view.Tanks)
{
<TankSection @key="tank.Tank.MeterId" View="tank" Query="view.Query" Period="view.Analysis.Period"
Problems="ProblemsOf(view.Analysis, tank.Tank)" Currency="@view.Analysis.Currency" OnRefresh="RetryAsync" />
}
}
</LoadPanel>
@code {
private int _months = 60;
private bool _loading;
private IReadOnlyList<ConsumableSummary>? _items;
private IReadOnlyList<UnconfiguredConsumable> _unconfigured = [];
private TimeZoneInfo _tz = TimeZoneInfo.Utc;
private static readonly AnalysisDefaults Defaults = AnalysisDefaults.History;
protected override Task OnInitializedAsync()
private readonly LoadSequencer _loads = new();
private readonly LoadState<ConsumablesPageView> _state = new();
private AnalysisQuery? _query;
/// <summary>One committed result: the query it answers, the read model, every tank's series and the export link.</summary>
private sealed record ConsumablesPageView(AnalysisQuery Query, ConsumableAnalysis Analysis, IReadOnlyList<TankView> Tanks, string? ExportHref);
protected override void OnInitialized() => Nav.LocationChanged += OnLocationChanged;
protected override Task OnParametersSetAsync() => ReloadIfChangedAsync();
private void OnLocationChanged(object? sender, LocationChangedEventArgs e) => _ = InvokeAsync(ReloadIfChangedAsync);
private async Task ReloadIfChangedAsync()
{
_tz = LocalTimeEntry.Resolve(Options.Value.TimeZone);
return LoadAsync();
}
private DateTimeOffset Local(DateTimeOffset instant) => TimeZoneInfo.ConvertTime(instant, _tz);
private async Task OnRangeChanged(int months)
{
_months = months;
await LoadAsync();
}
private async Task LoadAsync()
{
if (_loading)
var query = AnalysisQuery.Parse(Nav.Uri, Defaults);
if (query == _query)
{
return;
}
_loading = true;
_items = null;
try
{
var asOf = DateOnly.FromDateTime(DateTime.UtcNow);
var from = asOf.AddMonths(-_months);
_unconfigured = await ConsumablesSvc.GetUnconfiguredAsync();
_items = await ConsumablesSvc.GetConsumablesAsync(new DateOnly(from.Year, from.Month, 1), asOf.AddMonths(1));
}
finally
{
_loading = false;
}
_query = query;
await LoadAsync(query);
StateHasChanged();
}
private static IReadOnlyList<SeriesChart.SeriesDef> ChartFor(ConsumableSummary item)
private Task RetryAsync() => _query is null ? Task.CompletedTask : LoadAsync(_query);
private Task LoadAsync(AnalysisQuery query) => _loads.RunAsync(_state, async token =>
{
var points = item.Months
.Select(m => new SeriesChart.Point(Format.MonthLabel(m.Period), m.Consumption))
.ToList();
return [new SeriesChart.SeriesDef(Loc.F(S.Consumables_UnitUsed, item.Unit), ApexCharts.SeriesType.Bar, points)];
// "Now" is read once per load (D-01); "all" spans what the tanks have data for (D-19).
var now = Clock.Now;
var availability = query.Period == PeriodPreset.AllHistory ? await ConsumablesSvc.GetAvailabilityAsync(now, token) : null;
var period = query.Resolve(now, ConsumablesSvc.Zone, availability);
var analysis = await ConsumablesSvc.GetAsync(new ConsumableRequest(period) { Bucket = query.Bucket, Comparison = query.Comparison }, token);
var tanks = analysis.Tanks.Select(t => TankView.Build(t, analysis.Quantities, query, analysis.Currency)).ToList();
// The CSV export of what the tables show: every tank's usage (D-55), within the chart's series limit.
var ids = analysis.Tanks.Select(t => t.MeterId).ToList();
var export = ids.Count is > 0 and <= MeterVault.Infrastructure.Analysis.AnalysisLimits.MaxSeries
? AnalysisLinks.Export(query.WithScope(QueryScope.ForMeters(ids)).WithMetric(AnalysisMetric.Consumption))
: null;
return new ConsumablesPageView(query, analysis, tanks, export);
}, Logger);
private void OnQueryChanged(AnalysisQuery query) => AnalysisNavigation.Replace(Nav, query, Defaults);
/// <summary>The reader's problems about one tank and the burners it feeds.</summary>
private static IReadOnlyList<MeterVault.Infrastructure.Analysis.AnalysisProblem> ProblemsOf(ConsumableAnalysis analysis, TankAnalysis tank)
{
var ids = tank.Runtime.Select(r => r.MeterId).OfType<int>().Append(tank.MeterId).ToHashSet();
var problems = (analysis.Quantities?.Problems ?? []).Concat(tank.Cost?.QuantityProblems ?? []);
return [.. problems.Where(p => p.MeterId is { } id ? ids.Contains(id) : p.MeterIds.Any(ids.Contains))];
}
private static Color FillColor(double fraction) => fraction switch
public void Dispose()
{
< 0.15 => Color.Error,
< 0.30 => Color.Warning,
_ => Color.Success,
};
Nav.LocationChanged -= OnLocationChanged;
_loads.Dispose();
}
}