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

172 lines
7.0 KiB
Plaintext

@page "/meters"
@using MeterVault.App.Energy
@using MeterVault.App.Components.Shared.MeterLists
@using MeterVault.Core.Analysis
@using MeterVault.Infrastructure.Analysis
@using Microsoft.EntityFrameworkCore
@inject Microsoft.EntityFrameworkCore.IDbContextFactory<MeterVault.Infrastructure.Persistence.MeterVaultDbContext> DbFactory
@inject ISnackbar Snackbar
@inject IDialogService DialogService
@inject NavigationManager Nav
@inject InstanceClock Clock
@inject AnalysisPeriods Periods
@inject AnalysisReader Reader
@inject MeterVault.Infrastructure.Analysis.VirtualMeterService VirtualMeters
@inject NavState NavState
@inject ILogger<Meters> Logger
@implements IDisposable
@* Every meter (brief §7.3, §3.2): the shared meter list, grouped by energy type with a type filter and a search, each
meter with what it measured in the chosen period — a calculated meter by its formula, a meter without data in words —
and how it counts. Names open the meter's Analysis tab for the same period; the quick entry, edit and delete stay
one click away. Deleting names the calculated meters that depend on the meter first (D-33). *@
<PageHeader Title="@S.Nav_Meters" Description="@S.Meters_Description">
<Breadcrumbs>
<AnalysisBreadcrumbs Query="_query" Current="@S.Nav_Meters" />
</Breadcrumbs>
<Actions>
<MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" OnClick="@(() => _editor!.OpenNewAsync())">
@S.Meters_AddMeter
</MudButton>
</Actions>
</PageHeader>
@if (_query is not null)
{
<PeriodToolbar Query="_query" Period="_state.Value?.Period" Defaults="AnalysisDefaults.History" QueryChanged="OnQueryChanged"
ShowBucket="false" ShowComparison="false" Class="mb-3" />
}
<LoadPanel State="_state" OnRetry="Retry" Context="list" PlaceholderHeight="320">
<MudPaper Outlined="true" Elevation="0" Class="pa-2 pa-sm-4">
<MeterList Rows="list.Rows" Query="_query" GroupByType="true" ShowTypeFilter="true"
OnEdit="@(id => _editor!.OpenAsync(id))" OnDelete="DeleteAsync">
<EmptyContent>
<MudAlert Severity="Severity.Info">
@S.Meters_EmptyBefore <MudLink Href="/import">@S.Nav_Import</MudLink> @S.Meters_EmptyAfter
</MudAlert>
</EmptyContent>
</MeterList>
</MudPaper>
</LoadPanel>
<MeterEditor @ref="_editor" Saved="OnSavedAsync" SwapInsteadRequested="@(id => Nav.NavigateTo(MeterLinks.Event(id, MeterEventType.MeterSwap)))" />
@code {
private readonly LoadSequencer _loads = new();
private readonly LoadState<MeterListState> _state = new();
private AnalysisQuery? _query;
private MeterEditor? _editor;
/// <summary>What the list shows for one period: the resolved period and a row per meter.</summary>
private sealed record MeterListState(ResolvedPeriod Period, IReadOnlyList<MeterListRow> Rows);
protected override void OnInitialized() => Nav.LocationChanged += OnLocationChanged;
protected override Task OnParametersSetAsync() => SyncAsync();
private void OnLocationChanged(object? sender, LocationChangedEventArgs e) => _ = InvokeAsync(async () =>
{
// Only this page's own address: a link away fires this too, just before the page goes.
var path = Nav.ToBaseRelativePath(e.Location);
var end = path.IndexOfAny(['?', '#']);
if (!string.Equals((end >= 0 ? path[..end] : path).TrimEnd('/'), "meters", StringComparison.OrdinalIgnoreCase))
{
return;
}
await SyncAsync();
StateHasChanged();
});
private async Task SyncAsync()
{
var query = AnalysisQuery.Parse(Nav.Uri, AnalysisDefaults.History);
if (query == _query)
{
return;
}
_query = query;
await LoadAsync(query);
}
private Task Retry() => _query is null ? Task.CompletedTask : LoadAsync(_query);
private Task LoadAsync(AnalysisQuery query) => _loads.RunAsync(_state, token => ReadAsync(query, token), Logger);
/// <summary>
/// The meters and their period totals: one portfolio read with every meter's own series, in year buckets — only the
/// totals are shown, and they do not depend on the buckets — without a comparison.
/// </summary>
private async Task<MeterListState> ReadAsync(AnalysisQuery query, CancellationToken token)
{
var period = await Periods.ResolveAsync(query.WithMetric(null).WithScope(QueryScope.Portfolio), Clock.Now, token);
List<MeterFacts> meters;
await using (var db = await DbFactory.CreateDbContextAsync(token))
{
meters = await MeterFacts.LoadAsync(db, null, token);
}
AnalysisResult? result = null;
if (meters.Count > 0)
{
var request = new AnalysisRequest(AnalysisScope.Portfolio, period) { Bucket = BucketSize.Year, IncludeMeterSeries = true };
result = await Reader.ReadAsync(request, token);
}
return new MeterListState(period, MeterListRows.Build(meters, result));
}
private void OnQueryChanged(AnalysisQuery query) => AnalysisNavigation.Replace(Nav, query, AnalysisDefaults.History);
/// <summary>A new meter goes straight to its own page, where adding readings or a source is the next step.</summary>
private async Task OnSavedAsync((int MeterId, bool Created) saved)
{
if (saved.Created)
{
Nav.NavigateTo(MeterLinks.Detail(saved.MeterId));
return;
}
await Retry();
}
private async Task DeleteAsync(MeterFacts meter)
{
await using var db = await DbFactory.CreateDbContextAsync();
var readings = await db.Readings.CountAsync(r => r.MeterId == meter.Id);
var consumption = await db.Consumption.CountAsync(c => c.MeterId == meter.Id);
var message = readings + consumption > 0
? Loc.F(S.Meters_DeleteConfirmWithData, meter.Name, readings, consumption)
: Loc.F(S.Meters_DeleteConfirm, meter.Name);
// Virtual meters whose formula reads this one break with it (D-33): name them before anything is deleted.
var dependents = await VirtualMeters.GetDependentsAsync(meter.Id);
if (dependents.Count > 0)
{
message += " " + Loc.F(S.Meters_DeleteVirtualDependents, string.Join(", ", dependents.Select(d => d.Name)));
}
if (!await Confirm.DeleteAsync(DialogService, S.Meters_DeleteTitle, message))
{
return;
}
// Readings and consumption first (restricted keys), and its meter-scoped prices, which no key ties to it;
// events, sources, tank and members cascade.
await MeterVault.Infrastructure.Persistence.EntityDeletion.DeleteMeterAsync(db, meter.Id);
Snackbar.Add(S.Common_Deleted, Severity.Success);
NavState.NotifyMetersChanged();
await Retry();
}
public void Dispose()
{
Nav.LocationChanged -= OnLocationChanged;
_loads.Dispose();
}
}