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,182 +1,346 @@
|
||||
using MeterVault.Core.Analysis;
|
||||
using MeterVault.Core.Analysis.Virtual;
|
||||
using MeterVault.Core.Domain;
|
||||
using MeterVault.Core.Normalization;
|
||||
using MeterVault.Infrastructure.Analysis;
|
||||
using MeterVault.Infrastructure.Dashboard;
|
||||
using MeterVault.Infrastructure.Normalization;
|
||||
using MeterVault.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace MeterVault.Integration.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The per-energy-type flow graph (Sankey): a single-parent chain attributes the child's full
|
||||
/// consumption to its parent and shows the remainder as "Other"; a two-parent merge splits the
|
||||
/// child's consumption proportionally to the parents' own consumption.
|
||||
/// The per-energy-type flow graph (Sankey) on the shared analysis reader (D-30): node values are the meters' canonical
|
||||
/// period totals — a virtual meter's through its formula; a single-parent chain attributes the child's full total to
|
||||
/// its parent and shows the remainder as "Other"; a two-parent merge splits the child proportionally (an estimate);
|
||||
/// a pure-sum virtual meter is fed by its calculation dependencies; any other virtual meter, and a meter in another
|
||||
/// unit, is only in the table; links never carry more than the parent measured; a meter without data is never a zero.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Every meter here is installed on 1 January 2024 and read once, at the first instant of 2025 (UTC, the zone of a
|
||||
/// service built without options), so its whole amount accrues over 2024 and the year's total is fully covered.
|
||||
/// Each test creates its own energy type and meters and removes them again.
|
||||
/// </remarks>
|
||||
[Collection("Timescale")]
|
||||
public sealed class FlowServiceTests(TimescaleFixture fx)
|
||||
public sealed class FlowServiceTests(TimescaleFixture fx) : IAsyncLifetime
|
||||
{
|
||||
private static readonly DateOnly Year = new(2024, 1, 1);
|
||||
private static readonly DateOnly NextYear = new(2025, 1, 1);
|
||||
|
||||
private readonly List<int> _meters = [];
|
||||
private readonly List<short> _types = [];
|
||||
|
||||
public Task InitializeAsync() => Task.CompletedTask;
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
var ids = _meters.ToArray();
|
||||
await db.Consumption.Where(c => ids.Contains(c.MeterId)).ExecuteDeleteAsync();
|
||||
await db.Readings.Where(r => ids.Contains(r.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();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Single_parent_chain_makes_other_remainder()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
try
|
||||
{
|
||||
var type = await SeedTypeAsync(db, "flow_elec_a");
|
||||
var main = await AddMeterAsync(db, "Main", type);
|
||||
var car = await AddMeterAsync(db, "Car", type);
|
||||
db.MeterLinks.Add(new MeterLink { FromMeterId = main.Id, ToMeterId = car.Id });
|
||||
await db.SaveChangesAsync();
|
||||
var type = await TypeAsync();
|
||||
var main = await MeterAsync(type, "Main", 100);
|
||||
var car = await MeterAsync(type, "Car", 30);
|
||||
await LinkAsync(main, car);
|
||||
|
||||
await AddConsumptionAsync(db, main.Id, 100);
|
||||
await AddConsumptionAsync(db, car.Id, 30);
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, Year, NextYear);
|
||||
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, new DateOnly(2024, 1, 1), new DateOnly(2024, 12, 31));
|
||||
|
||||
Assert.Equal(100, graph.Total, 1);
|
||||
var link = Assert.Single(graph.Links, l => l.To == $"m{car.Id}");
|
||||
Assert.Equal(30, link.Value, 1); // full child consumption flows from its single parent
|
||||
var other = Assert.Single(graph.Nodes, n => n.IsOther);
|
||||
Assert.Equal(70, other.Value, 1); // 100 − 30
|
||||
}
|
||||
finally
|
||||
{
|
||||
await ClearAsync(db);
|
||||
}
|
||||
Assert.Equal(100, graph.Total, 1);
|
||||
var link = Assert.Single(graph.Links, l => l.To == $"m{car}");
|
||||
Assert.Equal(30, link.Value, 1); // full child consumption flows from its single parent
|
||||
Assert.False(link.IsEstimated);
|
||||
Assert.False(link.IsCalculated);
|
||||
var other = Assert.Single(graph.Nodes, n => n.IsOther);
|
||||
Assert.Equal(70, other.Value, 1); // 100 − 30
|
||||
Assert.Equal(BucketStatus.Available, other.Status);
|
||||
Assert.Equal(BucketStatus.Available, graph.Nodes.Single(n => n.MeterId == main).Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Two_parents_split_child_proportionally()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
try
|
||||
{
|
||||
var type = await SeedTypeAsync(db, "flow_elec_b");
|
||||
var grid = await AddMeterAsync(db, "Grid", type);
|
||||
var solar = await AddMeterAsync(db, "Solar draw", type);
|
||||
var house = await AddMeterAsync(db, "House", type);
|
||||
db.MeterLinks.Add(new MeterLink { FromMeterId = grid.Id, ToMeterId = house.Id });
|
||||
db.MeterLinks.Add(new MeterLink { FromMeterId = solar.Id, ToMeterId = house.Id });
|
||||
await db.SaveChangesAsync();
|
||||
var type = await TypeAsync();
|
||||
var grid = await MeterAsync(type, "Grid", 75);
|
||||
var solar = await MeterAsync(type, "Solar draw", 25);
|
||||
var house = await MeterAsync(type, "House", 40);
|
||||
await LinkAsync(grid, house);
|
||||
await LinkAsync(solar, house);
|
||||
|
||||
await AddConsumptionAsync(db, grid.Id, 75);
|
||||
await AddConsumptionAsync(db, solar.Id, 25);
|
||||
await AddConsumptionAsync(db, house.Id, 40);
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, Year, NextYear);
|
||||
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, new DateOnly(2024, 1, 1), new DateOnly(2024, 12, 31));
|
||||
|
||||
// House (40) splits 75:25 → 30 from grid, 10 from solar.
|
||||
Assert.Equal(30, graph.Links.Single(l => l.From == $"m{grid.Id}" && l.To == $"m{house.Id}").Value, 1);
|
||||
Assert.Equal(10, graph.Links.Single(l => l.From == $"m{solar.Id}" && l.To == $"m{house.Id}").Value, 1);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await ClearAsync(db);
|
||||
}
|
||||
// House (40) splits 75:25 → 30 from grid, 10 from solar — an estimate, and marked so.
|
||||
var fromGrid = graph.Links.Single(l => l.From == $"m{grid}" && l.To == $"m{house}");
|
||||
var fromSolar = graph.Links.Single(l => l.From == $"m{solar}" && l.To == $"m{house}");
|
||||
Assert.Equal(30, fromGrid.Value, 1);
|
||||
Assert.Equal(10, fromSolar.Value, 1);
|
||||
Assert.True(fromGrid.IsEstimated);
|
||||
Assert.True(fromSolar.IsEstimated);
|
||||
Assert.False(fromGrid.IsCapped);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Generation_meter_counts_as_source()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
try
|
||||
{
|
||||
var type = await SeedTypeAsync(db, "flow_elec_c");
|
||||
var grid = await AddMeterAsync(db, "Grid", type);
|
||||
var solar = await AddMeterAsync(db, "Solar", type);
|
||||
var house = await AddMeterAsync(db, "House", type);
|
||||
db.MeterLinks.Add(new MeterLink { FromMeterId = grid.Id, ToMeterId = house.Id });
|
||||
db.MeterLinks.Add(new MeterLink { FromMeterId = solar.Id, ToMeterId = house.Id });
|
||||
await db.SaveChangesAsync();
|
||||
var type = await TypeAsync();
|
||||
var grid = await MeterAsync(type, "Grid", 75); // grid import
|
||||
var solar = await MeterAsync(type, "Solar", 30, MeterMode.GenerationCounter); // solar generation
|
||||
var house = await MeterAsync(type, "House", 40); // house load
|
||||
await LinkAsync(grid, house);
|
||||
await LinkAsync(solar, house);
|
||||
|
||||
await AddConsumptionAsync(db, grid.Id, 75); // grid import
|
||||
await AddConsumptionAsync(db, solar.Id, 30, ConsumptionKind.Generation); // solar generation
|
||||
await AddConsumptionAsync(db, house.Id, 40); // house load
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, Year, NextYear);
|
||||
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, new DateOnly(2024, 1, 1), new DateOnly(2024, 12, 31));
|
||||
|
||||
// Solar's generation makes it a real source: House (40) splits 75:30 across grid+solar.
|
||||
Assert.Equal(40.0 * 75 / 105, graph.Links.Single(l => l.From == $"m{grid.Id}" && l.To == $"m{house.Id}").Value, 1);
|
||||
Assert.Equal(40.0 * 30 / 105, graph.Links.Single(l => l.From == $"m{solar.Id}" && l.To == $"m{house.Id}").Value, 1);
|
||||
// Remainder across grid+solar = (75+30) − 40 = 65 (export + battery/inverter losses).
|
||||
Assert.Equal(65, graph.Nodes.Where(n => n.IsOther).Sum(n => n.Value), 1);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await ClearAsync(db);
|
||||
}
|
||||
// Solar's generation makes it a real source: House (40) splits 75:30 across grid+solar.
|
||||
Assert.Equal(40.0 * 75 / 105, graph.Links.Single(l => l.From == $"m{grid}" && l.To == $"m{house}").Value, 1);
|
||||
Assert.Equal(40.0 * 30 / 105, graph.Links.Single(l => l.From == $"m{solar}" && l.To == $"m{house}").Value, 1);
|
||||
// Remainder across grid+solar = (75+30) − 40 = 65 (export + battery/inverter losses).
|
||||
Assert.Equal(65, graph.Nodes.Where(n => n.IsOther).Sum(n => n.Value), 1);
|
||||
Assert.Equal(QuantityKind.Generation, graph.MeterFor(solar)!.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Virtual_sum_meter_aggregates_its_upstreams()
|
||||
public async Task Virtual_sum_meter_is_its_formula()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
try
|
||||
var type = await TypeAsync();
|
||||
var solar1 = await MeterAsync(type, "Solar 1", 15, MeterMode.GenerationCounter);
|
||||
var solar2 = await MeterAsync(type, "Solar 2", 15, MeterMode.GenerationCounter);
|
||||
var solar3 = await MeterAsync(type, "Solar 3", 5, MeterMode.GenerationCounter);
|
||||
var sumSolar = await VirtualAsync(type, "Sum Solar", $"m{solar1} + m{solar2}", QuantityKind.Generation, VirtualCostRule.SourceCosts);
|
||||
var grid = await MeterAsync(type, "Grid", 75);
|
||||
var house = await MeterAsync(type, "House", 40);
|
||||
|
||||
// Solar1 + Solar2 → Sum Solar; Grid + Sum Solar → House. Solar 3 is linked into the sum too, but the formula —
|
||||
// not a link — says what the sum is (D-25).
|
||||
await LinkAsync(solar1, sumSolar);
|
||||
await LinkAsync(solar2, sumSolar);
|
||||
await LinkAsync(solar3, sumSolar);
|
||||
await LinkAsync(grid, house);
|
||||
await LinkAsync(sumSolar, house);
|
||||
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, Year, NextYear);
|
||||
|
||||
// Sum Solar has no readings but is Solar 1 + Solar 2 = 30, by its formula.
|
||||
var node = graph.Nodes.Single(n => n.MeterId == sumSolar);
|
||||
Assert.Equal(30, node.Value, 1);
|
||||
Assert.True(node.IsVirtual);
|
||||
Assert.Equal(SeriesBasis.Virtual, graph.MeterFor(sumSolar)!.Basis);
|
||||
|
||||
// Its incoming edges are its calculation dependencies, each at the source's value, marked calculated.
|
||||
var incoming = graph.Links.Where(l => l.To == $"m{sumSolar}").OrderBy(l => l.From, StringComparer.Ordinal).ToList();
|
||||
Assert.Equal([$"m{solar1}", $"m{solar2}"], incoming.Select(l => l.From).Order(StringComparer.Ordinal));
|
||||
Assert.All(incoming, l =>
|
||||
{
|
||||
var type = await SeedTypeAsync(db, "flow_elec_d");
|
||||
var solar1 = await AddMeterAsync(db, "Solar 1", type);
|
||||
var solar2 = await AddMeterAsync(db, "Solar 2", type);
|
||||
var sumSolar = await AddMeterAsync(db, "Sum Solar", type, MeterMode.Virtual);
|
||||
var grid = await AddMeterAsync(db, "Grid", type);
|
||||
var house = await AddMeterAsync(db, "House", type);
|
||||
// Solar1 + Solar2 → Sum Solar ; Grid + Sum Solar → House.
|
||||
db.MeterLinks.Add(new MeterLink { FromMeterId = solar1.Id, ToMeterId = sumSolar.Id });
|
||||
db.MeterLinks.Add(new MeterLink { FromMeterId = solar2.Id, ToMeterId = sumSolar.Id });
|
||||
db.MeterLinks.Add(new MeterLink { FromMeterId = grid.Id, ToMeterId = house.Id });
|
||||
db.MeterLinks.Add(new MeterLink { FromMeterId = sumSolar.Id, ToMeterId = house.Id });
|
||||
await db.SaveChangesAsync();
|
||||
Assert.True(l.IsCalculated);
|
||||
Assert.Equal(15, l.Value, 1);
|
||||
});
|
||||
Assert.DoesNotContain(graph.Links, l => l.From == $"m{solar3}");
|
||||
|
||||
await AddConsumptionAsync(db, solar1.Id, 15, ConsumptionKind.Generation);
|
||||
await AddConsumptionAsync(db, solar2.Id, 15, ConsumptionKind.Generation);
|
||||
await AddConsumptionAsync(db, grid.Id, 75);
|
||||
await AddConsumptionAsync(db, house.Id, 40);
|
||||
// House (40) splits across Grid (75) and Sum Solar (30) → 40*30/105 from solar, an estimate.
|
||||
var fromSum = graph.Links.Single(l => l.From == $"m{sumSolar}" && l.To == $"m{house}");
|
||||
Assert.Equal(40.0 * 30 / 105, fromSum.Value, 1);
|
||||
Assert.True(fromSum.IsEstimated);
|
||||
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, new DateOnly(2024, 1, 1), new DateOnly(2024, 12, 31));
|
||||
// No spurious remainder under Solar 1/2 (their whole output is in Sum Solar).
|
||||
Assert.DoesNotContain(graph.Nodes, n => n.IsOther && n.Id == $"other{solar1}");
|
||||
|
||||
// Sum Solar has no readings but equals Solar 1 + Solar 2 = 30.
|
||||
Assert.Equal(30, graph.Nodes.Single(n => n.MeterId == sumSolar.Id).Value, 1);
|
||||
// House (40) splits across Grid (75) and Sum Solar (30) → 40*30/105 from solar.
|
||||
Assert.Equal(40.0 * 30 / 105, graph.Links.Single(l => l.From == $"m{sumSolar.Id}" && l.To == $"m{house.Id}").Value, 1);
|
||||
// No spurious remainder under Solar 1/2 (their whole output flows into Sum Solar).
|
||||
Assert.DoesNotContain(graph.Nodes, n => n.IsOther && n.Id == $"other{solar1.Id}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await ClearAsync(db);
|
||||
}
|
||||
// The top-level throughput is the roots: grid and the three solar meters — never the sum on top of its sources.
|
||||
Assert.Equal(75 + 15 + 15 + 5, graph.Total, 1);
|
||||
}
|
||||
|
||||
private static async Task<short> SeedTypeAsync(MeterVaultDbContext db, string key)
|
||||
[Fact]
|
||||
public async Task A_legacy_virtual_meter_is_its_implied_sum_until_confirmed()
|
||||
{
|
||||
var type = new EnergyType { Key = key, DisplayName = key, BaseUnit = "kWh", DefaultMode = MeterMode.CumulativeCounter };
|
||||
var type = await TypeAsync();
|
||||
var solar1 = await MeterAsync(type, "Solar 1", 15, MeterMode.GenerationCounter);
|
||||
var solar2 = await MeterAsync(type, "Solar 2", 20, MeterMode.GenerationCounter);
|
||||
var legacy = await VirtualAsync(type, "Legacy sum", expression: null, QuantityKind.Generation, VirtualCostRule.SourceCosts);
|
||||
await LinkAsync(solar1, legacy);
|
||||
await LinkAsync(solar2, legacy);
|
||||
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, Year, NextYear);
|
||||
|
||||
var entry = graph.MeterFor(legacy)!;
|
||||
Assert.Equal(SeriesBasis.LegacyVirtual, entry.Basis);
|
||||
Assert.Equal(35, entry.Value!.Value, 6);
|
||||
Assert.Equal(ValueIssue.LegacyDefinition, entry.Issue);
|
||||
Assert.Equal(2, graph.Links.Count(l => l.To == $"m{legacy}" && l.IsCalculated));
|
||||
Assert.Contains(graph.Problems, p => p.Kind == AnalysisProblemKind.LegacyDefinition && p.MeterId == legacy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_virtual_meter_that_is_not_a_sum_is_only_in_the_table()
|
||||
{
|
||||
var type = await TypeAsync();
|
||||
var a = await MeterAsync(type, "A", 100, MeterMode.GenerationCounter);
|
||||
var b = await MeterAsync(type, "B", 150, MeterMode.GenerationCounter);
|
||||
var difference = await VirtualAsync(type, "A minus B", $"m{a} - m{b}", QuantityKind.Generation, VirtualCostRule.None);
|
||||
var house = await MeterAsync(type, "House", 40);
|
||||
await LinkAsync(a, difference);
|
||||
await LinkAsync(difference, house);
|
||||
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, Year, NextYear);
|
||||
|
||||
// Signed, from its formula — not the flow's old sum of its links (100) — and never drawn.
|
||||
var entry = graph.MeterFor(difference)!;
|
||||
Assert.Equal(-50, entry.Value!.Value, 6);
|
||||
Assert.Equal(BucketStatus.Available, entry.Status);
|
||||
Assert.False(entry.InDiagram);
|
||||
Assert.DoesNotContain(graph.Nodes, n => n.MeterId == difference);
|
||||
Assert.DoesNotContain(graph.Links, l => l.From == $"m{difference}" || l.To == $"m{difference}");
|
||||
|
||||
// Its sources and the house are still meters of the diagram.
|
||||
Assert.True(graph.MeterFor(a)!.InDiagram);
|
||||
Assert.Equal(40, graph.MeterFor(house)!.Value!.Value, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_link_never_carries_more_than_its_parent_measured()
|
||||
{
|
||||
var type = await TypeAsync();
|
||||
var parent = await MeterAsync(type, "Parent", 50);
|
||||
var child = await MeterAsync(type, "Child", 80);
|
||||
await LinkAsync(parent, child);
|
||||
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, Year, NextYear);
|
||||
|
||||
var link = Assert.Single(graph.Links);
|
||||
Assert.Equal(50, link.Value, 6);
|
||||
Assert.True(link.IsCapped);
|
||||
Assert.True(link.IsEstimated);
|
||||
Assert.DoesNotContain(graph.Nodes, n => n.IsOther);
|
||||
|
||||
// The child's own total is untouched: capping is a drawing rule, not a correction.
|
||||
Assert.Equal(80, graph.MeterFor(child)!.Value!.Value, 6);
|
||||
Assert.Equal(80, graph.Nodes.Single(n => n.MeterId == child).Value, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_sub_meter_without_data_is_not_a_zero()
|
||||
{
|
||||
var type = await TypeAsync();
|
||||
var main = await MeterAsync(type, "Main", 100);
|
||||
var silent = await MeterAsync(type, "Silent", amount: null);
|
||||
await LinkAsync(main, silent);
|
||||
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, Year, NextYear);
|
||||
|
||||
var entry = graph.MeterFor(silent)!;
|
||||
Assert.Null(entry.Value);
|
||||
Assert.Equal(BucketStatus.Missing, entry.Status);
|
||||
|
||||
// It keeps its place in the topology, drawn at zero and saying why, but nothing flows to it and the main meter's
|
||||
// total does not turn into "Other": what the silent meter used is unknown, not zero.
|
||||
Assert.Equal(BucketStatus.Missing, graph.Nodes.Single(n => n.MeterId == silent).Status);
|
||||
Assert.Empty(graph.Links);
|
||||
Assert.DoesNotContain(graph.Nodes, n => n.IsOther);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Meters_in_another_unit_or_type_stay_out_of_the_diagram()
|
||||
{
|
||||
var type = await TypeAsync();
|
||||
var otherType = await TypeAsync("m3");
|
||||
var main = await MeterAsync(type, "Main", 100);
|
||||
var water = await MeterAsync(type, "Stray water meter", 7, unit: "m3");
|
||||
var foreign = await MeterAsync(otherType, "Foreign", 12, unit: "m3");
|
||||
await LinkAsync(main, water);
|
||||
await LinkAsync(foreign, main);
|
||||
|
||||
var graph = await new FlowService(fx).GetFlowAsync(type, Year, NextYear);
|
||||
|
||||
// A flow never adds units: the m³ meter is in the table, with its own number and unit, but not in the diagram.
|
||||
var entry = graph.MeterFor(water)!;
|
||||
Assert.False(entry.InDiagram);
|
||||
Assert.Equal(7, entry.Value!.Value, 6);
|
||||
Assert.Equal("kWh", graph.Unit);
|
||||
Assert.DoesNotContain(graph.Nodes, n => n.MeterId == water);
|
||||
|
||||
// A meter of another type is not part of this flow at all.
|
||||
Assert.Null(graph.MeterFor(foreign));
|
||||
Assert.DoesNotContain(graph.Nodes, n => n.MeterId == foreign);
|
||||
Assert.Empty(graph.Links);
|
||||
Assert.Equal(100, graph.Total, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_range_reaching_past_now_counts_actuals_only()
|
||||
{
|
||||
var type = await TypeAsync();
|
||||
var main = await MeterAsync(type, "Main", 100);
|
||||
|
||||
// In July 2024 the reading that closes 2024 lies in the future: nothing of it is an actual yet (D-04).
|
||||
var july = new DateTimeOffset(2024, 7, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
var graph = await new FlowService(fx, time: new FixedTimeProvider(july)).GetFlowAsync(type, Year, NextYear);
|
||||
|
||||
Assert.Null(graph.MeterFor(main)!.Value);
|
||||
Assert.Contains(graph.Problems, p => p.Kind == AnalysisProblemKind.RecordedAfterNow && p.MeterId == main);
|
||||
Assert.Equal(0, graph.Total, 6);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ helpers
|
||||
|
||||
private async Task<short> TypeAsync(string unit = "kWh")
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
var type = new EnergyType { Key = $"flow-{Guid.NewGuid():N}", DisplayName = "Flow test", BaseUnit = unit, DefaultMode = MeterMode.CumulativeCounter };
|
||||
db.EnergyTypes.Add(type);
|
||||
await db.SaveChangesAsync();
|
||||
_types.Add(type.Id);
|
||||
return type.Id;
|
||||
}
|
||||
|
||||
private static async Task<Meter> AddMeterAsync(MeterVaultDbContext db, string name, short type, MeterMode mode = MeterMode.DirectDelta)
|
||||
/// <summary>A counter installed on 1 January 2024 whose one reading at the start of 2025 books <paramref name="amount"/> over 2024; none without an amount.</summary>
|
||||
private async Task<int> MeterAsync(short type, string name, double? amount, MeterMode mode = MeterMode.CumulativeCounter, string unit = "kWh")
|
||||
{
|
||||
var meter = new Meter { Name = name, EnergyTypeId = type, Mode = mode, Unit = "kWh" };
|
||||
await using var db = fx.CreateContext();
|
||||
var meter = new Meter { Name = name, EnergyTypeId = type, Mode = mode, Unit = unit, InstalledAt = Year };
|
||||
db.Meters.Add(meter);
|
||||
await db.SaveChangesAsync();
|
||||
return meter;
|
||||
_meters.Add(meter.Id);
|
||||
|
||||
if (amount is { } value)
|
||||
{
|
||||
db.Readings.Add(new Reading
|
||||
{
|
||||
MeterId = meter.Id,
|
||||
Time = new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero),
|
||||
Value = value,
|
||||
Quality = ReadingQuality.Manual,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Also without readings: the rollup state says the (empty) analysis data is current, not being prepared.
|
||||
await new NormalizationService(db, NormalizationEngine.CreateDefault()).RecomputeMeterAsync(meter.Id, null);
|
||||
await db.SaveChangesAsync();
|
||||
return meter.Id;
|
||||
}
|
||||
|
||||
private static async Task AddConsumptionAsync(MeterVaultDbContext db, int meterId, double amount, ConsumptionKind kind = ConsumptionKind.Consumption)
|
||||
/// <summary>A virtual meter with the given formula; without one, a legacy meter (Meta "{}").</summary>
|
||||
private async Task<int> VirtualAsync(short type, string name, string? expression, QuantityKind kind, VirtualCostRule rule)
|
||||
{
|
||||
db.Consumption.Add(new Consumption
|
||||
{
|
||||
MeterId = meterId,
|
||||
Time = new DateTimeOffset(2024, 6, 15, 0, 0, 0, TimeSpan.Zero),
|
||||
Amount = amount,
|
||||
Kind = kind,
|
||||
Quality = ReadingQuality.Manual,
|
||||
});
|
||||
await using var db = fx.CreateContext();
|
||||
var meta = expression is null ? "{}" : VirtualDefinitionJson.Write("{}", new VirtualDefinition(expression, kind, "kWh", rule));
|
||||
var meter = new Meter { Name = name, EnergyTypeId = type, Mode = MeterMode.Virtual, Unit = "kWh", Meta = meta };
|
||||
db.Meters.Add(meter);
|
||||
await db.SaveChangesAsync();
|
||||
_meters.Add(meter.Id);
|
||||
return meter.Id;
|
||||
}
|
||||
|
||||
private 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();
|
||||
}
|
||||
|
||||
private static async Task ClearAsync(MeterVaultDbContext db)
|
||||
{
|
||||
await db.MeterLinks.ExecuteDeleteAsync();
|
||||
await db.Consumption.ExecuteDeleteAsync();
|
||||
await db.Meters.ExecuteDeleteAsync();
|
||||
await db.EnergyTypes.Where(t => t.Key.StartsWith("flow_elec_")).ExecuteDeleteAsync();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user