Analysis: one selected period, one set of numbers, on every page
ci / build-test (push) Successful in 2m31s
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:
@@ -0,0 +1,174 @@
|
||||
using System.Net;
|
||||
using MeterVault.Infrastructure.Import;
|
||||
using MeterVault.Infrastructure.Persistence;
|
||||
using MeterVault.Integration.Tests.Costing;
|
||||
using Microsoft.AspNetCore.Localization;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using static MeterVault.Integration.Tests.Costing.CostSandbox;
|
||||
|
||||
namespace MeterVault.Integration.Tests.Overview;
|
||||
|
||||
/// <summary>
|
||||
/// The Overview page (brief §7.1) rendered by the real app on the frozen clock of <see cref="CostSandbox.Now"/>
|
||||
/// (server prerender, which reads the initial load): this month to date of the seeded instance says there is no data
|
||||
/// and offers the latest month as its own period instead of showing it; the previous year shows the sheet's bill with
|
||||
/// the energy type cards, the attention item with its tariff link, the change table and the composition, in English and
|
||||
/// German; a manual-cost-only instance shows its month without a meter. Interactive behaviour (chart, toggles) is covered
|
||||
/// by the pure tests and the browser check.
|
||||
/// </summary>
|
||||
[Collection("Timescale")]
|
||||
public sealed class OverviewPageTests(TimescaleFixture fx) : IAsyncLifetime
|
||||
{
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
await ClearDataAsync(db);
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
await ClearDataAsync(db);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_seeded_overview_explains_an_empty_month_and_shows_the_previous_year_s_bill()
|
||||
{
|
||||
await LoadReferenceDataAsync();
|
||||
int strom;
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
strom = await db.EnergyTypes.Where(t => t.Key == "electricity").Select(t => (int)t.Id).FirstAsync();
|
||||
}
|
||||
|
||||
using var app = new FrozenApp(fx.ConnectionString);
|
||||
|
||||
// Month to date (the default): no data, the dates that have data, and the latest month as its own period — the
|
||||
// panels are not silently switched to May.
|
||||
var empty = await app.GetAsync("/");
|
||||
Assert.Contains("<h1", empty, StringComparison.Ordinal);
|
||||
Assert.Contains("No data for this period", empty, StringComparison.Ordinal);
|
||||
Assert.Contains("to May 31, 2026.", empty, StringComparison.Ordinal);
|
||||
Assert.Contains("Go to latest data", empty, StringComparison.Ordinal);
|
||||
Assert.Contains("href=\"/?from=2026-05-01&to=2026-05-31\"", empty, StringComparison.Ordinal);
|
||||
Assert.Contains("Latest month with data: May 2026 (Meter data and manual costs)", empty, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Total (the bill)", empty, StringComparison.Ordinal);
|
||||
Assert.Contains($"href=\"/energy/{strom}?period=mtd\"", empty, StringComparison.Ordinal);
|
||||
|
||||
// The previous year: the sheet's bill (7,907.64 € ± 0.02), per-type cards with their own units, what changed,
|
||||
// the composition, and the tank's missing price with its tariff link.
|
||||
var year = await app.GetAsync("/?period=prev-year");
|
||||
Assert.Matches("7,907\\.6[3-6] €", year);
|
||||
Assert.Contains("Total cost", year, StringComparison.Ordinal);
|
||||
Assert.Contains("This period: Complete", year, StringComparison.Ordinal);
|
||||
Assert.Contains("15,661 kWh", year, StringComparison.Ordinal);
|
||||
Assert.Contains("213 m³", year, StringComparison.Ordinal);
|
||||
Assert.Contains("2,100 L", year, StringComparison.Ordinal);
|
||||
Assert.Contains("Billed by grid import", year, StringComparison.Ordinal);
|
||||
Assert.Contains("Not priced (no tariff)", year, StringComparison.Ordinal);
|
||||
Assert.Contains("Öltank: Unit price not set up.", year, StringComparison.Ordinal);
|
||||
Assert.Contains("/admin/tariffs?scope=type", year, StringComparison.Ordinal);
|
||||
Assert.Contains("What changed", year, StringComparison.Ordinal);
|
||||
Assert.Contains("Total (the bill)", year, StringComparison.Ordinal);
|
||||
Assert.Contains("Cost composition", year, StringComparison.Ordinal);
|
||||
Assert.Contains("Jan 1 – Dec 31, 2025 compared with Jan 1 – Dec 31, 2024", year, StringComparison.Ordinal);
|
||||
Assert.Contains($"href=\"/energy/{strom}?period=prev-year\"", year, StringComparison.Ordinal);
|
||||
Assert.Contains("No meters yet:", year, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("No data for this period", year, StringComparison.Ordinal);
|
||||
|
||||
// The same in German: the reader's words and numbers; names are user data.
|
||||
var german = await app.GetAsync("/?period=prev-year", "de");
|
||||
Assert.Matches("7\\.907,6[3-6] €", german);
|
||||
Assert.Contains("Gesamtkosten", german, StringComparison.Ordinal);
|
||||
Assert.Contains("Was sich verändert hat", german, StringComparison.Ordinal);
|
||||
Assert.Contains("Summe (die Rechnung)", german, StringComparison.Ordinal);
|
||||
Assert.Contains("Öltank: Arbeitspreis nicht hinterlegt.", german, StringComparison.Ordinal);
|
||||
Assert.Contains("Heizöl", german, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Total cost", german, StringComparison.Ordinal);
|
||||
|
||||
// The latest month opened as its own period shows May's figures.
|
||||
var may = await app.GetAsync("/?from=2026-05-01&to=2026-05-31");
|
||||
Assert.Contains("May 1 – May 31, 2026", may, StringComparison.Ordinal);
|
||||
Assert.Contains("Total (the bill)", may, StringComparison.Ordinal);
|
||||
|
||||
// A chart selection in the address is kept: the measure is the selected option.
|
||||
var chart = await app.GetAsync($"/?period=prev-year&chart=t{strom}:grid-import:kWh");
|
||||
Assert.Contains("Strom · Grid import (kWh)", chart, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_manual_cost_only_instance_shows_its_month_without_any_meter()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var category = await box.CategoryAsync($"Manual {Guid.NewGuid():N}", 100);
|
||||
await box.ManualCostAsync(D(2026, 5, 10), 60, categoryId: category);
|
||||
await box.ManualCostAsync(D(2026, 5, 20), 15);
|
||||
|
||||
using var app = new FrozenApp(fx.ConnectionString);
|
||||
var html = await app.GetAsync("/?from=2026-05-01&to=2026-05-31");
|
||||
|
||||
Assert.Contains("75.00 €", html, StringComparison.Ordinal);
|
||||
Assert.Contains("60.00 €", html, StringComparison.Ordinal);
|
||||
Assert.Contains("15.00 €", html, StringComparison.Ordinal);
|
||||
Assert.Contains("Uncategorized", html, StringComparison.Ordinal);
|
||||
Assert.Contains("Latest month with data: May 2026 (Manual costs)", html, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("No data for this period", html, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private async Task LoadReferenceDataAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
var importer = new ReferenceDataImporter(db, new ImportService(db, Normalization(db)), new CsvImporter());
|
||||
await importer.LoadAsync(Path.Combine(AppContext.BaseDirectory, "fixtures"));
|
||||
}
|
||||
|
||||
private static async Task ClearDataAsync(MeterVaultDbContext db)
|
||||
{
|
||||
await db.MeterLinks.ExecuteDeleteAsync();
|
||||
await db.Consumption.ExecuteDeleteAsync();
|
||||
await db.Readings.ExecuteDeleteAsync();
|
||||
await db.MeterEvents.ExecuteDeleteAsync();
|
||||
await db.ManualCosts.ExecuteDeleteAsync();
|
||||
await db.CostCategoryMembers.ExecuteDeleteAsync();
|
||||
await db.Tariffs.ExecuteDeleteAsync();
|
||||
await db.Tanks.ExecuteDeleteAsync();
|
||||
await db.MeterSources.ExecuteDeleteAsync();
|
||||
await db.Meters.ExecuteDeleteAsync();
|
||||
await db.ImportBatches.ExecuteDeleteAsync();
|
||||
}
|
||||
|
||||
/// <summary>The app on the frozen clock of <see cref="CostSandbox.Now"/>; pages come back HTML-decoded.</summary>
|
||||
private sealed class FrozenApp : IDisposable
|
||||
{
|
||||
private readonly MeterVaultAppFactory _root;
|
||||
private readonly WebApplicationFactory<Program> _app;
|
||||
|
||||
public FrozenApp(string connectionString)
|
||||
{
|
||||
_root = new MeterVaultAppFactory(connectionString);
|
||||
_app = _root.WithWebHostBuilder(builder =>
|
||||
builder.ConfigureTestServices(services => services.AddSingleton<TimeProvider>(new FixedTimeProvider(Now))));
|
||||
}
|
||||
|
||||
public async Task<string> GetAsync(string path, string culture = "en")
|
||||
{
|
||||
using var client = _app.CreateClient();
|
||||
client.DefaultRequestHeaders.Add(
|
||||
"Cookie",
|
||||
CookieRequestCultureProvider.DefaultCookieName + "="
|
||||
+ Uri.EscapeDataString(CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture))));
|
||||
using var response = await client.GetAsync(new Uri(path, UriKind.Relative));
|
||||
response.EnsureSuccessStatusCode();
|
||||
return WebUtility.HtmlDecode(await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_app.Dispose();
|
||||
_root.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user