Files
MeterVault/src/App/Components/Pages/MeterPage/MeterAnalysisTab.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

238 lines
13 KiB
Plaintext

@inject NavigationManager Nav
@* The meter's Analysis tab (brief §7.2): the shared period toolbar with CSV export, the period's quantity (normalized
unit, D-20) and cost (with its rule named, or why there is none), the projection kept apart from the actual (D-09),
the full-size chart with the comparison overlay, the accessible table, a click on a bucket drilling down (D-51), and
what qualifies the figures: coverage, resolution, opening balance, rows after now, freshness, and the events and
tariff changes inside the range. A virtual meter gets the same from its formula, with its sources' contributions. *@
<PeriodToolbar Query="Query" Period="Current?.Period" Plan="Current?.Quantities.Plan" Defaults="Defaults"
QueryChanged="OnQueryChanged" ExportHref="@ExportHref"
Metrics="Current?.Metrics" NaturalMetric="Current?.QuantityMetric" Class="mb-3" />
<LoadPanel State="State" OnRetry="OnRetry" Context="r">
@if (r.MeterId == Detail.Id)
{
var s = r.Series;
@if (s is null)
{
<MudAlert Severity="Severity.Warning" Dense="true">@Loc.F(S.MeterDetail_NotFound, Detail.Id)</MudAlert>
}
else if (r.Quantities.Refusal != AnalysisRefusal.None)
{
@* The toolbar above says why (too many points) and offers the coarser bucket. *@
}
else
{
<AttentionList Problems="ProblemsOf(r)" CostAttention="r.Cost?.Attention" Names="r.AttentionNames"
Query="Query" MaxItems="4" Class="mb-3" />
@if (s.IsPending)
{
<PendingState OnRefresh="OnRetry" />
}
else if (s.Total.Status == BucketStatus.Invalid)
{
<MudAlert Severity="Severity.Error" Class="mb-3">
@Loc.F(S.MeterDetail_CalculationNotEvaluable, (s.Virtual?.Status ?? VirtualMeterStatus.Invalid).Display())
<div class="d-flex flex-wrap mt-2" style="gap:.5rem">
<MudButton Size="Size.Small" Variant="Variant.Outlined" StartIcon="@Icons.Material.Filled.Functions"
OnClick="OnEdit">@S.MeterDetail_EditCalculation</MudButton>
<MudButton Size="Size.Small" Variant="Variant.Text"
Href="@MeterLinks.Detail(Detail.Id, MeterLinks.TabCalculation, null, Query)">@S.MeterDetail_ShowCalculation</MudButton>
</div>
</MudAlert>
}
else if (r.Quantities.NotYetOccurred || s.Total.Status == BucketStatus.Missing)
{
<EmptyPeriodState NotYetOccurred="r.Quantities.NotYetOccurred" Availability="s.Availability" LatestHref="@LatestHref(s)" Class="mb-3">
@if (s.Availability is null)
{
<MudText Typo="Typo.body2" Class="mv-muted">@NextStepText</MudText>
<div class="d-flex flex-wrap mt-2" style="gap:.5rem">
@if (MeterEventRules.TakesReadings(Detail.Mode))
{
<MudButton Size="Size.Small" Variant="Variant.Outlined" StartIcon="@Icons.Material.Filled.EditNote"
OnClick="OnAddReading">@S.MeterDetail_AddFirstReading</MudButton>
<MudButton Size="Size.Small" Variant="Variant.Text" StartIcon="@Icons.Material.Filled.SettingsInputComponent"
Href="@MeterLinks.Source(Detail.Id)">@S.MeterDetail_ConnectSource</MudButton>
}
else if (Detail.Mode == MeterMode.ConsumableBalance)
{
<MudButton Size="Size.Small" Variant="Variant.Outlined" StartIcon="@Icons.Material.Filled.Straighten"
OnClick="@(() => OnRecordEvent.InvokeAsync(MeterEventType.TankLevel))">@S.MeterDetail_RecordTankLevel</MudButton>
}
else if (Detail.IsVirtual)
{
<MudButton Size="Size.Small" Variant="Variant.Text" StartIcon="@Icons.Material.Filled.Functions"
Href="@MeterLinks.Detail(Detail.Id, MeterLinks.TabCalculation, null, Query)">@S.MeterDetail_ShowCalculation</MudButton>
}
</div>
}
</EmptyPeriodState>
@if (Detail.IsVirtual)
{
<SeriesContributions Series="s" Query="Query" Class="mt-3" />
}
}
else
{
<MudGrid Spacing="2" Class="mb-1">
<MudItem xs="12" sm="6" md="4">
<MetricCard Title="@s.Kind.Display()" Value="s.Total" Unit="@s.Unit" Caption="@Format.PeriodRange(r.Period)"
Change="s.Comparison?.Change" Polarity="ChangePolarities.For(s.Kind)"
ChangeCaption="@ComparisonCaption">
@if (r.Projection is { } projection)
{
<ProjectionNote Days="projection.Days" ValueText="@Format.Quantity(projection.Value, projection.Unit)" Class="mt-2" />
}
</MetricCard>
</MudItem>
@if (r.Cost is { } cost)
{
<MudItem xs="12" sm="6" md="4">
@if (r.IsCosted)
{
<MetricCard Title="@S.MeterDetail_CostTitle" Cost="cost.Total" Currency="@cost.Currency"
Caption="@CostRuleText(cost)"
Change="CostChanges.ForCard(r.CostChange)" Polarity="CostChanges.Polarity(r.CostChange)"
ChangeCaption="@CostChanges.Caption(Query, r.CostChange)" />
}
else
{
<MudPaper Outlined="true" Elevation="0" Class="pa-4 mv-metric">
<MudText Typo="Typo.overline" Class="mv-muted mv-metric__title">@S.MeterDetail_CostTitle</MudText>
<div class="mv-metric__value-row">
<span class="mv-metric__value mv-metric__value--words">@MeterCostRule.None.Display()</span>
</div>
<MudText Typo="Typo.caption" Class="mv-muted">@((cost.Meter?.NotCosted ?? MeterNotCostedReason.None).Display())</MudText>
</MudPaper>
}
</MudItem>
}
</MudGrid>
<ComparisonSummary Period="r.Period" Resolution="r.Quantities.Comparison?.Resolution" Matched="s.Comparison?.Matched" Class="mb-2" />
@* A click leads somewhere or is not offered (D-51): the chart is clickable, the table has its drill column and
the hint shows only when some bucket opens something. *@
var drills = r.Quantities.Plan.Buckets.Any(b => DrillHref(b, r, s) is not null);
<MudPaper Outlined="true" Elevation="0" Class="pa-3 mb-3">
@if (drills)
{
<AnalysisChart Buckets="r.Quantities.Plan.Buckets" Series="r.Chart" ComparisonPairs="r.Quantities.Comparison?.Buckets"
Title="@ChartTitle(r, s)" Height="340" OnBucketClick="b => Drill(b, r, s)"
Resolution="s.Resolution" OnUseBucket="UseBucketAsync" />
<MudText Typo="Typo.caption" Class="mv-muted">@DrillHint(s)</MudText>
}
else
{
<AnalysisChart Buckets="r.Quantities.Plan.Buckets" Series="r.Chart" ComparisonPairs="r.Quantities.Comparison?.Buckets"
Title="@ChartTitle(r, s)" Height="340" Resolution="s.Resolution" OnUseBucket="UseBucketAsync" />
}
</MudPaper>
<AnalysisTable Buckets="r.Quantities.Plan.Buckets" Series="r.Table" ComparisonPairs="r.Quantities.Comparison?.Buckets"
DrillHref="@(drills ? b => DrillHref(b, r, s) : null)" Caption="@ChartTitle(r, s)" />
@if (Detail.IsVirtual)
{
<MudText Typo="Typo.h6" Class="mt-5 mb-1">@S.MeterDetail_SourcesOfCalculation</MudText>
<SeriesContributions Series="s" Query="Query" />
}
}
<MeterCoverageNote View="r" Detail="Detail" Query="Query" OnEdit="OnEdit" Class="mt-5" />
}
}
</LoadPanel>
@code {
/// <summary>The meter.</summary>
[Parameter, EditorRequired]
public MeterDetailView Detail { get; set; } = null!;
/// <summary>The page's analysis state.</summary>
[Parameter, EditorRequired]
public AnalysisQuery Query { get; set; } = null!;
/// <summary>The page's analysis load (owned by the page, so switching tabs never reloads it, D-46).</summary>
[Parameter, EditorRequired]
public LoadState<MeterAnalysisView> State { get; set; } = null!;
/// <summary>A toolbar choice: the page writes it into its address (replace).</summary>
[Parameter]
public EventCallback<AnalysisQuery> OnQueryChanged { get; set; }
[Parameter]
public EventCallback OnRetry { get; set; }
[Parameter]
public EventCallback OnAddReading { get; set; }
[Parameter]
public EventCallback<MeterEventType> OnRecordEvent { get; set; }
/// <summary>Opens the shared meter editor (install date, calculation).</summary>
[Parameter]
public EventCallback OnEdit { get; set; }
private AnalysisDefaults Defaults => MeterAnalysisLoader.DefaultsFor(Detail.Id);
/// <summary>The committed value when it is this meter's.</summary>
private MeterAnalysisView? Current => State.Value is { } value && value.MeterId == Detail.Id ? value : null;
private string ExportHref => AnalysisLinks.Export(MeterAnalysisLoader.ForMeter(Query, Detail.Id));
private string? ComparisonCaption => Query.Comparison.Kind == ComparisonKind.None ? null : Query.Comparison.Display();
private string NextStepText => Detail.Mode switch
{
MeterMode.ConsumableBalance => S.MeterDetail_NextStepTank,
MeterMode.Virtual => S.MeterDetail_NextStepVirtual,
_ => S.MeterDetail_NextStepCounter,
};
/// <summary>
/// The readers' problems for the attention list. Rows recorded after now are explained with their dates and amount in
/// the coverage section below, so they are not listed twice.
/// </summary>
private static IEnumerable<AnalysisProblem> ProblemsOf(MeterAnalysisView view) =>
view.Quantities.Problems.Concat(view.Cost?.QuantityProblems ?? [])
.Where(p => p.Kind != AnalysisProblemKind.RecordedAfterNow);
private string CostRuleText(Infrastructure.Costing.CostAnalysis cost) =>
Loc.F(S.MeterDetail_CostRule, (cost.Meter?.Rule ?? MeterCostRule.None).Display());
private static string ChartTitle(MeterAnalysisView view, AnalysisSeries series) =>
view.ShowsCost
? Loc.F(S.MeterDetail_CostOf, AnalysisChartSeries.NameOf(series))
: Loc.F(S.MeterDetail_ChartTitle, series.Kind.Display(), AnalysisChartSeries.NameOf(series));
private string DrillHint(AnalysisSeries series) =>
Detail.IsVirtual ? S.MeterDetail_DrillHintVirtual : S.MeterDetail_DrillHint;
private string? LatestHref(AnalysisSeries series) =>
AnalysisNavigation.LatestData(Query, series.Availability) is { } latest ? MeterLinks.Analysis(Detail.Id, latest) : null;
/// <summary>
/// Where a bucket leads (D-51, <see cref="MeterDrill"/>): the next finer size the data resolves; otherwise a physical
/// meter's records of the bucket, or a virtual meter's own analysis over just that bucket, whose source contributions
/// link on to each source's records — never a dead end.
/// </summary>
private string? DrillHref(AnalysisBucket bucket, MeterAnalysisView view, AnalysisSeries series) =>
MeterDrill.Href(Detail.Id, Detail.IsVirtual, Query, view.Period, bucket, series.Resolution);
/// <summary>A chart click drills down, pushing a history entry so Back returns to the range it came from (D-46).</summary>
private void Drill(AnalysisBucket bucket, MeterAnalysisView view, AnalysisSeries series)
{
if (DrillHref(bucket, view, series) is { } href)
{
Nav.NavigateTo(href);
}
}
/// <summary>The buckets are finer than the data: apply the interval that shows it (the page replaces its address).</summary>
private Task UseBucketAsync(BucketSize size) => OnQueryChanged.InvokeAsync(Query.WithBucket(size));
}