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
@@ -6,14 +6,17 @@
@using Microsoft.EntityFrameworkCore
@using MudBlazor
<PageTitle>MeterVault — @S.Nav_EnergyTypes</PageTitle>
<PageTitle>MeterVault — @S.EnergyTypes_Title</PageTitle>
<div class="d-flex align-center justify-space-between mb-4 flex-wrap" style="gap:1rem">
<MudText Typo="Typo.h4">@S.Nav_EnergyTypes</MudText>
@* Configuration, not analysis: the menu's "Energy types" group opens each type's analysis, this page edits what a type
is. The title and the line below say which one the reader is on. *@
<div class="d-flex align-center justify-space-between mb-1 flex-wrap" style="gap:1rem">
<MudText Typo="Typo.h4" HtmlTag="h1">@S.EnergyTypes_Title</MudText>
<MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" OnClick="@(() => OpenEdit(null))">
@S.EnergyTypes_Add
</MudButton>
</div>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">@S.EnergyTypes_Description</MudText>
@if (_types is null)
{
@@ -162,11 +165,9 @@ else
return;
}
var target = await db.EnergyTypes.FirstOrDefaultAsync(t => t.Id == type.Id);
if (target is not null)
// Its type-scoped prices go with it: tariff.scope_id has no foreign key.
if (await MeterVault.Infrastructure.Persistence.EntityDeletion.DeleteEnergyTypeAsync(db, type.Id))
{
db.EnergyTypes.Remove(target);
await db.SaveChangesAsync();
Snackbar.Add(S.Common_Deleted, Severity.Success);
NavState.NotifyEnergyTypesChanged();
}
+144 -9
View File
@@ -1,10 +1,17 @@
@page "/admin/settings"
@using System.Text.Json
@using Microsoft.EntityFrameworkCore
@using MeterVault.Infrastructure.Analysis
@using MeterVault.Infrastructure.Normalization
@using MeterVault.Infrastructure.Persistence
@inject Microsoft.Extensions.Options.IOptions<MeterVault.Infrastructure.Options.MeterVaultOptions> Options
@inject IDbContextFactory<MeterVaultDbContext> DbFactory
@inject AnalysisReader Reader
@inject InstanceCurrency Currency
@inject ILogger<Settings> Logger
@using MudBlazor
<PageTitle>MeterVault — @S.Nav_Settings</PageTitle>
<MudText Typo="Typo.h4" Class="mb-2">@S.Nav_Settings</MudText>
<PageHeader Title="@S.Nav_Settings" Class="mb-2" />
<MudAlert Severity="Severity.Info" Class="mb-4" Dense="true">
@S.Settings_EffectiveLead <b>@S.Settings_EffectiveEmphasis</b> @S.Settings_EffectiveRest
(<code>MeterVault__Key</code> / <code>Section__Key</code>) @S.Settings_EffectiveTail
@@ -16,13 +23,20 @@
<MudText Typo="Typo.h6" Class="mb-2">@S.Settings_LocaleAndTime</MudText>
<MudSimpleTable Dense="true">
<tbody>
<tr><td>@S.Settings_Timezone</td><td style="text-align:right"><code>@_o.TimeZone</code></td></tr>
<tr><td>@S.Settings_Timezone</td><td style="text-align:right"><code>@Reader.Zone.Id</code></td></tr>
<tr><td>@S.Settings_Locale</td><td style="text-align:right"><code>@_o.Locale</code></td></tr>
<tr><td>@S.Common_Currency</td><td style="text-align:right"><code>@_o.Currency</code></td></tr>
<tr><td>@S.Settings_RawRetention</td><td style="text-align:right">@Loc.F(S.Settings_RetentionDays, _o.RawRetentionDays)</td></tr>
<tr><td>@S.Common_Currency</td><td style="text-align:right"><code>@Currency.Code</code> (@Currency.Symbol)</td></tr>
<tr>
<td>@S.Settings_RawRetention</td>
<td style="text-align:right">
@* D-57: every recompute rebuilds a meter from its readings, so deleting old ones would erase history. *@
<MudChip T="string" Size="Size.Small" Color="Color.Default" Variant="Variant.Outlined">@S.Settings_RetentionNotEnforced</MudChip>
</td>
</tr>
</tbody>
</MudSimpleTable>
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mt-2">
<MudText Typo="Typo.caption" Class="mv-muted d-block mt-2">@Loc.F(S.Settings_RetentionReason, _o.RawRetentionDays)</MudText>
<MudText Typo="Typo.caption" Class="mv-muted mt-2">
@S.Settings_EnvKeysLabel <code>MeterVault__TimeZone</code>, <code>MeterVault__Locale</code>,
<code>MeterVault__Currency</code>, <code>MeterVault__RawRetentionDays</code>.
</MudText>
@@ -56,16 +70,137 @@
<tr><td>@S.Settings_SeedReferenceData</td><td style="text-align:right">@(_o.SeedReferenceData ? S.Settings_On : S.Settings_Off)</td></tr>
</tbody>
</MudSimpleTable>
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mt-2">
<MudText Typo="Typo.caption" Class="mv-muted mt-2">
@S.Settings_ApiKeysHintBefore <code>MeterVault__ApiKeys__0</code>. @S.Settings_ApiKeysHintAfter
@S.Settings_ApiDocsLabel <MudLink Href="/swagger" Target="_blank">/swagger</MudLink>.
</MudText>
</MudPaper>
</MudItem>
<MudItem xs="12">
<MudPaper Class="pa-4" Elevation="2">
<MudText Typo="Typo.h6" Class="mb-2">@S.Settings_AnalysisData</MudText>
@if (_analysis is { } state)
{
<MudSimpleTable Dense="true">
<tbody>
<tr><td>@S.Settings_NormalizationRevision</td><td style="text-align:right">@RevisionText(state)</td></tr>
<tr><td>@S.Settings_NormalizationZone</td><td style="text-align:right">@ZoneText(state)</td></tr>
<tr>
<td>@S.Settings_MetersCurrent</td>
<td style="text-align:right">
@Loc.F(S.Settings_MetersCurrentValue, state.CurrentMeters, state.PhysicalMeters)
@if (state.PhysicalMeters > state.CurrentMeters)
{
<span class="mv-muted"> · @Loc.F(S.Settings_MetersPending, state.PhysicalMeters - state.CurrentMeters)</span>
}
</td>
</tr>
@if (state.Retry.Count > 0)
{
<tr><td>@S.Settings_RebuildRetry</td><td style="text-align:right">@string.Join(", ", state.Retry)</td></tr>
}
<tr><td>@S.Settings_VirtualMeters</td><td style="text-align:right">@VirtualText(state)</td></tr>
</tbody>
</MudSimpleTable>
}
else if (_analysisFailed)
{
<MudAlert Severity="Severity.Warning" Dense="true">@S.Settings_AnalysisUnavailable</MudAlert>
}
<MudText Typo="Typo.caption" Class="mv-muted d-block mt-2">@S.Settings_AnalysisHelp</MudText>
</MudPaper>
</MudItem>
</MudGrid>
@code {
private MeterVault.Infrastructure.Options.MeterVaultOptions _o = new();
private AnalysisState? _analysis;
private bool _analysisFailed;
protected override void OnInitialized() => _o = Options.Value;
/// <summary>What the analysis data is built with (D-16) and how the calculated meters stand (D-26, D-28).</summary>
private sealed record AnalysisState(
int? Revision,
string? Zone,
int PhysicalMeters,
int CurrentMeters,
IReadOnlyList<string> Retry,
IReadOnlyList<(VirtualMeterStatus Status, int Count)> Virtual);
protected override async Task OnInitializedAsync()
{
_o = Options.Value;
try
{
_analysis = await LoadAnalysisStateAsync();
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// The settings themselves are configuration and always show; only this read-out depends on the database.
Logger.LogWarning(ex, "Could not read the analysis data state");
_analysisFailed = true;
}
}
private async Task<AnalysisState> LoadAnalysisStateAsync()
{
await using var db = await DbFactory.CreateDbContextAsync();
var settings = await db.AppSettings.AsNoTracking()
.Where(s => s.Key == NormalizationUpgrade.SettingKey || s.Key == NormalizationUpgrade.ZoneSettingKey || s.Key == NormalizationUpgrade.PendingSettingKey)
.ToDictionaryAsync(s => s.Key, s => s.Value);
var catalog = await Reader.LoadCatalogAsync();
var physical = catalog.Meters.Values.Where(m => !m.IsVirtual).ToList();
var retryIds = Read<int[]>(settings, NormalizationUpgrade.PendingSettingKey) ?? [];
var virtualStates = catalog.Meters.Values
.Where(m => m.IsVirtual)
.GroupBy(m => m.VirtualStatus ?? VirtualMeterStatus.NeedsConfiguration)
.OrderBy(g => g.Key)
.Select(g => (g.Key, g.Count()))
.ToList();
return new AnalysisState(
Read<int?>(settings, NormalizationUpgrade.SettingKey),
Read<string>(settings, NormalizationUpgrade.ZoneSettingKey),
physical.Count,
physical.Count(m => !m.IsPending),
[.. retryIds.Select(id => catalog.Find(id)?.Name ?? $"#{id}")],
virtualStates);
}
private static T? Read<T>(IReadOnlyDictionary<string, string> settings, string key)
{
if (!settings.TryGetValue(key, out var json))
{
return default;
}
try
{
return JsonSerializer.Deserialize<T>(json);
}
catch (JsonException)
{
return default;
}
}
private static string RevisionText(AnalysisState state) => state.Revision switch
{
null => S.Settings_RevisionNone,
var revision when revision < NormalizationUpgrade.CurrentRevision =>
Loc.F(S.Settings_RevisionOutdated, revision, NormalizationUpgrade.CurrentRevision),
var revision => Loc.F(S.Settings_RevisionValue, revision),
};
private string ZoneText(AnalysisState state) => state.Zone switch
{
null => S.Settings_RevisionNone,
var zone when !string.Equals(zone, Reader.Zone.Id, StringComparison.Ordinal) => Loc.F(S.Settings_ZoneDiffers, zone),
var zone => zone,
};
private static string VirtualText(AnalysisState state) => state.Virtual.Count == 0
? S.Settings_None
: string.Join(" · ", state.Virtual.Select(v => $"{v.Status.Display()}: {v.Count}"));
}
+297 -43
View File
@@ -1,18 +1,37 @@
@page "/admin/tariffs"
@inject Microsoft.EntityFrameworkCore.IDbContextFactory<MeterVault.Infrastructure.Persistence.MeterVaultDbContext> DbFactory
@inject ISnackbar Snackbar
@inject IDialogService DialogService
@using Microsoft.EntityFrameworkCore
@using MudBlazor
@using MeterVault.App.TariffEditing
@using MeterVault.Core.Analysis.Quantities
@using MeterVault.Infrastructure.Analysis
@inject Microsoft.EntityFrameworkCore.IDbContextFactory<MeterVault.Infrastructure.Persistence.MeterVaultDbContext> DbFactory
@inject AnalysisReader Reader
@inject InstanceCurrency Currency
@inject InstanceClock Clock
@inject NavigationManager Nav
@inject ISnackbar Snackbar
@inject IDialogService DialogService
@inject ILogger<Tariffs> Logger
<PageTitle>MeterVault — @S.Nav_Tariffs</PageTitle>
<PageHeader Title="@S.Nav_Tariffs" Description="@S.Tariffs_Description" Class="mb-1">
<Actions>
<MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" OnClick="@(() => OpenEdit(null))">
@S.Tariffs_AddTariff
</MudButton>
</Actions>
</PageHeader>
<MudText Typo="Typo.caption" Class="mv-muted d-block mb-3">@S.Tariffs_NotAppliedNote</MudText>
<div class="d-flex align-center justify-space-between mb-4 flex-wrap" style="gap:1rem">
<MudText Typo="Typo.h4">@S.Nav_Tariffs</MudText>
<MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" OnClick="@(() => OpenEdit(null))">
@S.Tariffs_AddTariff
</MudButton>
</div>
@if (_link.HasScope)
{
@* D-52: a link from a missing-cost explanation scopes the list to what can price that meter or type. *@
<MudAlert Severity="Severity.Info" Dense="true" Class="mb-3">
<div class="d-flex flex-wrap align-center" style="gap:0.25rem 1rem">
<span>@FilterText</span>
<MudButton Variant="Variant.Text" Size="Size.Small" Color="Color.Primary" OnClick="ShowAll">@S.Tariffs_ShowAll</MudButton>
</div>
</MudAlert>
}
@if (_tariffs is null)
{
@@ -20,7 +39,8 @@
}
else
{
<MudTable Items="_tariffs" Dense="true" Hover="true" Elevation="2">
var shown = _tariffs.Where(t => _link.Lists(t, MeterEnergyType)).ToList();
<MudTable Items="shown" Dense="true" Hover="true" Elevation="2">
<HeaderContent>
<MudTh>@S.Common_Scope</MudTh>
<MudTh>@S.Tariffs_Component</MudTh>
@@ -32,14 +52,30 @@ else
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="@S.Common_Scope">@ScopeLabel(context)</MudTd>
<MudTd DataLabel="@S.Tariffs_Component">@context.Component.Display()</MudTd>
<MudTd DataLabel="@S.Tariffs_Component">
@context.Component.Display()
@if (IsNotApplied(context.Component))
{
<MudChip T="string" Size="Size.Small" Variant="Variant.Outlined" Class="ml-1">@S.Tariffs_NotAppliedChip</MudChip>
}
</MudTd>
<MudTd DataLabel="@S.Common_Value">@Format.Number(context.Value, 4)</MudTd>
<MudTd DataLabel="@S.Common_Unit">@context.Unit</MudTd>
<MudTd DataLabel="@S.Tariffs_ValidFrom">@context.ValidFrom.ToString("yyyy-MM-dd")</MudTd>
<MudTd DataLabel="@S.Tariffs_ValidTo">@(context.ValidTo?.ToString("yyyy-MM-dd") ?? S.Tariffs_OpenEnded)</MudTd>
<MudTd DataLabel="@S.Common_Unit">
@context.Unit
@if (RowIssue(context) is { } issue)
{
<MudTooltip Text="@issue.Text">
<MudIcon Icon="@(issue.IsError ? Icons.Material.Filled.ErrorOutline : Icons.Material.Filled.WarningAmber)"
Color="@(issue.IsError ? Color.Error : Color.Warning)" Size="Size.Small" Class="ml-1"
Style="vertical-align:middle" aria-label="@issue.Text" />
</MudTooltip>
}
</MudTd>
<MudTd DataLabel="@S.Tariffs_ValidFrom" Style="white-space:nowrap">@Format.Date(context.ValidFrom)</MudTd>
<MudTd DataLabel="@S.Tariffs_ValidTo" Style="white-space:nowrap">@(_effectiveEnds.GetValueOrDefault(context.Id) is { } until ? Format.Date(until) : S.Tariffs_OpenEnded)</MudTd>
<MudTd DataLabel="@S.Common_Actions" Style="text-align:right">
<MudIconButton Icon="@Icons.Material.Filled.Edit" Size="Size.Small" OnClick="@(() => OpenEdit(context))" />
<MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small" Color="Color.Error" OnClick="@(() => DeleteAsync(context))" />
<MudIconButton Icon="@Icons.Material.Filled.Edit" Size="Size.Small" OnClick="@(() => OpenEdit(context))" aria-label="@S.Tariffs_EditTariff" />
<MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small" Color="Color.Error" OnClick="@(() => DeleteAsync(context))" aria-label="@S.Tariffs_DeleteTitle" />
</MudTd>
</RowTemplate>
</MudTable>
@@ -47,6 +83,10 @@ else
{
<MudAlert Severity="Severity.Info" Class="mt-4">@S.Tariffs_EmptyState <MudLink Href="/import">@S.Nav_Import</MudLink>.</MudAlert>
}
else if (shown.Count == 0)
{
<MudAlert Severity="Severity.Info" Class="mt-4">@S.Tariffs_FilterEmpty</MudAlert>
}
}
<MudDialog @bind-Visible="_editOpen" Options="_dialogOptions">
@@ -54,7 +94,7 @@ else
<MudText Typo="Typo.h6">@(_working.Id == 0 ? S.Tariffs_NewTariff : S.Tariffs_EditTariff)</MudText>
</TitleContent>
<DialogContent>
<MudSelect T="TariffScope" @bind-Value="_working.ScopeType" Label="@S.Common_Scope" Class="mb-2">
<MudSelect T="TariffScope" Value="_working.ScopeType" ValueChanged="SetScope" Label="@S.Common_Scope" Class="mb-2">
@foreach (var scope in Enum.GetValues<TariffScope>())
{
<MudSelectItem T="TariffScope" Value="scope">@scope.Display()</MudSelectItem>
@@ -62,7 +102,7 @@ else
</MudSelect>
@if (_working.ScopeType == TariffScope.EnergyType)
{
<MudSelect T="int?" @bind-Value="_working.ScopeId" Label="@S.Common_EnergyType" Class="mb-2">
<MudSelect T="int?" Value="_working.ScopeId" ValueChanged="SetScopeId" Label="@S.Common_EnergyType" Class="mb-2">
@foreach (var t in _energyTypes)
{
<MudSelectItem T="int?" Value="@((int?)t.Id)">@t.DisplayName</MudSelectItem>
@@ -71,21 +111,32 @@ else
}
else if (_working.ScopeType == TariffScope.Meter)
{
<MudSelect T="int?" @bind-Value="_working.ScopeId" Label="@S.Common_Meter" Class="mb-2">
<MudSelect T="int?" Value="_working.ScopeId" ValueChanged="SetScopeId" Label="@S.Common_Meter" Class="mb-2">
@foreach (var m in _meters)
{
<MudSelectItem T="int?" Value="@((int?)m.Id)">@m.Name</MudSelectItem>
}
</MudSelect>
}
<MudSelect T="TariffComponent" @bind-Value="_working.Component" Label="@S.Tariffs_Component" Class="mb-2">
<MudSelect T="TariffComponent" Value="_working.Component" ValueChanged="SetComponent" Label="@S.Tariffs_Component" Class="mb-2">
@foreach (var component in Enum.GetValues<TariffComponent>())
{
<MudSelectItem T="TariffComponent" Value="component">@component.Display()</MudSelectItem>
}
</MudSelect>
<MudNumericField T="double" @bind-Value="_working.Value" Label="@S.Common_Value" Format="0.####" Class="mb-2" />
<MudTextField @bind-Value="_working.Unit" Label="@S.Tariffs_UnitLabel" Required="true" Class="mb-2" />
@* D-38: a new tariff starts without a value, and saving needs one; a typed 0 is a deliberate free price, said so. *@
<MudNumericField T="double?" @bind-Value="_working.Value" Label="@S.Common_Value" Format="0.####" Class="mb-2"
Required="true" RequiredError="@S.Tariffs_ValueRequired" Immediate="true"
HelperText="@(_working.Value is null ? null : TariffValue.Note(ValueVerdict))" />
<MudTextField T="string" Value="_working.Unit" ValueChanged="SetUnit" Label="@S.Tariffs_UnitLabel" Required="true"
Immediate="true" DebounceInterval="300" Class="mb-1" />
@* D-37: how the unit was read and whether it fits what this tariff would price, before it is saved. *@
<div class="mb-3" aria-live="polite">
@foreach (var (isError, text) in TariffUnitCheck.Describe(Verdict, Currency.Code))
{
<MudText Typo="Typo.caption" Color="@(isError ? Color.Error : Color.Default)" Class="@(isError ? "d-block" : "d-block mv-muted")">@text</MudText>
}
</div>
<MudTextField @bind-Value="_working.Currency" Label="@S.Common_Currency" Class="mb-2" />
<MudDatePicker @bind-Date="_working.ValidFrom" Label="@S.Tariffs_ValidFrom" Class="mb-2" />
<MudDatePicker @bind-Date="_working.ValidTo" Label="@S.Tariffs_ValidToLabel" Clearable="true" Class="mb-2" />
@@ -99,20 +150,104 @@ else
@code {
private List<Tariff>? _tariffs;
private IReadOnlyDictionary<int, DateOnly?> _effectiveEnds = new Dictionary<int, DateOnly?>();
private List<EnergyType> _energyTypes = [];
private List<Meter> _meters = [];
private AnalysisCatalog? _catalog;
private bool _editOpen;
private EditModel _working = new();
private readonly DialogOptions _dialogOptions = new() { MaxWidth = MaxWidth.Small, FullWidth = true };
private TariffDeepLink _link = TariffDeepLink.None;
/// <summary>A new-tariff request from the link, held until the action has been dropped from the address.</summary>
private TariffDeepLink? _pendingNew;
private bool _droppingAction;
[SupplyParameterFromQuery(Name = TariffLinks.ParamScope)]
public string? ScopeParam { get; set; }
[SupplyParameterFromQuery(Name = TariffLinks.ParamId)]
public string? IdParam { get; set; }
[SupplyParameterFromQuery(Name = TariffLinks.ParamComponent)]
public string? ComponentParam { get; set; }
[SupplyParameterFromQuery(Name = TariffLinks.ParamFrom)]
public string? FromParam { get; set; }
/// <summary>A dialog to open once the page is interactive (<c>new</c>); dropped from the address when consumed.</summary>
[SupplyParameterFromQuery(Name = TariffLinks.ParamAction)]
public string? Action { get; set; }
protected override Task OnInitializedAsync() => LoadAsync();
protected override void OnParametersSet()
{
_link = TariffDeepLink.Parse(ScopeParam, IdParam, ComponentParam, FromParam, Action);
if (_link.OpenNew)
{
_pendingNew = _link;
}
else if (string.IsNullOrEmpty(Action))
{
_droppingAction = false;
}
}
/// <summary>
/// Opens the deep-linked new-tariff dialog once the page is interactive (D-52). As on a meter's page, the action is
/// dropped from the address first and the dialog opened when that navigation has come back: a circuit's first
/// location change would otherwise dismiss the dialog, and a reload must not reopen it. The scope stays in the
/// address, so the list stays scoped.
/// </summary>
protected override void OnAfterRender(bool firstRender)
{
if (_pendingNew is not { } request || _tariffs is null)
{
return;
}
if (!string.IsNullOrEmpty(Action))
{
if (!_droppingAction)
{
_droppingAction = true;
Nav.NavigateTo(Nav.GetUriWithQueryParameters(new Dictionary<string, object?>
{
[TariffLinks.ParamAction] = null,
[TariffLinks.ParamComponent] = null,
[TariffLinks.ParamFrom] = null,
}), replace: true);
}
return;
}
_pendingNew = null;
OpenNew(request);
StateHasChanged();
}
private async Task LoadAsync()
{
await using var db = await DbFactory.CreateDbContextAsync();
_tariffs = await db.Tariffs.AsNoTracking().OrderBy(t => t.Component).ThenBy(t => t.ValidFrom).ToListAsync();
_effectiveEnds = TariffValidity.EffectiveEnds(
_tariffs.Select(t => new TariffSpan(t.Id, t.ScopeType, t.ScopeId, t.Component, t.ValidFrom, t.ValidTo)));
_energyTypes = await db.EnergyTypes.AsNoTracking().OrderBy(t => t.DisplayName).ToListAsync();
_meters = await db.Meters.AsNoTracking().OrderBy(m => m.Name).ToListAsync();
try
{
_catalog = await Reader.LoadCatalogAsync();
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// Without it the unit is still parsed; only the check against the scope's units is skipped.
Logger.LogWarning(ex, "Could not load the meter catalog for the tariff unit check");
_catalog = null;
}
}
private string ScopeLabel(Tariff t) => t.ScopeType switch
@@ -123,26 +258,124 @@ else
_ => t.ScopeType.ToString(),
};
private string FilterText => _link.Scope switch
{
TariffScope.Meter => Loc.F(S.Tariffs_FilterMeter, _meters.FirstOrDefault(m => m.Id == _link.ScopeId)?.Name ?? $"#{_link.ScopeId}"),
TariffScope.EnergyType => Loc.F(S.Tariffs_FilterType, _energyTypes.FirstOrDefault(t => t.Id == _link.ScopeId)?.DisplayName ?? $"#{_link.ScopeId}"),
_ => S.Tariffs_FilterGlobal,
};
private int? MeterEnergyType(int meterId) => _meters.FirstOrDefault(m => m.Id == meterId)?.EnergyTypeId;
private static bool IsNotApplied(TariffComponent component) =>
component is TariffComponent.Bonus or TariffComponent.Discount or TariffComponent.Tax;
private void ShowAll() => Nav.NavigateTo(TariffLinks.Path);
/// <summary>What a tariff of this scope and component would price, by unit (D-20, D-34).</summary>
private IReadOnlyList<TariffUnitTarget> TargetsFor(TariffScope scope, int? scopeId, TariffComponent component) =>
_catalog is null
? []
: TariffUnitCheck.TargetsFor(_catalog, scope, scopeId, component, id =>
_energyTypes.FirstOrDefault(t => t.Id == id) is { } type ? (type.DisplayName, type.BaseUnit) : null);
private TariffUnitVerdict Verdict => TariffUnitCheck.Check(
_working.Unit, _working.Component, TargetsFor(_working.ScopeType, _working.ScopeId, _working.Component), Currency.Code);
/// <summary>A stored tariff whose unit would be refused or warned about now, with the first line that says why.</summary>
private (bool IsError, string Text)? RowIssue(Tariff tariff)
{
var verdict = TariffUnitCheck.Check(tariff.Unit, tariff.Component, TargetsFor(tariff.ScopeType, tariff.ScopeId, tariff.Component), Currency.Code);
if (verdict.Kind is TariffUnitVerdictKind.Fits or TariffUnitVerdictKind.NotApplied)
{
return null;
}
var lines = TariffUnitCheck.Describe(verdict, Currency.Code);
var reason = lines.FirstOrDefault(l => l.IsError);
return reason.Text is null ? (false, lines[^1].Text) : (true, reason.Text);
}
private void OpenEdit(Tariff? tariff)
{
_working = tariff is null
? new EditModel { ValidFrom = DateTime.Today }
: new EditModel
{
Id = tariff.Id,
ScopeType = tariff.ScopeType,
ScopeId = tariff.ScopeId,
Component = tariff.Component,
Value = tariff.Value,
Unit = tariff.Unit,
Currency = tariff.Currency,
ValidFrom = tariff.ValidFrom.ToDateTime(TimeOnly.MinValue),
ValidTo = tariff.ValidTo?.ToDateTime(TimeOnly.MinValue),
Notes = tariff.Notes,
};
if (tariff is null)
{
OpenNew(TariffDeepLink.None with { Scope = _link.Scope, ScopeId = _link.ScopeId });
return;
}
_working = new EditModel
{
Id = tariff.Id,
ScopeType = tariff.ScopeType,
ScopeId = tariff.ScopeId,
Component = tariff.Component,
Value = tariff.Value,
Unit = tariff.Unit,
UnitTouched = true,
Currency = tariff.Currency,
ValidFrom = tariff.ValidFrom.ToDateTime(TimeOnly.MinValue),
ValidTo = tariff.ValidTo?.ToDateTime(TimeOnly.MinValue),
Notes = tariff.Notes,
};
_editOpen = true;
}
/// <summary>A new tariff, prefilled from a link (D-52): its scope, component and first month, and a unit that fits.</summary>
private void OpenNew(TariffDeepLink request)
{
_working = new EditModel
{
ScopeType = request.Scope ?? TariffScope.EnergyType,
ScopeId = request.Scope == TariffScope.Global ? null : request.ScopeId,
Component = request.Component ?? TariffComponent.UnitPrice,
Currency = Currency.Code,
ValidFrom = (request.From ?? Clock.Today).ToDateTime(TimeOnly.MinValue),
};
SuggestUnit();
_editOpen = true;
}
/// <summary>A unit nobody typed follows the scope and component: currency per the priced unit, or per month.</summary>
private void SuggestUnit()
{
if (_working.UnitTouched)
{
return;
}
var target = TargetsFor(_working.ScopeType, _working.ScopeId, _working.Component).FirstOrDefault();
_working.Unit = TariffUnit.Suggest(_working.Component, target?.Unit ?? (_working.Component is TariffComponent.UnitPrice or TariffComponent.FeedIn ? "kWh" : null), Currency.Code);
}
private void SetScope(TariffScope scope)
{
_working.ScopeType = scope;
_working.ScopeId = null;
SuggestUnit();
}
private void SetScopeId(int? id)
{
_working.ScopeId = id;
SuggestUnit();
}
private void SetComponent(TariffComponent component)
{
_working.Component = component;
SuggestUnit();
}
private void SetUnit(string? unit)
{
_working.Unit = unit ?? "";
_working.UnitTouched = true;
}
/// <summary>What the value field holds, for the save guard and the note under it (D-38).</summary>
private TariffValueVerdict ValueVerdict => TariffValue.Check(_working.Value, _working.Component);
private async Task SaveAsync()
{
if (string.IsNullOrWhiteSpace(_working.Unit) || _working.ValidFrom is null)
@@ -157,7 +390,22 @@ else
return;
}
// D-38: an untouched value is not a price. Without this, the missing-price deep link would save a free period.
if (ValueVerdict.BlocksSave())
{
Snackbar.Add(S.Tariffs_ValueRequired, Severity.Warning);
return;
}
// D-37: a unit that is read and does not fit would leave the cost "unavailable (unit)"; refuse it here instead.
if (Verdict.Blocks)
{
Snackbar.Add(S.Tariffs_UnitBlocked, Severity.Warning);
return;
}
var scopeId = _working.ScopeType == TariffScope.Global ? null : _working.ScopeId;
var value = _working.Value!.Value;
await using var db = await DbFactory.CreateDbContextAsync();
if (_working.Id == 0)
@@ -167,9 +415,9 @@ else
ScopeType = _working.ScopeType,
ScopeId = scopeId,
Component = _working.Component,
Value = _working.Value,
Value = value,
Unit = _working.Unit.Trim(),
Currency = string.IsNullOrWhiteSpace(_working.Currency) ? "EUR" : _working.Currency.Trim(),
Currency = string.IsNullOrWhiteSpace(_working.Currency) ? Currency.Code : _working.Currency.Trim(),
ValidFrom = DateOnly.FromDateTime(_working.ValidFrom.Value),
ValidTo = _working.ValidTo is { } to ? DateOnly.FromDateTime(to) : null,
Notes = string.IsNullOrWhiteSpace(_working.Notes) ? null : _working.Notes,
@@ -181,9 +429,9 @@ else
existing.ScopeType = _working.ScopeType;
existing.ScopeId = scopeId;
existing.Component = _working.Component;
existing.Value = _working.Value;
existing.Value = value;
existing.Unit = _working.Unit.Trim();
existing.Currency = string.IsNullOrWhiteSpace(_working.Currency) ? "EUR" : _working.Currency.Trim();
existing.Currency = string.IsNullOrWhiteSpace(_working.Currency) ? Currency.Code : _working.Currency.Trim();
existing.ValidFrom = DateOnly.FromDateTime(_working.ValidFrom.Value);
existing.ValidTo = _working.ValidTo is { } to ? DateOnly.FromDateTime(to) : null;
existing.Notes = string.IsNullOrWhiteSpace(_working.Notes) ? null : _working.Notes;
@@ -221,8 +469,14 @@ else
public TariffScope ScopeType { get; set; } = TariffScope.EnergyType;
public int? ScopeId { get; set; }
public TariffComponent Component { get; set; } = TariffComponent.UnitPrice;
public double Value { get; set; }
/// <summary>The price; null until one is typed (a new tariff never defaults to a free 0, D-38).</summary>
public double? Value { get; set; }
public string Unit { get; set; } = "EUR/kWh";
/// <summary>True once the user typed a unit (or it is a stored tariff's): it is no longer re-suggested.</summary>
public bool UnitTouched { get; set; }
public string Currency { get; set; } = "EUR";
public DateTime? ValidFrom { get; set; }
public DateTime? ValidTo { get; set; }