Files
MeterVault/src/App/Components/Pages/Energy/EnergyHistoryTab.razor
T
Florian Schmidt 8940ef25c3
ci / build-test (push) Successful in 2m31s
Analysis: one selected period, one set of numbers, on every page
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.
2026-09-20 10:29:13 +02:00

209 lines
9.2 KiB
Plaintext

@using MeterVault.App.Energy
@using MeterVault.Core.Analysis
@using MeterVault.Infrastructure.Analysis
@inject NavigationManager Nav
@* The energy type's History (brief §7.3): the shared chart and table for the chosen metric, over the page's period and
interval, compared with the chosen period (a calendar year for a year). "Total" charts the type's measures — never a
breakdown on top of its parent or a calculated view on top of its sources (D-22); "Individual meters" charts the
meters side by side and says how each one counts, so their bars are not read as adding up. Signed values stay signed.
A bucket opens its finer detail (D-51). *@
<div class="mv-energy-history">
<div class="mv-energy-history__views">
<MudToggleGroup T="string" Value="@View" ValueChanged="OnViewChangedAsync" SelectionMode="SelectionMode.SingleSelection"
Outlined="true" Color="Color.Primary" Size="Size.Small" aria-label="@S.EnergyView_ViewLabel"
Class="mv-energy-history__toggle">
<MudToggleItem T="string" Value="@EnergyPageKeys.ViewTotal" Text="@S.EnergyView_ViewTotal" />
<MudToggleItem T="string" Value="@EnergyPageKeys.ViewMeters" Text="@S.EnergyView_ViewMeters" />
</MudToggleGroup>
<MudText Typo="Typo.caption" Class="mv-muted">
@(_view?.IsIndividual == true ? S.EnergyView_ViewMetersHelp : S.EnergyView_ViewTotalHelp)
</MudText>
</div>
@if (_view is null || _quantities is null)
{
@* Nothing read yet: the page shows its own loading state. *@
}
else if (_view.IsEmpty)
{
<MudAlert Severity="Severity.Info" Dense="true">@EmptyText()</MudAlert>
}
else if (_view.Main is { IsPending: true })
{
<PendingState OnRefresh="OnRefresh" />
}
else if (_quantities.NotYetOccurred || NoData())
{
<EmptyPeriodState NotYetOccurred="_quantities.NotYetOccurred" Availability="Availability()" LatestHref="@LatestHref()" />
}
else
{
<ComparisonSummary Period="Analysis.Period" Resolution="ComparisonResolution()" Matched="_view.Main?.Comparison?.Matched" Class="mb-3" />
<AnalysisChart Buckets="_buckets" Series="_view.Chart" ComparisonPairs="_pairs" Title="@_title" OnBucketClick="_onBucketClick"
Resolution="_view.Coarsest" OnUseBucket="UseBucket" />
@if (_view.IsIndividual)
{
@if (_view.Hidden > 0)
{
<MudText Typo="Typo.body2" Class="mv-muted mt-2">
@Loc.F(S.EnergyView_MoreMeters, _view.Shown.Count, _view.Shown.Count + _view.Hidden)
<MudLink Href="@AnalysisLinks.Analysis(QueryScope.ForEnergyType(Analysis.EnergyTypeId), _view.Metric, Query)" Typo="Typo.body2">@S.Nav_Analysis</MudLink>
</MudText>
}
@if (_view.Memberships.Count > 0)
{
<section class="mv-energy-history__counts" aria-labelledby="@_countsId">
<MudText Typo="Typo.subtitle2" id="@_countsId">@S.EnergyView_HowCounted</MudText>
<ul>
@foreach (var (series, membership) in _view.Memberships)
{
<li>
<MudIcon Icon="@MeterListRows.MembershipIcon(membership)" Size="Size.Small" aria-hidden="true" Class="mv-muted" />
<span>
<MudLink Href="@MeterLinks.Analysis(series.MeterId!.Value, Query)" Typo="Typo.body2">@series.Name</MudLink>:
@membership.Label@(string.IsNullOrEmpty(membership.Detail) ? null : " — " + membership.Detail)
</span>
</li>
}
</ul>
</section>
}
}
else if (_view.Metric == AnalysisMetric.Cost && Analysis.Cost is { } cost)
{
<AttentionList CostAttention="cost.Attention" Problems="cost.QuantityProblems" Names="Analysis.Names" Query="Query"
MaxItems="3" Class="mt-3" />
}
<div class="mt-4">
<AnalysisTable Buckets="_buckets" Series="_view.Table" ComparisonPairs="_pairs" Caption="@_title" DrillHref="_drillHref" />
</div>
}
</div>
@code {
/// <summary>The page's committed value.</summary>
[Parameter, EditorRequired]
public EnergyAnalysis Analysis { get; set; } = null!;
/// <summary>The page's analysis state.</summary>
[Parameter, EditorRequired]
public AnalysisQuery Query { get; set; } = null!;
/// <summary>The page's defaults (drill-downs and "latest data" keep the page's other keys).</summary>
[Parameter, EditorRequired]
public AnalysisDefaults Defaults { get; set; } = null!;
/// <summary>The metric shown (<see cref="EnergyMetrics.Effective"/>).</summary>
[Parameter]
public AnalysisMetric Metric { get; set; }
/// <summary>The view key (<see cref="EnergyPageKeys.ViewTotal"/> or <see cref="EnergyPageKeys.ViewMeters"/>).</summary>
[Parameter]
public string View { get; set; } = EnergyPageKeys.ViewTotal;
/// <summary>The view was switched; the page writes it into its address.</summary>
[Parameter]
public EventCallback<string> ViewChanged { get; set; }
/// <summary>Loads again (analysis being prepared).</summary>
[Parameter]
public EventCallback OnRefresh { get; set; }
private readonly string _countsId = "mv-counts-" + Guid.NewGuid().ToString("N")[..8];
private object? _builtFrom;
private EnergyHistoryView? _view;
private AnalysisResult? _quantities;
private IReadOnlyList<AnalysisBucket> _buckets = [];
private IReadOnlyList<BucketPair>? _pairs;
private string _title = string.Empty;
private EventCallback<AnalysisBucket> _onBucketClick;
private Func<AnalysisBucket, string?>? _drillHref;
protected override void OnParametersSet()
{
// Rebuilt only for a new value, metric, view or comparison: the chart re-keys on a new list.
var source = (Analysis, Metric, View, Query.Comparison);
if (Equals(_builtFrom, source))
{
return;
}
_builtFrom = source;
_quantities = Analysis.Quantities;
_view = EnergyHistoryView.Build(Analysis, Metric, View == EnergyPageKeys.ViewMeters, Query.Comparison);
if (_view.Metric == AnalysisMetric.Cost && Analysis.Cost is { } cost)
{
_buckets = cost.Plan.Buckets;
_pairs = Analysis.CostComparison?.Pairs is { Count: > 0 } pairs ? pairs : null;
}
else
{
_buckets = _quantities?.Plan.Buckets ?? [];
_pairs = _quantities?.Comparison?.Buckets;
}
var typeName = Analysis.Type?.Name ?? string.Empty;
_title = Loc.F(S.EnergyView_ChartTitle, Metric.Display(), typeName);
// Buckets are clickable, and the table has its drill column, only when some bucket leads somewhere (D-51): monthly
// data has no days to open, and a click that does nothing is a dead end.
var drills = _buckets.Any(b => DrillHref(b) is not null);
_onBucketClick = drills ? EventCallback.Factory.Create<AnalysisBucket>(this, DrillAsync) : default;
_drillHref = drills ? DrillHref : null;
}
/// <summary>The buckets are finer than the data: open the interval that shows it (replacing the address, D-46).</summary>
private void UseBucket(BucketSize size) => AnalysisNavigation.Replace(Nav, Query.WithBucket(size), Defaults);
private async Task OnViewChangedAsync(string? view) =>
await ViewChanged.InvokeAsync(EnergyPageKeys.ResolveView(view));
private string EmptyText()
{
if (_view!.Metric == AnalysisMetric.Cost)
{
return S.EnergyView_CostPerMeterNote;
}
return _view.IsIndividual
? Loc.F(S.EnergyView_NoMetersForMetric, _view.Metric.Display())
: Loc.F(S.EnergyView_NoTotalForMetric, _view.Metric.Display());
}
private bool NoData()
{
if (_view!.Metric == AnalysisMetric.Cost)
{
return false;
}
var shown = _view.IsIndividual ? _view.Shown : EnergyMetrics.MeasuresOf(_quantities, _view.Metric);
return _view.HasNoData(shown);
}
private MeterVault.Core.Analysis.Coverage.AvailableRange? Availability() =>
_view?.Main?.Availability ?? _quantities?.Availability.Quantity;
private ComparisonResolution? ComparisonResolution() =>
_view?.Metric == AnalysisMetric.Cost ? Analysis.CostComparison?.Resolution : _quantities?.Comparison?.Resolution;
private string? LatestHref() =>
AnalysisNavigation.LatestData(Query, Availability()) is { } latest ? AnalysisNavigation.UriFor(Nav, latest, Defaults) : null;
private string? DrillHref(AnalysisBucket bucket) =>
AnalysisNavigation.DrillInto(Query, bucket, _view?.Coarsest) is { } next ? AnalysisNavigation.UriFor(Nav, next, Defaults) : null;
/// <summary>A chart bucket opens its finer detail (D-51), pushing a history entry so Back returns here.</summary>
private void DrillAsync(AnalysisBucket bucket)
{
if (DrillHref(bucket) is { } href)
{
Nav.NavigateTo(href);
}
}
}