Files
MeterVault/tests/Core.Tests/Analysis/VirtualFixtures.cs
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

116 lines
5.6 KiB
C#

using MeterVault.Core.Analysis;
using MeterVault.Core.Analysis.Virtual;
using MeterVault.Core.Domain;
namespace MeterVault.Core.Tests.Analysis;
/// <summary>Builders for virtual-meter tests: UTC buckets and source day maps in the shapes the reader produces.</summary>
internal static class VirtualFixtures
{
public static DateTimeOffset Utc(DateOnly day) => new(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
public static AnalysisBucket Month(int year, int month)
{
var first = new DateOnly(year, month, 1);
var end = first.AddMonths(1);
return new AnalysisBucket(first, end, Utc(first), Utc(end), BucketSize.Month);
}
public static AnalysisBucket[] Months(int year, int firstMonth, int count) =>
[.. Enumerable.Range(0, count).Select(i => new DateOnly(year, firstMonth, 1).AddMonths(i)).Select(d => Month(d.Year, d.Month))];
public static AnalysisBucket Day(DateOnly day) => new(day, day.AddDays(1), Utc(day), Utc(day.AddDays(1)), BucketSize.Day);
public static AnalysisBucket[] Days(DateOnly first, int count) =>
[.. Enumerable.Range(0, count).Select(i => Day(first.AddDays(i)))];
/// <summary>
/// A monthly-resolution series, as an imported monthly table produces it: every day of each listed month is
/// covered by a month-long run, and the month's amount is booked on its last day. Each interval lies inside its
/// month, so the run is divided at months (A-02) unless <paramref name="dividedAtMonths"/> says otherwise (a tank
/// read on the 15th).
/// </summary>
public static Dictionary<DateOnly, SourceDay> Monthly(bool dividedAtMonths, params (int Year, int Month, double Amount)[] months)
{
var days = new Dictionary<DateOnly, SourceDay>();
foreach (var (year, month, amount) in months)
{
var first = new DateOnly(year, month, 1);
var last = first.AddMonths(1).AddDays(-1);
for (var day = first; day <= last; day = day.AddDays(1))
{
days[day] = new SourceDay(
day == last ? amount : 0d, true, ResolutionClass.Month, day == last ? Provenance.Imported : Provenance.None, dividedAtMonths);
}
}
return days;
}
/// <summary>A monthly-resolution series divided at months, the shape of an imported monthly table.</summary>
public static Dictionary<DateOnly, SourceDay> Monthly(params (int Year, int Month, double Amount)[] months) => Monthly(true, months);
/// <summary>
/// One interval longer than a month over <c>[from, to)</c>, as a quarterly reading books it: covered at
/// <see cref="ResolutionClass.Coarse"/>, the whole amount on the last day, never divided.
/// </summary>
public static Dictionary<DateOnly, SourceDay> Coarse(DateOnly from, DateOnly to, double amount)
{
var days = new Dictionary<DateOnly, SourceDay>();
for (var day = from; day < to; day = day.AddDays(1))
{
var last = day == to.AddDays(-1);
days[day] = new SourceDay(last ? amount : 0d, true, ResolutionClass.Coarse, last ? Provenance.Imported : Provenance.None);
}
return days;
}
/// <summary>A daily-resolution series with the same amount on every day of <c>[from, to)</c>.</summary>
public static Dictionary<DateOnly, SourceDay> Daily(DateOnly from, DateOnly to, double perDay, Provenance provenance = Provenance.Measured)
{
var days = new Dictionary<DateOnly, SourceDay>();
for (var day = from; day < to; day = day.AddDays(1))
{
days[day] = new SourceDay(perDay, true, ResolutionClass.Day, provenance);
}
return days;
}
public static VirtualSource Source(int meterId, Dictionary<DateOnly, SourceDay> days) => new(meterId, days);
public static CatalogMeter Physical(int id, string name, MeterMode mode, QuantityKind kind, string unit, short energyType = 1) =>
new(id, name, mode, kind, unit, energyType);
public static CatalogMeter Virtual(int id, string name, QuantityKind kind, string unit, string? expression, short energyType = 1) =>
new(id, name, MeterMode.Virtual, kind, unit, energyType, expression is null ? null : new VirtualDefinition(expression, kind, unit));
/// <summary>
/// The seeded electricity meters (ReferenceDataImporter): Haus 1, Netz 2, Auto 3, Solar 1 = 4, Solar 2 = 5 and the
/// legacy virtual Summe Solar 6, plus a water meter 7 of another energy type.
/// </summary>
public static List<CatalogMeter> SeededElectricity() =>
[
Physical(1, "Zähler Haus", MeterMode.CumulativeCounter, QuantityKind.Consumption, "kWh"),
Physical(2, "Zähler Netz", MeterMode.CumulativeCounter, QuantityKind.Consumption, "kWh"),
Physical(3, "Zähler Auto", MeterMode.CumulativeCounter, QuantityKind.Consumption, "kWh"),
Physical(4, "Solar 1", MeterMode.GenerationCounter, QuantityKind.Generation, "kWh"),
Physical(5, "Solar 2", MeterMode.GenerationCounter, QuantityKind.Generation, "kWh"),
new CatalogMeter(6, "Summe Solar", MeterMode.Virtual, QuantityKind.Generation, "kWh", 1),
Physical(7, "Wasser", MeterMode.CumulativeCounter, QuantityKind.Consumption, "m³", energyType: 2),
];
/// <summary>The seeded links: Solar 1 → Summe, Solar 2 → Summe, Netz → Haus, Summe → Haus, Haus → Auto.</summary>
public static List<MeterLink> SeededLinks() =>
[
Link(4, 6),
Link(5, 6),
Link(2, 1),
Link(6, 1),
Link(1, 3),
];
public static MeterLink Link(int from, int to) => new() { FromMeterId = from, ToMeterId = to };
}