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:
@@ -1,3 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using MeterVault.Core.Analysis;
|
||||
using MeterVault.Core.Analysis.Virtual;
|
||||
using MeterVault.Core.Domain;
|
||||
using MeterVault.Infrastructure.Backup;
|
||||
using MeterVault.Infrastructure.Persistence;
|
||||
@@ -7,7 +10,8 @@ namespace MeterVault.Integration.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// JSON config export/import (SDD §10): a round-trip through an emptied database preserves the
|
||||
/// relationships (meter → energy type, meter-scoped tariff, category membership) after id remapping.
|
||||
/// relationships (meter → energy type, meter-scoped tariff, category membership, meter topology links)
|
||||
/// after id remapping — and the meter ids inside virtual-meter definitions follow their meters (D-32).
|
||||
/// </summary>
|
||||
[Collection("Timescale")]
|
||||
public sealed class ExportRoundTripTests(TimescaleFixture fx)
|
||||
@@ -57,6 +61,205 @@ public sealed class ExportRoundTripTests(TimescaleFixture fx)
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Links_and_virtual_definitions_follow_their_meters_to_new_ids()
|
||||
{
|
||||
string json;
|
||||
(int Meter, int Solar, int Sum, int Broken) old;
|
||||
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
await WipeAllAsync(db);
|
||||
await DatabaseSeeder.SeedAsync(db);
|
||||
var elec = await db.EnergyTypes.FirstAsync(t => t.Key == "electricity");
|
||||
|
||||
var ghost = new Meter { Name = "Deleted before the export", EnergyTypeId = elec.Id, Mode = MeterMode.CumulativeCounter, Unit = "kWh" };
|
||||
var meter = new Meter { Name = "Export Haus", EnergyTypeId = elec.Id, Mode = MeterMode.CumulativeCounter, Unit = "kWh" };
|
||||
var solar = new Meter { Name = "Export Solar", EnergyTypeId = elec.Id, Mode = MeterMode.GenerationCounter, Unit = "kWh" };
|
||||
var sum = new Meter { Name = "Export Net", EnergyTypeId = elec.Id, Mode = MeterMode.Virtual, Unit = "kWh" };
|
||||
var broken = new Meter { Name = "Export Broken", EnergyTypeId = elec.Id, Mode = MeterMode.Virtual, Unit = "kWh" };
|
||||
db.Meters.AddRange(ghost, meter, solar, sum, broken);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
// A definition with a key of its own next to it (the role, a totals override, …), and one naming a meter the
|
||||
// export will not contain.
|
||||
sum.Meta = VirtualDefinitionJson.Write(
|
||||
"""{"totals":"never"}""",
|
||||
new VirtualDefinition($"(m{solar.Id} + m{meter.Id})", QuantityKind.Net, "kWh", VirtualCostRule.None));
|
||||
broken.Meta = VirtualDefinitionJson.Write(
|
||||
"{}", new VirtualDefinition($"m{solar.Id} + m{ghost.Id}", QuantityKind.Generation, "kWh", VirtualCostRule.SourceCosts));
|
||||
db.MeterLinks.AddRange(
|
||||
new MeterLink { FromMeterId = solar.Id, ToMeterId = sum.Id },
|
||||
new MeterLink { FromMeterId = meter.Id, ToMeterId = sum.Id },
|
||||
new MeterLink { FromMeterId = meter.Id, ToMeterId = solar.Id });
|
||||
await db.SaveChangesAsync();
|
||||
await db.Meters.Where(m => m.Id == ghost.Id).ExecuteDeleteAsync();
|
||||
old = (meter.Id, solar.Id, sum.Id, broken.Id);
|
||||
|
||||
json = await new ExportService(db).ExportJsonAsync();
|
||||
}
|
||||
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
await WipeAllAsync(db);
|
||||
await new ExportService(db).ImportJsonAsync(json);
|
||||
}
|
||||
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
var ids = await db.Meters.ToDictionaryAsync(m => m.Name, m => m.Id);
|
||||
var (meter, solar, sum, broken) = (ids["Export Haus"], ids["Export Solar"], ids["Export Net"], ids["Export Broken"]);
|
||||
|
||||
// The restore numbered the meters anew, so a formula still naming the old ids would read other meters.
|
||||
Assert.NotEqual(old.Solar, solar);
|
||||
Assert.NotEqual(old.Meter, meter);
|
||||
|
||||
var links = await db.MeterLinks.Select(l => new { l.FromMeterId, l.ToMeterId }).ToListAsync();
|
||||
Assert.Equal(
|
||||
new[] { (meter, solar), (meter, sum), (solar, sum) }.Order(),
|
||||
links.Select(l => (l.FromMeterId, l.ToMeterId)).Order());
|
||||
|
||||
var metas = await db.Meters.ToDictionaryAsync(m => m.Id, m => m.Meta);
|
||||
var read = VirtualDefinitionJson.Read(metas[sum]);
|
||||
Assert.Equal(VirtualDefinitionReadStatus.Present, read.Status);
|
||||
Assert.Equal($"(m{solar} + m{meter})", read.Definition!.Expression);
|
||||
Assert.Equal(new[] { meter, solar }.Order(), read.Definition.ReferencedMeterIds);
|
||||
Assert.False(read.ReferencedIdsStale);
|
||||
Assert.Equal(QuantityKind.Net, read.Definition.ResultKind);
|
||||
Assert.Equal(VirtualCostRule.None, read.Definition.CostRule);
|
||||
using (var doc = JsonDocument.Parse(metas[sum]))
|
||||
{
|
||||
Assert.Equal("never", doc.RootElement.GetProperty("totals").GetString());
|
||||
}
|
||||
|
||||
// A meter the document has no row for becomes m0, which no meter has: an unknown reference, never another meter.
|
||||
var brokenRead = VirtualDefinitionJson.Read(metas[broken]);
|
||||
Assert.Equal($"m{solar} + m0", brokenRead.Definition!.Expression);
|
||||
Assert.Equal([0, solar], brokenRead.Definition.ReferencedMeterIds);
|
||||
Assert.False(await db.Meters.AnyAsync(m => m.Id == 0));
|
||||
|
||||
await WipeAllAsync(db);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_tariff_of_a_deleted_meter_is_not_restored_onto_another_meter()
|
||||
{
|
||||
// Review virtual F2: tariff.scope_id has no foreign key, so deleting a meter the old way left its meter-scoped
|
||||
// price behind. A fresh instance numbers its meters from where the original did, so the dead id is given to
|
||||
// another restored meter, which the orphaned 0.99 EUR/kWh would then bill.
|
||||
string json;
|
||||
int firstId;
|
||||
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
await WipeAllAsync(db);
|
||||
await DatabaseSeeder.SeedAsync(db);
|
||||
var elec = await db.EnergyTypes.FirstAsync(t => t.Key == "electricity");
|
||||
var a = new Meter { Name = "Meter A", EnergyTypeId = elec.Id, Mode = MeterMode.CumulativeCounter, Unit = "kWh" };
|
||||
var b = new Meter { Name = "Old wallbox", EnergyTypeId = elec.Id, Mode = MeterMode.CumulativeCounter, Unit = "kWh" };
|
||||
var c = new Meter { Name = "Netz", EnergyTypeId = elec.Id, Mode = MeterMode.CumulativeCounter, Unit = "kWh", Meta = """{"role":"grid_import"}""" };
|
||||
db.Meters.Add(a);
|
||||
await db.SaveChangesAsync();
|
||||
db.Meters.Add(b);
|
||||
await db.SaveChangesAsync();
|
||||
db.Meters.Add(c);
|
||||
await db.SaveChangesAsync();
|
||||
firstId = a.Id;
|
||||
|
||||
db.Tariffs.Add(new Tariff { ScopeType = TariffScope.Meter, ScopeId = b.Id, Component = TariffComponent.UnitPrice, Value = 0.99, Unit = "EUR/kWh", ValidFrom = new DateOnly(2024, 1, 1) });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
// An orphan an older delete left behind: the meter goes, its price stays.
|
||||
await db.Meters.Where(m => m.Id == b.Id).ExecuteDeleteAsync();
|
||||
json = await new ExportService(db).ExportJsonAsync();
|
||||
}
|
||||
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
await WipeAllAsync(db);
|
||||
await db.Database.ExecuteSqlRawAsync($"ALTER TABLE meter ALTER COLUMN id RESTART WITH {firstId}");
|
||||
await new ExportService(db).ImportJsonAsync(json);
|
||||
}
|
||||
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
var restored = await db.Meters.Select(m => m.Id).ToListAsync();
|
||||
var meterTariffs = await db.Tariffs.Where(t => t.ScopeType == TariffScope.Meter).ToListAsync();
|
||||
Assert.DoesNotContain(meterTariffs, t => restored.Contains(t.ScopeId!.Value));
|
||||
Assert.Empty(meterTariffs);
|
||||
await WipeAllAsync(db);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_tariff_of_a_deleted_energy_type_is_not_restored_onto_another_type()
|
||||
{
|
||||
string json;
|
||||
short firstId;
|
||||
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
await WipeAllAsync(db);
|
||||
var kept = new EnergyType { Key = "kept", DisplayName = "Kept", BaseUnit = "kWh", DefaultMode = MeterMode.CumulativeCounter };
|
||||
var gone = new EnergyType { Key = "gone", DisplayName = "Gone", BaseUnit = "kWh", DefaultMode = MeterMode.CumulativeCounter };
|
||||
var other = new EnergyType { Key = "other", DisplayName = "Other", BaseUnit = "kWh", DefaultMode = MeterMode.CumulativeCounter };
|
||||
db.EnergyTypes.Add(kept);
|
||||
await db.SaveChangesAsync();
|
||||
db.EnergyTypes.Add(gone);
|
||||
await db.SaveChangesAsync();
|
||||
db.EnergyTypes.Add(other);
|
||||
await db.SaveChangesAsync();
|
||||
firstId = kept.Id;
|
||||
|
||||
db.Tariffs.Add(new Tariff { ScopeType = TariffScope.EnergyType, ScopeId = gone.Id, Component = TariffComponent.UnitPrice, Value = 0.99, Unit = "EUR/kWh", ValidFrom = new DateOnly(2024, 1, 1) });
|
||||
await db.SaveChangesAsync();
|
||||
await db.EnergyTypes.Where(t => t.Id == gone.Id).ExecuteDeleteAsync();
|
||||
json = await new ExportService(db).ExportJsonAsync();
|
||||
}
|
||||
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
await WipeAllAsync(db);
|
||||
await db.Database.ExecuteSqlRawAsync($"ALTER TABLE energy_type ALTER COLUMN id RESTART WITH {firstId}");
|
||||
await new ExportService(db).ImportJsonAsync(json);
|
||||
}
|
||||
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
Assert.Empty(await db.Tariffs.Where(t => t.ScopeType == TariffScope.EnergyType).ToListAsync());
|
||||
await WipeAllAsync(db);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Deleting_a_meter_or_an_energy_type_takes_its_own_prices_with_it()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
await WipeAllAsync(db);
|
||||
var type = new EnergyType { Key = "deleting", DisplayName = "Deleting", BaseUnit = "kWh", DefaultMode = MeterMode.CumulativeCounter };
|
||||
db.EnergyTypes.Add(type);
|
||||
await db.SaveChangesAsync();
|
||||
var meter = new Meter { Name = "Wallbox", EnergyTypeId = type.Id, Mode = MeterMode.CumulativeCounter, Unit = "kWh" };
|
||||
db.Meters.Add(meter);
|
||||
await db.SaveChangesAsync();
|
||||
db.Readings.Add(new Reading { MeterId = meter.Id, Time = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero), Value = 1 });
|
||||
db.Tariffs.AddRange(
|
||||
new Tariff { ScopeType = TariffScope.Meter, ScopeId = meter.Id, Component = TariffComponent.UnitPrice, Value = 0.99, Unit = "EUR/kWh", ValidFrom = new DateOnly(2024, 1, 1) },
|
||||
new Tariff { ScopeType = TariffScope.EnergyType, ScopeId = type.Id, Component = TariffComponent.BasePrice, Value = 9, Unit = "EUR/month", ValidFrom = new DateOnly(2024, 1, 1) },
|
||||
new Tariff { ScopeType = TariffScope.Global, Component = TariffComponent.BasePrice, Value = 1, Unit = "EUR/month", ValidFrom = new DateOnly(2024, 1, 1) });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
await EntityDeletion.DeleteMeterAsync(db, meter.Id);
|
||||
Assert.False(await db.Meters.AnyAsync(m => m.Id == meter.Id));
|
||||
Assert.False(await db.Tariffs.AnyAsync(t => t.ScopeType == TariffScope.Meter));
|
||||
|
||||
await EntityDeletion.DeleteEnergyTypeAsync(db, type.Id);
|
||||
Assert.False(await db.EnergyTypes.AnyAsync(t => t.Id == type.Id));
|
||||
Assert.Equal(TariffScope.Global, (await db.Tariffs.SingleAsync()).ScopeType);
|
||||
await WipeAllAsync(db);
|
||||
}
|
||||
|
||||
private static async Task WipeAllAsync(MeterVaultDbContext db)
|
||||
{
|
||||
await db.Consumption.ExecuteDeleteAsync();
|
||||
|
||||
Reference in New Issue
Block a user