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.
273 lines
14 KiB
C#
273 lines
14 KiB
C#
using MeterVault.App.Analysis;
|
|
using MeterVault.App.AnalysisPage;
|
|
using MeterVault.Core.Analysis;
|
|
using MeterVault.Core.Analysis.Virtual;
|
|
using MeterVault.Core.Domain;
|
|
using MeterVault.Infrastructure.Analysis;
|
|
using MeterVault.Infrastructure.Costing;
|
|
using MeterVault.Infrastructure.Options;
|
|
using MeterVault.Integration.Tests.Costing;
|
|
using static MeterVault.Integration.Tests.Costing.CostSandbox;
|
|
|
|
namespace MeterVault.Integration.Tests.Analysis;
|
|
|
|
/// <summary>
|
|
/// What the Analysis page reads (brief §7.4): the portfolio cost is the bill the cost reader prices for the same range —
|
|
/// manual costs once, the same total whatever the bucket (D-36) — two historical years compare bucket by bucket from the
|
|
/// shared reader, and a selection that cannot be one chart (seven meters, a category of mixed units) reads nothing and
|
|
/// explains. Frozen clock of <see cref="CostSandbox.Now"/>, Berlin.
|
|
/// </summary>
|
|
[Collection("Timescale")]
|
|
public sealed class AnalysisPageLoaderTests(TimescaleFixture fx)
|
|
{
|
|
[Fact]
|
|
public async Task The_portfolio_cost_is_the_bill_with_manual_costs_once_whatever_the_bucket()
|
|
{
|
|
await using var box = new CostSandbox(fx);
|
|
var type = await box.TypeAsync();
|
|
await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2024, 1, 1), 100, 50);
|
|
await box.TypePriceAsync(type, 0.30, D(2023, 1, 1));
|
|
await box.ManualCostAsync(D(2024, 2, 10), 40);
|
|
|
|
var view = await LoadAsync("/trends?from=2024-01-01&to=2024-02-29&bucket=month&compare=none");
|
|
|
|
Assert.Equal(AnalysisPageViewKind.Cost, view.Kind);
|
|
Assert.Equal(QueryScope.Portfolio, view.Selection.Scope);
|
|
var cost = Assert.Single(view.Costs);
|
|
Assert.Null(cost.Comparison);
|
|
|
|
// The very figure the cost reader gives the Overview for the same range.
|
|
var bill = await Readers().Costs.ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, Custom(D(2024, 1, 1), D(2024, 2, 29))) { Bucket = BucketSize.Month });
|
|
Assert.Equal(bill.Total.Cost, cost.Current.Total.Cost);
|
|
CostAssert.Priced(30 + 15 + 40, cost.Current.Total);
|
|
Assert.Equal(40, cost.Current.Total.Manual!.Value, 6);
|
|
Assert.Equal(45, cost.Current.Total.Usage!.Value, 6);
|
|
CostAssert.Cost(30, cost.Current.Buckets[0]);
|
|
CostAssert.Cost(15 + 40, cost.Current.Buckets[1]);
|
|
|
|
// One chart series and one table series, in the currency.
|
|
var chart = Assert.Single(view.Chart);
|
|
Assert.Equal("EUR", chart.Currency);
|
|
Assert.True(Assert.Single(view.Table).IsMoney);
|
|
|
|
// A finer or coarser bucket never changes the period total (D-36).
|
|
foreach (var bucket in new[] { "week", "day", "year" })
|
|
{
|
|
var other = await LoadAsync($"/trends?from=2024-01-01&to=2024-02-29&bucket={bucket}&compare=none");
|
|
Assert.Equal(cost.Current.Total.Cost!.Value, other.Costs.Single().Current.Total.Cost!.Value, 6);
|
|
Assert.Equal(40, other.Costs.Single().Current.Total.Manual!.Value, 6);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Two_historical_years_compare_bucket_by_bucket_with_the_overlay_and_the_table()
|
|
{
|
|
await using var box = new CostSandbox(fx);
|
|
var type = await box.TypeAsync();
|
|
var meter = await box.MonthlyAsync(
|
|
type, MeterMode.CumulativeCounter, D(2023, 1, 1), 80, 40, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 100, 50, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20);
|
|
await box.TypePriceAsync(type, 0.30, D(2023, 1, 1));
|
|
|
|
var view = await LoadAsync($"/trends?scope=meter&id={meter}&from=2024-01-01&to=2024-12-31&compare=year:2023");
|
|
|
|
Assert.Equal(AnalysisPageViewKind.Quantity, view.Kind);
|
|
Assert.Equal(BucketSize.Month, view.Plan!.Size);
|
|
var series = Assert.Single(view.Series);
|
|
Assert.Equal(meter, series.MeterId);
|
|
Assert.Equal(350, series.Total.Value!.Value, 6);
|
|
|
|
// The comparison year, bucket by bucket, and the change over what both years cover.
|
|
Assert.True(view.Comparison!.IsApplicable);
|
|
Assert.Equal(12, view.Pairs!.Count);
|
|
Assert.Equal(D(2023, 1, 1), view.Pairs[0].Comparison.FirstDay);
|
|
var comparison = series.Comparison!;
|
|
Assert.Equal(80, comparison.Values[0].Value!.Value, 6);
|
|
Assert.Equal(40, comparison.Values[1].Value!.Value, 6);
|
|
Assert.Equal(220, comparison.Total.Value!.Value, 6);
|
|
Assert.True(view.Matched!.IsComparable);
|
|
Assert.Equal(130, comparison.Change.Absolute!.Value, 6);
|
|
|
|
// The overlay shares the meter's colour; the table carries the comparison and the meter's cost by its rule.
|
|
Assert.Contains(view.Chart, c => c.IsComparison && c.BaseKey == series.Key.Id);
|
|
var table = Assert.Single(view.Table);
|
|
Assert.NotNull(table.Comparison);
|
|
Assert.NotNull(table.Costs);
|
|
CostAssert.Priced(350 * 0.30, view.MeterCost!.Total);
|
|
|
|
// The previous year as a preset is the same comparison.
|
|
var previous = await LoadAsync($"/trends?scope=meter&id={meter}&from=2024-01-01&to=2024-12-31");
|
|
Assert.Equal(220, previous.Series.Single().Comparison!.Total.Value!.Value, 6);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Seven_meters_are_refused_before_anything_is_read()
|
|
{
|
|
await using var box = new CostSandbox(fx);
|
|
var type = await box.TypeAsync();
|
|
var ids = new List<int>();
|
|
for (var i = 0; i < 7; i++)
|
|
{
|
|
ids.Add(await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2024, 1, 1), 10 + i));
|
|
}
|
|
|
|
var (loader, reader, _) = Readers();
|
|
var options = await AnalysisPageOptions.LoadAsync(fx, reader);
|
|
var query = AnalysisQuery.Default(AnalysisDefaults.History).WithScope(QueryScope.ForMeters(ids));
|
|
var selection = AnalysisSelection.Resolve(query, options);
|
|
var view = await loader.LoadAsync(query, selection, options, Now);
|
|
|
|
Assert.Equal(AnalysisPageRefusal.TooManyMeters, view.Selection.Refusal);
|
|
Assert.True(view.IsRefused);
|
|
Assert.Null(view.Plan);
|
|
Assert.Empty(view.Series);
|
|
Assert.Empty(view.Chart);
|
|
|
|
// Six of them compare side by side, each its own series from the shared reader.
|
|
var six = query.WithScope(QueryScope.ForMeters(ids.Take(6)));
|
|
var shown = await loader.LoadAsync(six, AnalysisSelection.Resolve(six, options), options, Now);
|
|
Assert.False(shown.IsRefused);
|
|
Assert.Equal(ids.Take(6), shown.Series.Select(s => s.MeterId!.Value));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_category_of_mixed_units_explains_while_one_of_a_single_unit_shows_its_meters_side_by_side()
|
|
{
|
|
await using var box = new CostSandbox(fx);
|
|
var power = await box.TypeAsync();
|
|
var water = await box.TypeAsync("m³");
|
|
var house = await box.MonthlyAsync(power, MeterMode.CumulativeCounter, D(2024, 1, 1), 100, 50);
|
|
var car = await box.MonthlyAsync(power, MeterMode.CumulativeCounter, D(2024, 1, 1), 10, 20);
|
|
var tap = await box.MeterAsync(water, MeterMode.CumulativeCounter, "m³", installedAt: D(2024, 1, 1));
|
|
await box.MonthlyReadingsAsync(tap, D(2024, 1, 1), 5, 6);
|
|
await box.TypePriceAsync(power, 0.30, D(2023, 1, 1));
|
|
|
|
var mixed = await box.CategoryAsync($"mixed-{Guid.NewGuid():N}", 91, meters: [house, tap]);
|
|
var single = await box.CategoryAsync($"single-{Guid.NewGuid():N}", 92, meters: [house, car]);
|
|
const string Range = "&from=2024-01-01&to=2024-02-29&bucket=month&compare=none";
|
|
|
|
// kWh and m³: no quantity, and nothing read — the explanation names each group.
|
|
var refused = await LoadAsync($"/trends?scope=category&id={mixed}&metric=consumption{Range}");
|
|
Assert.Equal(AnalysisPageRefusal.CategoryMixed, refused.Selection.Refusal);
|
|
Assert.True(refused.IsRefused);
|
|
Assert.Null(refused.Plan);
|
|
Assert.Empty(refused.Series);
|
|
Assert.Equal(2, refused.Selection.Groups.Count);
|
|
|
|
// Its cost is always there.
|
|
var mixedCost = await LoadAsync($"/trends?scope=category&id={mixed}{Range}");
|
|
Assert.Equal(AnalysisPageViewKind.Cost, mixedCost.Kind);
|
|
var categoryBill = await Readers().Costs.ReadAsync(
|
|
new CostAnalysisRequest(CostScope.ForCategory(mixed), Custom(D(2024, 1, 1), D(2024, 2, 29))) { Bucket = BucketSize.Month });
|
|
Assert.Equal(categoryBill.Total.Cost, mixedCost.Costs.Single().Current.Total.Cost);
|
|
|
|
// Two kWh consumption meters: side by side, each exactly as the reader reads it on its own, never added up.
|
|
var shown = await LoadAsync($"/trends?scope=category&id={single}&metric=consumption{Range}");
|
|
Assert.False(shown.IsRefused);
|
|
Assert.Equal([house, car], shown.Series.Select(s => s.MeterId!.Value));
|
|
Assert.Equal(150, shown.Series[0].Total.Value!.Value, 6);
|
|
Assert.Equal(30, shown.Series[1].Total.Value!.Value, 6);
|
|
Assert.Equal(2, shown.Table.Count);
|
|
Assert.DoesNotContain(shown.Table, t => t.Total?.Value is 180);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_energy_type_shows_its_measures_side_by_side_named_by_the_meters_they_count()
|
|
{
|
|
await using var box = new CostSandbox(fx);
|
|
var type = await box.TypeAsync();
|
|
await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2024, 1, 1), 100, 50);
|
|
|
|
var view = await LoadAsync($"/trends?scope=type&id={type}&from=2024-01-01&to=2024-02-29&bucket=month");
|
|
|
|
Assert.Equal(AnalysisMetric.Consumption, view.Selection.Metric);
|
|
var use = Assert.Single(view.Series);
|
|
Assert.Equal(Core.Analysis.Totals.TotalsMeasure.Use, use.Key.Measure);
|
|
Assert.Equal(150, use.Total.Value!.Value, 6);
|
|
Assert.Equal(use.Total.Value, view.Quantities!.MeasureFor(type, Core.Analysis.Totals.TotalsMeasure.Use)!.Total.Value);
|
|
|
|
// Nothing in the range but data before it: no data for this period, and the dates that have some.
|
|
var empty = await LoadAsync($"/trends?scope=type&id={type}&from=2025-01-01&to=2025-02-28");
|
|
Assert.True(empty.HasNoData);
|
|
Assert.Equal(D(2024, 1, 1), empty.Availability!.FirstDay);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_source_without_data_is_named_in_the_figures_of_a_virtual_meter()
|
|
{
|
|
// Brief §4.3 "name the problem and affected source": the table and chart of /trends?scope=meter name the source a
|
|
// bucket misses by its name — as the attention list does — never "#id".
|
|
await using var box = new CostSandbox(fx);
|
|
var type = await box.TypeAsync();
|
|
var a = await box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2025, 1, 1), 100, 80);
|
|
var b = await box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2025, 1, 1), 150);
|
|
var sum = await box.VirtualAsync(type, $"m{a} + m{b}", QuantityKind.Generation, "kWh", VirtualCostRule.None);
|
|
string bName;
|
|
await using (var db = fx.CreateContext())
|
|
{
|
|
bName = (await db.Meters.FindAsync(b))!.Name;
|
|
}
|
|
|
|
var view = await AnalysisUiTestData.In("en", () => LoadAsync($"/trends?scope=meter&id={sum}&from=2025-01-01&to=2025-02-28&bucket=month&compare=none"));
|
|
|
|
var table = Assert.Single(view.Table);
|
|
var february = table.Values[1];
|
|
Assert.Null(february.Value);
|
|
Assert.Contains(bName, february.Status.Detail, StringComparison.Ordinal);
|
|
Assert.DoesNotContain("#" + b.ToString(System.Globalization.CultureInfo.InvariantCulture), february.Status.Detail!, StringComparison.Ordinal);
|
|
Assert.Contains(bName, table.Total!.Status.Detail, StringComparison.Ordinal);
|
|
Assert.Contains(bName, view.Chart.Single().Values[1].Note, StringComparison.Ordinal);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_type_of_monthly_meters_resolves_months_so_a_month_has_no_finer_bucket_to_open()
|
|
{
|
|
// D-51: drilling goes to the next finer bucket the data supports. A type's measure carries the resolution of the
|
|
// meters it counts — monthly here — so a month is not opened into 31 days of "only coarser data".
|
|
await using var box = new CostSandbox(fx);
|
|
var type = await box.TypeAsync();
|
|
await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2025, 1, 1), 100, 80, 90);
|
|
var (_, reader, _) = Readers();
|
|
|
|
var result = await reader.ReadAsync(
|
|
new AnalysisRequest(AnalysisScope.ForEnergyType(type), Custom(D(2025, 1, 1), D(2025, 3, 31))) { Bucket = BucketSize.Month });
|
|
Assert.Equal(ResolutionClass.Month, Assert.Single(result.Measures).Resolution);
|
|
|
|
var view = await LoadAsync($"/trends?scope=type&id={type}&metric=consumption&from=2025-01-01&to=2025-03-31&bucket=month");
|
|
Assert.Equal(ResolutionClass.Month, view.Resolution);
|
|
Assert.Null(AnalysisNavigation.DrillInto(view.Query, view.Plan!.Buckets[1], view.Resolution));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_category_of_calculated_views_explains_itself_instead_of_no_data_yet()
|
|
{
|
|
// Brief §4.3: an explained result, not "nothing has been recorded yet" — its member has data and a cost of its own.
|
|
await using var box = new CostSandbox(fx);
|
|
var type = await box.TypeAsync();
|
|
var a = await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2025, 1, 1), 100, 80);
|
|
await box.TypePriceAsync(type, 0.30, D(2024, 1, 1));
|
|
var view = await box.VirtualAsync(type, $"m{a}", QuantityKind.Consumption, "kWh", VirtualCostRule.SourceCosts);
|
|
var category = await box.CategoryAsync($"views-{Guid.NewGuid():N}", 95, meters: [view]);
|
|
|
|
var page = await LoadAsync($"/trends?scope=category&id={category}&metric=cost&from=2025-01-01&to=2025-02-28&bucket=month&compare=none");
|
|
|
|
Assert.False(page.HasNoData);
|
|
Assert.Contains(page.CostAttention, x => x.Kind == CostAttentionKind.CategoryPricesNothing && x.MeterIds.Contains(view));
|
|
}
|
|
|
|
private (AnalysisPageLoader Loader, AnalysisReader Reader, CostReader Costs) Readers()
|
|
{
|
|
var options = Microsoft.Extensions.Options.Options.Create(new MeterVaultOptions { TimeZone = BerlinId, Currency = "EUR" });
|
|
var reader = new AnalysisReader(fx, options);
|
|
var costs = new CostReader(fx, reader, options);
|
|
return (new AnalysisPageLoader(reader, costs, new AnalysisPeriods(reader, costs)), reader, costs);
|
|
}
|
|
|
|
private async Task<AnalysisPageView> LoadAsync(string url)
|
|
{
|
|
var (loader, reader, _) = Readers();
|
|
var options = await AnalysisPageOptions.LoadAsync(fx, reader);
|
|
var query = AnalysisQuery.Parse(url, AnalysisDefaults.History);
|
|
return await loader.LoadAsync(query, AnalysisSelection.Resolve(query, options), options, Now);
|
|
}
|
|
}
|