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
@@ -0,0 +1,281 @@
using MeterVault.Core.Analysis;
using MeterVault.Core.Analysis.Costing;
using MeterVault.Core.Analysis.Virtual;
using MeterVault.Core.Domain;
using MeterVault.Core.Normalization;
using MeterVault.Infrastructure.Analysis;
using MeterVault.Infrastructure.Costing;
using MeterVault.Infrastructure.Normalization;
using MeterVault.Infrastructure.Options;
using MeterVault.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
namespace MeterVault.Integration.Tests.Costing;
/// <summary>
/// Builds what a cost test prices — its own energy types, meters with readings normalized in Berlin, tariffs, manual
/// costs and categories — on a frozen clock of 19 September 2026, 14:37 Berlin, and removes all of it again.
/// </summary>
internal sealed class CostSandbox(TimescaleFixture fx) : IAsyncDisposable
{
public const string BerlinId = "Europe/Berlin";
public static readonly TimeZoneInfo Berlin = TimeZoneInfo.FindSystemTimeZoneById(BerlinId);
/// <summary>The frozen "now" of every request (D-01), after the reference data ends (31 May 2026).</summary>
public static readonly DateTimeOffset Now = new DateTimeOffset(2026, 9, 19, 14, 37, 0, TimeSpan.FromHours(2)).ToUniversalTime();
private readonly List<int> _meters = [];
private readonly List<short> _types = [];
private readonly List<int> _tariffs = [];
private readonly List<int> _manualCosts = [];
private readonly List<int> _categories = [];
public TimescaleFixture Fixture => fx;
public static ResolvedPeriod Custom(DateOnly first, DateOnly last) => PeriodResolver.Resolve(PeriodPreset.Custom, first, last, Now, Berlin);
public static ResolvedPeriod Year(int year) => Custom(new DateOnly(year, 1, 1), new DateOnly(year, 12, 31));
public static ResolvedPeriod Month(int year, int month) =>
Custom(new DateOnly(year, month, 1), new DateOnly(year, month, DateTime.DaysInMonth(year, month)));
public static ResolvedPeriod Preset(PeriodPreset preset) => PeriodResolver.Resolve(preset, null, null, Now, Berlin);
public static DateTimeOffset Midnight(int year, int month, int day) => GapAttribution.LocalMidnight(new DateOnly(year, month, day), Berlin);
public static DateOnly D(int year, int month, int day) => new(year, month, day);
public CostReader Reader(string currency = "EUR")
{
var options = Microsoft.Extensions.Options.Options.Create(new MeterVaultOptions { TimeZone = BerlinId, Currency = currency });
return new CostReader(fx, new AnalysisReader(fx, options), options);
}
public async Task<short> TypeAsync(string unit = "kWh")
{
await using var db = fx.CreateContext();
var type = new EnergyType
{
Key = $"cost-{Guid.NewGuid():N}",
DisplayName = "Cost test",
BaseUnit = unit,
DefaultMode = MeterMode.CumulativeCounter,
};
db.EnergyTypes.Add(type);
await db.SaveChangesAsync();
_types.Add(type.Id);
return type.Id;
}
public async Task<int> MeterAsync(
short type, MeterMode mode, string unit, DateOnly? installedAt = null, string meta = "{}", DateOnly? retiredAt = null, string? name = null)
{
await using var db = fx.CreateContext();
var meter = new Meter
{
Name = name ?? $"cost-{Guid.NewGuid():N}",
EnergyTypeId = type,
Mode = mode,
Unit = unit,
InstalledAt = installedAt,
RetiredAt = retiredAt,
Meta = meta,
};
db.Meters.Add(meter);
await db.SaveChangesAsync();
_meters.Add(meter.Id);
return meter.Id;
}
/// <summary>
/// A counter installed on the 1st of <paramref name="firstMonth"/> whose consecutive local months book the given
/// amounts: one reading at each following local midnight of the 1st.
/// </summary>
public async Task<int> MonthlyAsync(short type, MeterMode mode, DateOnly firstMonth, params double[] months)
{
var meter = await MeterAsync(type, mode, "kWh", installedAt: firstMonth);
await MonthlyReadingsAsync(meter, firstMonth, months);
return meter;
}
/// <summary>Monthly readings on an existing meter, as <see cref="MonthlyAsync"/> writes them.</summary>
public async Task MonthlyReadingsAsync(int meter, DateOnly firstMonth, params double[] months)
{
var register = 0d;
var readings = new List<(DateTimeOffset, double)>();
for (var i = 0; i < months.Length; i++)
{
register += months[i];
var next = firstMonth.AddMonths(i + 1);
readings.Add((Midnight(next.Year, next.Month, 1), register));
}
await ReadingsAsync(meter, [.. readings]);
}
/// <summary>A counter installed on <paramref name="from"/> that rises by <paramref name="perDay"/> at every local midnight up to <paramref name="to"/>.</summary>
public async Task<int> DailyAsync(short type, DateOnly from, DateOnly to, double perDay)
{
var meter = await MeterAsync(type, MeterMode.CumulativeCounter, "kWh", installedAt: from);
var readings = new List<(DateTimeOffset, double)>();
var register = 0d;
for (var day = from.AddDays(1); day <= to; day = day.AddDays(1))
{
register += perDay;
readings.Add((Midnight(day.Year, day.Month, day.Day), register));
}
await ReadingsAsync(meter, [.. readings]);
return meter;
}
public async Task<int> VirtualAsync(short type, string expression, QuantityKind kind, string unit, VirtualCostRule rule, string meta = "{}")
{
meta = VirtualDefinitionJson.Write(meta, new VirtualDefinition(expression, kind, unit, rule));
var meter = await MeterAsync(type, MeterMode.Virtual, unit, meta: meta);
await RecomputeAsync(meter);
return meter;
}
public async Task LinkAsync(int from, int to)
{
await using var db = fx.CreateContext();
db.MeterLinks.Add(new MeterLink { FromMeterId = from, ToMeterId = to });
await db.SaveChangesAsync();
}
public async Task<int> TariffAsync(
TariffScope scope, int? scopeId, TariffComponent component, double value, string unit, DateOnly from, DateOnly? to = null)
{
await using var db = fx.CreateContext();
var tariff = new Tariff
{
ScopeType = scope,
ScopeId = scopeId,
Component = component,
Value = value,
Unit = unit,
ValidFrom = from,
ValidTo = to,
};
db.Tariffs.Add(tariff);
await db.SaveChangesAsync();
_tariffs.Add(tariff.Id);
return tariff.Id;
}
public Task<int> TypePriceAsync(short type, double value, DateOnly from, string unit = "EUR/kWh", DateOnly? to = null) =>
TariffAsync(TariffScope.EnergyType, type, TariffComponent.UnitPrice, value, unit, from, to);
public Task<int> MeterPriceAsync(int meter, double value, DateOnly from, string unit = "EUR/kWh") =>
TariffAsync(TariffScope.Meter, meter, TariffComponent.UnitPrice, value, unit, from);
public async Task<int> ManualCostAsync(DateOnly start, double amount, int? meterId = null, int? categoryId = null, string currency = "EUR")
{
await using var db = fx.CreateContext();
var cost = new ManualCost
{
MeterId = meterId,
CategoryId = categoryId,
PeriodStart = start,
PeriodEnd = start.AddMonths(1).AddDays(-1),
Amount = amount,
Currency = currency,
};
db.ManualCosts.Add(cost);
await db.SaveChangesAsync();
_manualCosts.Add(cost.Id);
return cost.Id;
}
public async Task<int> CategoryAsync(string name, int sort, int[]? meters = null, short[]? types = null)
{
await using var db = fx.CreateContext();
var category = new CostCategory { Name = name, Sort = sort };
foreach (var meter in meters ?? [])
{
category.Members.Add(new CostCategoryMember { MeterId = meter });
}
foreach (var type in types ?? [])
{
category.Members.Add(new CostCategoryMember { EnergyTypeId = type });
}
db.CostCategories.Add(category);
await db.SaveChangesAsync();
_categories.Add(category.Id);
return category.Id;
}
public async Task ReadingsAsync(int meterId, params (DateTimeOffset Time, double Value)[] readings)
{
await using (var db = fx.CreateContext())
{
db.Readings.AddRange(readings.Select(r => new Reading
{
MeterId = meterId,
Time = r.Time.ToUniversalTime(),
Value = r.Value,
Quality = ReadingQuality.Manual,
}));
await db.SaveChangesAsync();
}
await RecomputeAsync(meterId);
}
public async Task RecomputeAsync(params int[] meterIds)
{
await using var db = fx.CreateContext();
await using var tx = await db.Database.BeginTransactionAsync();
foreach (var id in meterIds)
{
await Normalization(db).RecomputeMeterAsync(id, null);
}
await db.SaveChangesAsync();
await tx.CommitAsync();
}
public static NormalizationService Normalization(MeterVaultDbContext db) =>
new(db, NormalizationEngine.CreateDefault(),
Microsoft.Extensions.Options.Options.Create(new MeterVaultOptions { TimeZone = BerlinId }),
new FixedTimeProvider(Now));
public async ValueTask DisposeAsync()
{
await using var db = fx.CreateContext();
var ids = _meters.ToArray();
await db.ManualCosts.Where(c => _manualCosts.Contains(c.Id)).ExecuteDeleteAsync();
await db.CostCategories.Where(c => _categories.Contains(c.Id)).ExecuteDeleteAsync();
await db.Tariffs.Where(t => _tariffs.Contains(t.Id)).ExecuteDeleteAsync();
await db.MeterLinks.Where(l => ids.Contains(l.FromMeterId) || ids.Contains(l.ToMeterId)).ExecuteDeleteAsync();
await db.Consumption.Where(c => ids.Contains(c.MeterId)).ExecuteDeleteAsync();
await db.Readings.Where(r => ids.Contains(r.MeterId)).ExecuteDeleteAsync();
await db.MeterEvents.Where(e => ids.Contains(e.MeterId)).ExecuteDeleteAsync();
await db.Meters.Where(m => ids.Contains(m.Id)).ExecuteDeleteAsync();
var types = _types.ToArray();
await db.EnergyTypes.Where(t => types.Contains(t.Id)).ExecuteDeleteAsync();
}
}
/// <summary>Assertions on cost figures.</summary>
internal static class CostAssert
{
public static void Cost(double expected, CostAmount amount, int precision = 6)
{
Assert.NotNull(amount.Cost);
Assert.Equal(expected, amount.Cost!.Value, precision);
}
/// <summary>Priced, with a value, and nothing unavailable in it (not-priced components may have been left out).</summary>
public static void Priced(double expected, CostAmount amount, double tolerance = 1e-6)
{
Assert.Equal(CostStatus.Priced, amount.Status);
Assert.NotNull(amount.Cost);
Assert.InRange(amount.Cost!.Value, expected - tolerance, expected + tolerance);
Assert.DoesNotContain(amount.MissingPrices, m => m.Reason is CostStatus.PriceGap or CostStatus.UnitMismatch);
}
}