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,267 @@
|
||||
using System.Globalization;
|
||||
using MeterVault.App.Analysis;
|
||||
using MeterVault.App.Localization;
|
||||
using MeterVault.App.MeterDetails;
|
||||
using MeterVault.Core.Analysis;
|
||||
using MeterVault.Core.Analysis.Virtual;
|
||||
using MeterVault.Core.Domain;
|
||||
using MeterVault.Infrastructure.Analysis;
|
||||
using MeterVault.Infrastructure.Costing;
|
||||
using MeterVault.Infrastructure.Dashboard;
|
||||
using MeterVault.Infrastructure.Options;
|
||||
using MeterVault.Integration.Tests.Costing;
|
||||
using static MeterVault.Integration.Tests.Costing.CostSandbox;
|
||||
|
||||
namespace MeterVault.Integration.Tests.MeterPage;
|
||||
|
||||
/// <summary>
|
||||
/// The meter page's Analysis tab load (brief §7.2, §5.4): one committed value per request — the series from the shared
|
||||
/// reader, the cost by the meter's rule, the comparison, the chart and table inputs — for a physical and a virtual
|
||||
/// meter alike, on a frozen clock of 19 September 2026, 14:37 Berlin. Replaces MeterPeriodServiceTests (the service is
|
||||
/// retired): the same cases, read the way the page reads them now.
|
||||
/// </summary>
|
||||
[Collection("Timescale")]
|
||||
public sealed class MeterAnalysisLoaderTests(TimescaleFixture fx)
|
||||
{
|
||||
[Fact]
|
||||
public async Task A_virtual_sum_of_two_generation_meters_reads_250_and_200_by_month_and_450_in_total()
|
||||
{
|
||||
// Brief §5.4, the worked example: A = 100/80, B = 150/120 → A+B = 250/200, 450, generation, no raw readings, no
|
||||
// cost category — and the page labels it generation.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var a = await box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2026, 1, 1), 100, 80);
|
||||
var b = await box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2026, 1, 1), 150, 120);
|
||||
var sum = await box.VirtualAsync(type, $"m{a} + m{b}", QuantityKind.Generation, "kWh", VirtualCostRule.None);
|
||||
|
||||
var view = await InEnglish(() => Loader(box).LoadAsync(sum, JanFeb(sum), Now));
|
||||
|
||||
Assert.Equal(sum, view.MeterId);
|
||||
var series = view.Series!;
|
||||
Assert.Equal(SeriesBasis.Virtual, series.Basis);
|
||||
Assert.Equal(QuantityKind.Generation, series.Kind);
|
||||
Assert.Equal("Generation", InEnglishSync(() => series.Kind.Display()));
|
||||
Assert.Equal("kWh", series.Unit);
|
||||
Assert.Equal([250d, 200d], series.Values.Select(v => v.Value!.Value));
|
||||
Assert.All(series.Values, v => Assert.Equal(BucketStatus.Available, v.Status));
|
||||
Assert.Equal(450d, series.Total.Value!.Value, 6);
|
||||
Assert.Equal(BucketStatus.Available, series.Total.Status);
|
||||
Assert.Equal(2, series.Contributions.Count);
|
||||
|
||||
// The chart and table say the same, with the months as their rows.
|
||||
var table = Assert.Single(view.Table);
|
||||
Assert.Equal(["250 kWh", "200 kWh"], table.Values.Select(v => v.Text));
|
||||
Assert.Equal("450 kWh", table.Total!.Text);
|
||||
Assert.Equal([250d, 200d], Assert.Single(view.Chart).Values.Select(v => v.Value!.Value));
|
||||
|
||||
// Generation is never billed: the meter is not costed, and the page offers no cost metric.
|
||||
Assert.NotNull(view.Cost);
|
||||
Assert.False(view.IsCosted);
|
||||
Assert.Equal(MeterCostRule.None, view.Cost!.Meter!.Rule);
|
||||
Assert.Empty(view.Metrics);
|
||||
Assert.Null(table.Costs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_physical_meter_reads_local_months_its_comparison_and_its_cost()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var meter = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", installedAt: D(2025, 7, 1));
|
||||
await box.ReadingsAsync(meter,
|
||||
(Midnight(2025, 7, 1), 0), (Midnight(2025, 8, 1), 0), (Midnight(2025, 9, 1), 80), (Midnight(2025, 10, 1), 150),
|
||||
(Midnight(2026, 8, 1), 1000), (Midnight(2026, 9, 1), 1100), (Midnight(2026, 9, 10), 1130));
|
||||
await box.TypePriceAsync(type, 0.10, D(2025, 1, 1));
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
db.MeterEvents.Add(new MeterEvent { MeterId = meter, Time = Midnight(2026, 8, 15), EventType = MeterEventType.Note, Notes = "new tenant" });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var query = AnalysisQuery.Parse("?from=2026-08-01&to=2026-08-31&bucket=month", MeterAnalysisLoader.DefaultsFor(meter));
|
||||
var view = await InEnglish(() => Loader(box).LoadAsync(meter, query, Now));
|
||||
|
||||
var series = view.Series!;
|
||||
Assert.Equal(100d, series.Total.Value!.Value, 6);
|
||||
Assert.Equal(QuantityKind.Consumption, series.Kind);
|
||||
|
||||
// Compared with August last year (A-13 default), over what both cover.
|
||||
Assert.NotNull(series.Comparison);
|
||||
Assert.Equal(80d, series.Comparison!.Total.Value!.Value, 6);
|
||||
Assert.Equal(20d, series.Comparison.Change.Absolute!.Value, 6);
|
||||
|
||||
// Its cost is its bill line at the type's price, and the change of the cost pairs complete months only.
|
||||
Assert.True(view.IsCosted);
|
||||
Assert.Equal(MeterCostRule.BillLine, view.Cost!.Meter!.Rule);
|
||||
CostAssert.Priced(10, view.Cost.Total);
|
||||
Assert.Equal(2d, view.CostChange.Change.Absolute!.Value, 6);
|
||||
Assert.Equal([AnalysisMetric.Consumption, AnalysisMetric.Cost], view.Metrics);
|
||||
Assert.NotNull(Assert.Single(view.Table).Costs);
|
||||
|
||||
// The note recorded in the month is a marker under the chart.
|
||||
Assert.Equal("new tenant", Assert.Single(view.Markers.Events).Notes);
|
||||
|
||||
// metric=cost charts the cost and its comparison instead.
|
||||
var costView = await InEnglish(() => Loader(box).LoadAsync(meter, query.WithMetric(AnalysisMetric.Cost), Now));
|
||||
Assert.True(costView.ShowsCost);
|
||||
Assert.Equal(2, costView.Chart.Count);
|
||||
Assert.True(costView.Chart.All(c => c.IsMoney));
|
||||
Assert.Equal([10d], costView.Chart[0].Values.Select(v => v.Value!.Value));
|
||||
Assert.Equal([8d], costView.Chart[1].Values.Select(v => v.Value!.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_reading_after_now_is_not_counted_and_the_month_is_not_a_confident_zero_before_the_data()
|
||||
{
|
||||
// D-04: a reading stamped on 25 September (a device clock ahead) is not an actual on the 19th.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var meter = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", installedAt: D(2026, 8, 1));
|
||||
await box.ReadingsAsync(
|
||||
meter, (Midnight(2026, 8, 1), 0), (Midnight(2026, 9, 1), 100), (Midnight(2026, 9, 10), 130), (Midnight(2026, 9, 25), 1000));
|
||||
|
||||
var ytd = AnalysisQuery.Parse("?period=ytd&bucket=month", MeterAnalysisLoader.DefaultsFor(meter));
|
||||
var view = await InEnglish(() => Loader(box).LoadAsync(meter, ytd, Now));
|
||||
|
||||
var series = view.Series!;
|
||||
Assert.Equal(130d, series.Total.Value!.Value, 6);
|
||||
Assert.Contains(series.RecordedAfterNow, r => r.MeterId == meter);
|
||||
|
||||
// The months before the install hold no data: missing, not zero.
|
||||
Assert.Equal(BucketStatus.Missing, series.Values[0].Status);
|
||||
Assert.Null(series.Values[0].Value);
|
||||
Assert.Equal("—", view.Table[0].Values[0].Text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_year_of_measured_zeros_is_data_and_a_generation_meter_reports_generation()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var zeros = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", installedAt: D(2026, 5, 1));
|
||||
await box.ReadingsAsync(zeros, (Midnight(2026, 5, 1), 0), (Midnight(2026, 6, 1), 0), (Midnight(2026, 7, 1), 0), (Midnight(2026, 8, 1), 0));
|
||||
var pv = await box.MeterAsync(type, MeterMode.GenerationCounter, "kWh", installedAt: D(2026, 6, 1));
|
||||
await box.ReadingsAsync(pv, (Midnight(2026, 6, 1), 0), (Midnight(2026, 7, 1), 42));
|
||||
await box.TypePriceAsync(type, 0.10, D(2025, 1, 1));
|
||||
|
||||
var june = AnalysisQuery.Parse("?from=2026-06-01&to=2026-07-31&bucket=month&compare=none", MeterAnalysisLoader.DefaultsFor(zeros));
|
||||
var zeroView = await InEnglish(() => Loader(box).LoadAsync(zeros, june, Now));
|
||||
Assert.All(zeroView.Series!.Values, v => Assert.Equal((BucketStatus.Available, 0d), (v.Status, v.Value!.Value)));
|
||||
Assert.Equal(0d, zeroView.Series!.Total.Value!.Value, 9);
|
||||
|
||||
var pvView = await InEnglish(() => Loader(box).LoadAsync(pv, june, Now));
|
||||
Assert.Equal(QuantityKind.Generation, pvView.Series!.Kind);
|
||||
Assert.Equal(42d, pvView.Series.Values[0].Value!.Value, 6);
|
||||
Assert.False(pvView.IsCosted);
|
||||
Assert.Equal(MeterNotCostedReason.Generation, pvView.Cost!.Meter!.NotCosted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_virtual_meter_that_cannot_be_evaluated_shows_no_values_and_is_not_costed()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var a = await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 80);
|
||||
var broken = await box.VirtualAsync(type, $"m{a} + m{int.MaxValue}", QuantityKind.Consumption, "kWh", VirtualCostRule.SourceCosts);
|
||||
|
||||
var view = await InEnglish(() => Loader(box).LoadAsync(broken, JanFeb(broken), Now));
|
||||
|
||||
var series = view.Series!;
|
||||
Assert.Equal(BucketStatus.Invalid, series.Total.Status);
|
||||
Assert.Null(series.Total.Value);
|
||||
Assert.All(series.Values, v => Assert.Null(v.Value));
|
||||
Assert.Equal(VirtualMeterStatus.Invalid, series.Virtual!.Status);
|
||||
Assert.Contains(view.Quantities.Problems, p => p.Kind == AnalysisProblemKind.InvalidDefinition && p.MeterId == broken);
|
||||
Assert.False(view.IsCosted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_dependency_loop_names_the_other_meter_by_its_name_never_by_its_id()
|
||||
{
|
||||
// Brief §4.3 / §11 "a cycle reports a named dependency error": a loop stops the evaluation, so the other end of it
|
||||
// is in no contribution — the attention item and the figures still name it.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var a = await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100, 80);
|
||||
var one = await box.VirtualAsync(type, $"m{a}", QuantityKind.Consumption, "kWh", VirtualCostRule.OwnQuantity);
|
||||
var two = await box.VirtualAsync(type, $"m{one}", QuantityKind.Consumption, "kWh", VirtualCostRule.OwnQuantity);
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
var meter = await db.Meters.FindAsync(one);
|
||||
meter!.Meta = VirtualDefinitionJson.Write("{}", new VirtualDefinition($"m{a} + m{two}", QuantityKind.Consumption, "kWh", VirtualCostRule.OwnQuantity));
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
string twoName;
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
twoName = (await db.Meters.FindAsync(two))!.Name;
|
||||
}
|
||||
|
||||
var view = await InEnglish(() => Loader(box).LoadAsync(one, JanFeb(one), Now));
|
||||
|
||||
Assert.Equal(BucketStatus.Invalid, view.Series!.Total.Status);
|
||||
Assert.Equal(twoName, view.MeterNames[two]);
|
||||
var items = InEnglishSync(() => AttentionItems.Build(
|
||||
view.Quantities.Problems.Concat(view.Cost?.QuantityProblems ?? []), view.Cost?.Attention, view.AttentionNames, view.Query));
|
||||
var loop = Assert.Single(items, i => i.Text.Contains(" → ", StringComparison.Ordinal));
|
||||
Assert.Contains(twoName, loop.Text, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("#" + two.ToString(CultureInfo.InvariantCulture), loop.Text, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Meter #", loop.Text, StringComparison.Ordinal);
|
||||
|
||||
// The figures that name a culprit name it too.
|
||||
var details = view.Table.Single().Values.Select(v => v.Status.Detail).Append(view.Table.Single().Total!.Status.Detail).OfType<string>().ToList();
|
||||
Assert.DoesNotContain(details, d => d.Contains('#', StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_meter_that_is_being_rebuilt_is_pending_and_nothing_is_priced()
|
||||
{
|
||||
// D-16: hand-inserted consumption without rollups reads as "being prepared", never as no data.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var meter = await box.MeterAsync(type, MeterMode.DirectDelta, "kWh");
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
db.Consumption.Add(new Consumption { MeterId = meter, Time = Midnight(2026, 2, 1), Amount = 5, Kind = ConsumptionKind.Consumption, Quality = ReadingQuality.Measured });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var view = await InEnglish(() => Loader(box).LoadAsync(meter, JanFeb(meter), Now));
|
||||
|
||||
Assert.True(view.Series!.IsPending);
|
||||
Assert.Null(view.Cost);
|
||||
}
|
||||
|
||||
private static AnalysisQuery JanFeb(int meterId) =>
|
||||
AnalysisQuery.Parse("?from=2026-01-01&to=2026-02-28&bucket=month&compare=none", MeterAnalysisLoader.DefaultsFor(meterId));
|
||||
|
||||
private MeterAnalysisLoader Loader(CostSandbox box)
|
||||
{
|
||||
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);
|
||||
_ = box;
|
||||
return new MeterAnalysisLoader(new AnalysisPeriods(reader, costs), reader, costs, new MeterDetailService(fx, options, reader));
|
||||
}
|
||||
|
||||
/// <summary>Runs a load with English as the formatting and UI culture (the chart and table text is built inside it).</summary>
|
||||
private static async Task<T> InEnglish<T>(Func<Task<T>> load)
|
||||
{
|
||||
var format = CultureInfo.CurrentCulture;
|
||||
var ui = CultureInfo.CurrentUICulture;
|
||||
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en");
|
||||
CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en");
|
||||
try
|
||||
{
|
||||
return await load();
|
||||
}
|
||||
finally
|
||||
{
|
||||
CultureInfo.CurrentCulture = format;
|
||||
CultureInfo.CurrentUICulture = ui;
|
||||
}
|
||||
}
|
||||
|
||||
private static T InEnglishSync<T>(Func<T> body) => Analysis.AnalysisUiTestData.In("en", body);
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
using MeterVault.Core.Analysis;
|
||||
using MeterVault.Core.Analysis.Virtual;
|
||||
using MeterVault.Core.Domain;
|
||||
using MeterVault.Infrastructure.Analysis;
|
||||
using MeterVault.Infrastructure.Dashboard;
|
||||
using MeterVault.Infrastructure.Ingestion;
|
||||
using MeterVault.Infrastructure.Options;
|
||||
using MeterVault.Integration.Tests.Costing;
|
||||
using static MeterVault.Integration.Tests.Costing.CostSandbox;
|
||||
|
||||
namespace MeterVault.Integration.Tests.MeterPage;
|
||||
|
||||
/// <summary>
|
||||
/// The meter page's read model (brief §7.2, D-50): record tabs paged server-side, newest first, keyset-ordered on each
|
||||
/// table's key and filtered by a half-open range; the manual-entry dialog's own context for the entered instant (the
|
||||
/// neighbours the ingestion guard reads); markers inside a range; applicable tariffs; and a virtual meter's calculation.
|
||||
/// </summary>
|
||||
[Collection("Timescale")]
|
||||
public sealed class MeterDetailServiceTests(TimescaleFixture fx)
|
||||
{
|
||||
private static readonly DateTimeOffset Start = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
|
||||
[Fact]
|
||||
public async Task Readings_page_newest_first_by_keyset_and_filter_by_a_half_open_range()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var meter = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh");
|
||||
await InsertReadingsAsync(meter, 250);
|
||||
var service = Service();
|
||||
|
||||
var first = await service.GetReadingsAsync(meter, RecordRange.All);
|
||||
var second = await service.GetReadingsAsync(meter, RecordRange.All, first.Next);
|
||||
var third = await service.GetReadingsAsync(meter, RecordRange.All, second.Next);
|
||||
|
||||
Assert.Equal((100, 100, 50), (first.Rows.Count, second.Rows.Count, third.Rows.Count));
|
||||
Assert.All(new[] { first, second, third }, page => Assert.Equal(250, page.Total));
|
||||
Assert.NotNull(first.Next);
|
||||
Assert.NotNull(second.Next);
|
||||
Assert.Null(third.Next);
|
||||
var all = first.Rows.Concat(second.Rows).Concat(third.Rows).Select(r => r.Time).ToList();
|
||||
Assert.Equal(250, all.Distinct().Count());
|
||||
Assert.Equal(all.OrderDescending(), all);
|
||||
Assert.Equal(Start.AddHours(249), all[0]);
|
||||
|
||||
// Keyset, not offset: a reading arriving at the top does not shift the older pages.
|
||||
await InsertReadingsAsync(meter, 1, fromHour: 1000);
|
||||
var again = await service.GetReadingsAsync(meter, RecordRange.All, first.Next);
|
||||
Assert.Equal(second.Rows, again.Rows);
|
||||
Assert.Equal(251, again.Total);
|
||||
|
||||
// [from, to): the start is included, the end is not.
|
||||
var range = new RecordRange(Start.AddHours(10), Start.AddHours(20));
|
||||
var filtered = await service.GetReadingsAsync(meter, range);
|
||||
Assert.Equal(10, filtered.Total);
|
||||
Assert.Equal(Start.AddHours(19), filtered.Rows[0].Time);
|
||||
Assert.Equal(Start.AddHours(10), filtered.Rows[^1].Time);
|
||||
Assert.Null(filtered.Next);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Normalized_rows_break_ties_on_their_kind_across_a_page_boundary()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var meter = await box.MeterAsync(type, MeterMode.DirectDelta, "kWh");
|
||||
|
||||
// One row at the newest instant, then 51 instants with both kinds: the 100th and 101st rows share an instant.
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
db.Consumption.Add(Row(meter, 51, ConsumptionKind.Consumption));
|
||||
for (var i = 0; i <= 50; i++)
|
||||
{
|
||||
db.Consumption.Add(Row(meter, i, ConsumptionKind.Consumption));
|
||||
db.Consumption.Add(Row(meter, i, ConsumptionKind.Generation));
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var service = Service();
|
||||
var first = await service.GetConsumptionAsync(meter, RecordRange.All);
|
||||
var second = await service.GetConsumptionAsync(meter, RecordRange.All, first.Next);
|
||||
|
||||
Assert.Equal(103, first.Total);
|
||||
Assert.Equal(100, first.Rows.Count);
|
||||
Assert.Equal((Start.AddHours(1), ConsumptionKind.Generation), (first.Rows[^1].Time, first.Rows[^1].Kind));
|
||||
Assert.Equal(3, second.Rows.Count);
|
||||
Assert.Equal((Start.AddHours(1), ConsumptionKind.Consumption), (second.Rows[0].Time, second.Rows[0].Kind));
|
||||
Assert.Null(second.Next);
|
||||
Assert.Equal(103, first.Rows.Concat(second.Rows).Select(r => (r.Time, r.Kind)).Distinct().Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Events_page_on_their_instant_then_their_id()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var meter = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh");
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
// All at one instant: only the id orders them.
|
||||
for (var i = 0; i < 101; i++)
|
||||
{
|
||||
db.MeterEvents.Add(new MeterEvent { MeterId = meter, Time = Start, EventType = MeterEventType.Note, Notes = $"note {i}" });
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var service = Service();
|
||||
var first = await service.GetEventsAsync(meter, RecordRange.All);
|
||||
var second = await service.GetEventsAsync(meter, RecordRange.All, first.Next);
|
||||
|
||||
Assert.Equal((100, 1, 101), (first.Rows.Count, second.Rows.Count, first.Total));
|
||||
var ids = first.Rows.Concat(second.Rows).Select(e => e.Id).ToList();
|
||||
Assert.Equal(101, ids.Distinct().Count());
|
||||
Assert.Equal(ids.OrderDescending(), ids);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_entry_context_judges_a_reading_by_the_neighbours_the_guard_reads()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var meter = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh");
|
||||
|
||||
// Imported month rows: "July 2026" (400) and "August 2026" (500), stamped on the 1st (UTC, as the importer writes
|
||||
// them), describing the month's end.
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
db.Readings.Add(new Reading { MeterId = meter, Time = new DateTimeOffset(2026, 7, 1, 0, 0, 0, TimeSpan.Zero), Value = 400, Quality = ReadingQuality.Imported, Flags = ReadingFlags.MonthLabel });
|
||||
db.Readings.Add(new Reading { MeterId = meter, Time = new DateTimeOffset(2026, 8, 1, 0, 0, 0, TimeSpan.Zero), Value = 500, Quality = ReadingQuality.Imported, Flags = ReadingFlags.MonthLabel });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var service = Service();
|
||||
var at = Midnight(2026, 8, 20);
|
||||
var context = await service.GetReadingEntryContextAsync(meter, at);
|
||||
|
||||
// The latest reading by stamp is August's (500), but on the timeline a reading on 20 August comes after July's end
|
||||
// and before August's: the dialog judges it against 400, exactly like the guard — the old page, holding only
|
||||
// the latest row, would have called 450 a decrease.
|
||||
Assert.NotNull(context);
|
||||
Assert.Equal(500, context!.Latest!.Value);
|
||||
Assert.Equal(400, context.Previous!.Value);
|
||||
Assert.True(context.Monotonic);
|
||||
Assert.False(context.BoundaryExplainsDecrease);
|
||||
Assert.Null(context.AtTime);
|
||||
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
var ingestion = new IngestionService(db, Normalization(db));
|
||||
Assert.Equal(IngestionOutcome.RejectedDecrease, await ingestion.IngestByMeterAsync(meter, at, 350, renormalize: false, quality: ReadingQuality.Manual));
|
||||
Assert.Equal(IngestionOutcome.Written, await ingestion.IngestByMeterAsync(meter, at, 450, renormalize: false, quality: ReadingQuality.Manual));
|
||||
}
|
||||
|
||||
// The reading at that instant is now what a save would replace.
|
||||
var replacing = await service.GetReadingEntryContextAsync(meter, at);
|
||||
Assert.Equal(450, replacing!.AtTime!.Value);
|
||||
Assert.False(replacing.AtTime.IsRegisterStart);
|
||||
|
||||
// A swap after the previous reading explains a lower value.
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
db.MeterEvents.Add(new MeterEvent { MeterId = meter, Time = Midnight(2026, 9, 5), EventType = MeterEventType.MeterSwap, PrevValue = 520, NewValue = 0 });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var afterSwap = await service.GetReadingEntryContextAsync(meter, Midnight(2026, 9, 10));
|
||||
Assert.True(afterSwap!.BoundaryExplainsDecrease);
|
||||
|
||||
Assert.Null(await service.GetReadingEntryContextAsync(int.MaxValue, at));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_identity_read_carries_the_register_span_and_the_normalized_unit()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var meter = await box.MeterAsync(type, MeterMode.GenerationCounter, "kWh", installedAt: D(2026, 1, 1));
|
||||
await box.ReadingsAsync(meter, (Midnight(2026, 1, 1), 10), (Midnight(2026, 2, 1), 110));
|
||||
var service = Service();
|
||||
|
||||
var detail = await service.GetAsync(meter);
|
||||
|
||||
Assert.NotNull(detail);
|
||||
Assert.True(detail!.HasReadings);
|
||||
Assert.False(detail.HasEvents);
|
||||
Assert.Equal((10d, 110d), (detail.FirstReading!.Value, detail.LastReading!.Value));
|
||||
Assert.Equal(QuantityKind.Generation, detail.Kind);
|
||||
Assert.Equal("kWh", detail.NormalizedUnit);
|
||||
Assert.Equal(D(2026, 1, 1), detail.InstalledAt);
|
||||
Assert.Null(await service.GetAsync(int.MaxValue));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Markers_hold_the_events_and_tariff_changes_inside_the_range_only()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var meter = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh");
|
||||
var other = await box.TypeAsync();
|
||||
await box.TypePriceAsync(type, 0.30, D(2025, 1, 1));
|
||||
await box.TypePriceAsync(type, 0.32, D(2025, 7, 1));
|
||||
await box.MeterPriceAsync(meter, 0.25, D(2025, 3, 1));
|
||||
await box.TypePriceAsync(other, 0.99, D(2025, 3, 1));
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
db.MeterEvents.Add(new MeterEvent { MeterId = meter, Time = Midnight(2025, 2, 10), EventType = MeterEventType.Note, Notes = "before" });
|
||||
db.MeterEvents.Add(new MeterEvent { MeterId = meter, Time = Midnight(2025, 5, 10), EventType = MeterEventType.Note, Notes = "inside" });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var service = Service();
|
||||
var markers = await service.GetMarkersAsync(
|
||||
meter, new RecordRange(Midnight(2025, 3, 1), Midnight(2025, 7, 1)), D(2025, 3, 1), D(2025, 6, 30));
|
||||
|
||||
Assert.Equal("inside", Assert.Single(markers.Events).Notes);
|
||||
Assert.False(markers.MoreEvents);
|
||||
var change = Assert.Single(markers.TariffChanges);
|
||||
Assert.Equal((TariffScope.Meter, 0.25), (change.Scope, change.Value));
|
||||
|
||||
// The tariff list: the meter's own and its type's (and any global), never another type's.
|
||||
var tariffs = await service.GetTariffsAsync(meter);
|
||||
Assert.Contains(tariffs, t => t.Scope == TariffScope.Meter && t.ScopeId == meter);
|
||||
Assert.Equal(2, tariffs.Count(t => t.Scope == TariffScope.EnergyType && t.ScopeId == type));
|
||||
Assert.DoesNotContain(tariffs, t => t.Scope == TariffScope.EnergyType && t.ScopeId == other);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_virtual_meters_calculation_names_its_sources_and_its_problems()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var a = await box.MeterAsync(type, MeterMode.GenerationCounter, "kWh", name: "PV Ost");
|
||||
var b = await box.MeterAsync(type, MeterMode.GenerationCounter, "kWh", name: "PV West");
|
||||
var sum = await box.VirtualAsync(type, $"m{a} + m{b}", QuantityKind.Generation, "kWh", VirtualCostRule.None);
|
||||
var broken = await box.VirtualAsync(type, $"m{a} + m{int.MaxValue}", QuantityKind.Generation, "kWh", VirtualCostRule.None);
|
||||
var service = Service();
|
||||
|
||||
var calculation = await service.GetCalculationAsync(sum);
|
||||
|
||||
Assert.NotNull(calculation);
|
||||
Assert.Equal(VirtualMeterStatus.Valid, calculation!.Status);
|
||||
Assert.Equal($"m{a} + m{b}", calculation.Expression);
|
||||
Assert.Equal((QuantityKind.Generation, "kWh"), (calculation.Kind, calculation.Unit));
|
||||
Assert.Equal(["PV Ost", "PV West"], calculation.Sources.Select(s => s.Name));
|
||||
Assert.All(calculation.Sources, s => Assert.True(s.Exists));
|
||||
Assert.Equal("PV West", calculation.NameOf(b));
|
||||
Assert.Empty(calculation.Problems);
|
||||
|
||||
var invalid = await service.GetCalculationAsync(broken);
|
||||
Assert.Equal(VirtualMeterStatus.Invalid, invalid!.Status);
|
||||
var problem = Assert.Single(invalid.Problems);
|
||||
Assert.Equal(VirtualProblemKind.UnknownMeter, problem.Kind);
|
||||
Assert.Equal([int.MaxValue], problem.MeterIds);
|
||||
Assert.Contains(invalid.Sources, s => s.MeterId == int.MaxValue && !s.Exists);
|
||||
|
||||
// A physical meter has no calculation.
|
||||
Assert.Null(await service.GetCalculationAsync(a));
|
||||
}
|
||||
|
||||
private MeterDetailService Service() =>
|
||||
new(fx, Microsoft.Extensions.Options.Options.Create(new MeterVaultOptions { TimeZone = BerlinId }));
|
||||
|
||||
private static Consumption Row(int meter, int hour, ConsumptionKind kind) => new()
|
||||
{
|
||||
MeterId = meter,
|
||||
Time = Start.AddHours(hour),
|
||||
Amount = 1,
|
||||
Kind = kind,
|
||||
Quality = ReadingQuality.Measured,
|
||||
};
|
||||
|
||||
private async Task InsertReadingsAsync(int meter, int count, int fromHour = 0)
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
db.Readings.Add(new Reading { MeterId = meter, Time = Start.AddHours(fromHour + i), Value = fromHour + i, Quality = ReadingQuality.Measured });
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
using MeterVault.App;
|
||||
using MeterVault.App.Analysis;
|
||||
using MeterVault.App.MeterDetails;
|
||||
using MeterVault.Core.Analysis;
|
||||
using MeterVault.Core.Analysis.Coverage;
|
||||
using MeterVault.Core.Domain;
|
||||
using MeterVault.Infrastructure.Analysis;
|
||||
using MeterVault.Infrastructure.Dashboard;
|
||||
using static MeterVault.Integration.Tests.Analysis.AnalysisUiTestData;
|
||||
|
||||
namespace MeterVault.Integration.Tests.MeterPage;
|
||||
|
||||
/// <summary>
|
||||
/// The meter page's pure rules (brief §7.2, D-09, D-46, D-47, D-50): which tab a link opens, how the manual-entry
|
||||
/// dialog judges an entry against its own context, the keyset pager, the record tabs' date filter and the projection's
|
||||
/// suppression rules. No database.
|
||||
/// </summary>
|
||||
public sealed class MeterPageLogicTests
|
||||
{
|
||||
// ---------------------------------------------------------------------------------------------------- tab keys
|
||||
|
||||
[Theory]
|
||||
[InlineData("analysis", MeterMode.CumulativeCounter, "analysis")]
|
||||
[InlineData("readings", MeterMode.CumulativeCounter, "readings")]
|
||||
[InlineData("consumption", MeterMode.CumulativeCounter, "normalized")]
|
||||
[InlineData("Consumption", MeterMode.ConsumableBalance, "normalized")]
|
||||
[InlineData("events", MeterMode.ConsumableBalance, "events")]
|
||||
[InlineData("tariffs", MeterMode.GenerationCounter, "tariffs")]
|
||||
[InlineData("sources", MeterMode.RuntimeCounter, "sources")]
|
||||
[InlineData("calculation", MeterMode.CumulativeCounter, "analysis")]
|
||||
[InlineData("sources", MeterMode.Virtual, "calculation")]
|
||||
[InlineData("readings", MeterMode.Virtual, "analysis")]
|
||||
[InlineData("normalized", MeterMode.Virtual, "analysis")]
|
||||
[InlineData("consumption", MeterMode.Virtual, "analysis")]
|
||||
[InlineData(" EVENTS ", MeterMode.Virtual, "events")]
|
||||
[InlineData(null, MeterMode.Virtual, "analysis")]
|
||||
[InlineData("", MeterMode.DirectDelta, "analysis")]
|
||||
public void Every_old_and_new_tab_link_opens_a_tab_the_meter_shows(string? requested, MeterMode mode, string expected)
|
||||
{
|
||||
Assert.Equal(expected, MeterLinks.ResolveTab(requested, mode));
|
||||
Assert.Equal(MeterLinks.VisibleTabs(mode).ToList().IndexOf(expected), MeterLinks.PanelIndex(requested, mode));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_links_other_pages_write_open_the_tab_they_name()
|
||||
{
|
||||
// Quick entry, event links and the connector detour still land on the tab they meant, with their action.
|
||||
Assert.Equal("/meters/7?tab=readings&action=reading", MeterLinks.QuickEntry(7, MeterMode.CumulativeCounter));
|
||||
Assert.Equal("/meters/7?tab=events&action=tank-level", MeterLinks.QuickEntry(7, MeterMode.ConsumableBalance));
|
||||
Assert.Null(MeterLinks.QuickEntry(9, MeterMode.Virtual));
|
||||
Assert.Equal("/meters/7?tab=events&action=swap", MeterLinks.Event(7, MeterEventType.MeterSwap));
|
||||
Assert.StartsWith("/meters/7?tab=sources&action=source", MeterLinks.Source(7, 3, SourceType.Mqtt, 12), StringComparison.Ordinal);
|
||||
Assert.Equal(MeterLinks.TabSources, MeterLinks.ResolveTab("sources", MeterMode.CumulativeCounter));
|
||||
Assert.Equal(MeterLinks.TabEvents, MeterLinks.ResolveTab("events", MeterMode.ConsumableBalance));
|
||||
|
||||
// A drill-down into records keeps the range it came from, on the Normalized data tab.
|
||||
var query = AnalysisQuery.Default(MeterAnalysisLoader.DefaultsFor(7));
|
||||
var bucket = Buckets(D(2025, 3, 1), D(2025, 3, 31))[0];
|
||||
Assert.Equal("/meters/7?tab=normalized&from=2025-03-01&to=2025-03-31", AnalysisNavigation.NormalizedData(7, query, bucket));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_meter_page_reads_its_query_with_the_meter_as_scope()
|
||||
{
|
||||
var defaults = MeterAnalysisLoader.DefaultsFor(7);
|
||||
var plain = AnalysisQuery.Parse("/meters/7?tab=events", defaults);
|
||||
Assert.Equal(QueryScope.ForMeter(7), plain.Scope);
|
||||
Assert.Equal(PeriodPreset.Last12Months, plain.Period);
|
||||
Assert.Equal(ComparisonKind.PreviousYear, plain.Comparison.Kind);
|
||||
|
||||
// A stray scope in the address cannot make the page analyse something else.
|
||||
var stray = AnalysisQuery.Parse("/meters/7?scope=type&id=3&period=ytd", defaults);
|
||||
var forced = MeterAnalysisLoader.ForMeter(stray, 7);
|
||||
Assert.Equal(QueryScope.ForMeter(7), forced.Scope);
|
||||
Assert.Equal(PeriodPreset.YearToDate, forced.Period);
|
||||
|
||||
// The tab and the action are not part of the analysis state: changing them is not a new analysis (D-46).
|
||||
Assert.Equal(
|
||||
AnalysisQuery.Parse("/meters/7?tab=analysis&period=ytd", defaults),
|
||||
AnalysisQuery.Parse("/meters/7?tab=events&action=swap&period=ytd", defaults));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------ manual-entry verdict
|
||||
|
||||
private static readonly DateTimeOffset T = new(2026, 9, 19, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static ReadingEntryContext Context(
|
||||
double? previous = 1000, double? latest = 1000, DateTimeOffset? latestAt = null, bool monotonic = true,
|
||||
bool boundary = false, ExistingReading? atTime = null, DateTimeOffset? at = null) =>
|
||||
new(
|
||||
MeterId: 1,
|
||||
At: at ?? T,
|
||||
Unit: "kWh",
|
||||
InitialBaseline: 0,
|
||||
Monotonic: monotonic,
|
||||
Latest: latest is { } l ? new RegisterPoint(latestAt ?? T.AddDays(-1), l) : null,
|
||||
Previous: previous is { } p ? new RegisterPoint(T.AddDays(-1), p) : null,
|
||||
BoundaryExplainsDecrease: boundary,
|
||||
AtTime: atTime);
|
||||
|
||||
[Fact]
|
||||
public void A_lower_value_on_a_register_is_flagged_unless_a_swap_or_reset_explains_it()
|
||||
{
|
||||
var verdict = ReadingEntryVerdict.Of(Context(), 999, T, T);
|
||||
Assert.True(verdict.WouldBeRejected);
|
||||
Assert.Null(verdict.ChangeSincePrevious);
|
||||
Assert.Equal(1000, verdict.Previous!.Value);
|
||||
|
||||
Assert.False(ReadingEntryVerdict.Of(Context(boundary: true), 999, T, T).WouldBeRejected);
|
||||
Assert.False(ReadingEntryVerdict.Of(Context(monotonic: false), 999, T, T).WouldBeRejected);
|
||||
|
||||
var up = ReadingEntryVerdict.Of(Context(), 1012.5, T, T);
|
||||
Assert.False(up.WouldBeRejected);
|
||||
Assert.Equal(12.5, up.ChangeSincePrevious!.Value, 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_backdated_entry_is_judged_against_the_reading_before_it_not_the_latest()
|
||||
{
|
||||
// The old page only held the latest reading and gave a backdated entry no verdict; the dialog's own context
|
||||
// (D-50) knows the reading before the entered time, as the ingestion guard does.
|
||||
var context = Context(previous: 500, latest: 1000, latestAt: T.AddDays(10));
|
||||
var lower = ReadingEntryVerdict.Of(context, 450, T, T.AddDays(11));
|
||||
Assert.True(lower.IsBackdated);
|
||||
Assert.True(lower.WouldBeRejected);
|
||||
|
||||
var between = ReadingEntryVerdict.Of(context, 700, T, T.AddDays(11));
|
||||
Assert.True(between.IsBackdated);
|
||||
Assert.False(between.WouldBeRejected);
|
||||
Assert.Equal(200, between.ChangeSincePrevious!.Value, 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_context_for_another_instant_gives_no_verdict_rather_than_a_wrong_one()
|
||||
{
|
||||
// The pickers moved and the new context is still being read: nothing is judged against the old instant.
|
||||
var verdict = ReadingEntryVerdict.Of(Context(), 1, T.AddHours(1), T.AddHours(1));
|
||||
Assert.False(verdict.WouldBeRejected);
|
||||
Assert.False(verdict.ReplacesReading);
|
||||
Assert.Null(verdict.ChangeSincePrevious);
|
||||
|
||||
Assert.False(ReadingEntryVerdict.Of(null, 1, T, T).WouldBeRejected);
|
||||
Assert.True(ReadingEntryVerdict.Of(null, 1, T.AddMinutes(2), T).IsFuture);
|
||||
Assert.False(ReadingEntryVerdict.Of(null, 1, T.AddSeconds(30), T).IsFuture);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Saving_over_a_stored_reading_says_whether_it_is_a_swap_start()
|
||||
{
|
||||
var plain = ReadingEntryVerdict.Of(Context(atTime: new ExistingReading(T, 1000, ReadingQuality.Manual, ReadingFlags.None)), 1001, T, T);
|
||||
Assert.True(plain.ReplacesReading);
|
||||
Assert.False(plain.ReplacesRegisterStart);
|
||||
|
||||
var start = ReadingEntryVerdict.Of(Context(atTime: new ExistingReading(T, 0, ReadingQuality.Manual, ReadingFlags.MeterSwap)), 3, T, T);
|
||||
Assert.True(start.ReplacesReading);
|
||||
Assert.True(start.ReplacesRegisterStart);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- record pager
|
||||
|
||||
[Fact]
|
||||
public void The_pager_walks_keyset_pages_and_back()
|
||||
{
|
||||
var pager = new RecordPager();
|
||||
Assert.Null(pager.Current);
|
||||
Assert.False(pager.CanGoNewer);
|
||||
Assert.Equal(1, pager.FirstRow);
|
||||
|
||||
var first = new RecordCursor(T, 0);
|
||||
var second = new RecordCursor(T.AddDays(-5), 3);
|
||||
pager.Older(first);
|
||||
pager.Older(second);
|
||||
Assert.Equal(second, pager.Current);
|
||||
Assert.Equal(2, pager.PageIndex);
|
||||
Assert.Equal((2 * MeterDetailService.PageSize) + 1, pager.FirstRow);
|
||||
|
||||
pager.Newer();
|
||||
Assert.Equal(first, pager.Current);
|
||||
pager.Newer();
|
||||
pager.Newer();
|
||||
Assert.Null(pager.Current);
|
||||
Assert.Equal(0, pager.PageIndex);
|
||||
|
||||
pager.Older(first);
|
||||
pager.Reset();
|
||||
Assert.Null(pager.Current);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- record filter
|
||||
|
||||
[Fact]
|
||||
public void Record_tabs_filter_by_the_page_period_and_show_everything_for_all_history()
|
||||
{
|
||||
var custom = Range(D(2025, 3, 1), D(2025, 3, 31));
|
||||
var range = MeterRecordRange.Of(custom);
|
||||
Assert.Equal(new DateTimeOffset(2025, 2, 28, 23, 0, 0, TimeSpan.Zero), range.From);
|
||||
Assert.Equal(new DateTimeOffset(2025, 3, 31, 22, 0, 0, TimeSpan.Zero), range.To); // CEST from 30 March
|
||||
|
||||
// Month to date: the rows of the whole month, so rows stamped later this month (after now) are listed too.
|
||||
var mtd = PeriodResolver.Resolve(PeriodPreset.MonthToDate, null, null, Now, Berlin);
|
||||
var month = MeterRecordRange.Of(mtd);
|
||||
Assert.Equal(new DateTimeOffset(2026, 8, 31, 22, 0, 0, TimeSpan.Zero), month.From);
|
||||
Assert.Equal(new DateTimeOffset(2026, 9, 30, 22, 0, 0, TimeSpan.Zero), month.To);
|
||||
|
||||
var all = PeriodResolver.Resolve(PeriodPreset.AllHistory, null, null, Now, Berlin, D(2019, 1, 1), D(2026, 5, 31));
|
||||
Assert.Same(RecordRange.All, MeterRecordRange.Of(all));
|
||||
Assert.False(RecordRange.All.IsBounded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Record_tabs_show_the_dates_they_list_and_mark_rows_after_now() => In("en", () =>
|
||||
{
|
||||
// D-04: the record tabs list the rows of the whole named range, rows dated after now included; the dates on screen
|
||||
// must say so (the whole month, not "up to today"), and each such row carries a mark.
|
||||
var mtd = PeriodResolver.Resolve(PeriodPreset.MonthToDate, null, null, Now, Berlin);
|
||||
Assert.Equal("Sep 1 – Sep 19, 2026", Format.PeriodRange(mtd));
|
||||
Assert.Equal("Sep 1 – Sep 30, 2026", MeterRecordRange.Text(mtd));
|
||||
|
||||
var custom = PeriodResolver.Resolve(PeriodPreset.Custom, D(2026, 9, 19), D(2026, 9, 25), Now, Berlin);
|
||||
Assert.Equal("Sep 19 – Sep 25, 2026", MeterRecordRange.Text(custom));
|
||||
|
||||
Assert.True(MeterRecordRange.IsAfterNow(new DateTimeOffset(2026, 9, 25, 4, 0, 0, TimeSpan.Zero), mtd));
|
||||
Assert.True(MeterRecordRange.IsAfterNow(Now.AddMinutes(1), mtd));
|
||||
Assert.False(MeterRecordRange.IsAfterNow(Now, mtd));
|
||||
Assert.False(MeterRecordRange.IsAfterNow(new DateTimeOffset(2026, 9, 1, 0, 0, 0, TimeSpan.Zero), mtd));
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------------------------------- projection
|
||||
|
||||
private static AnalysisSeries MonthSeries(double total, ResolutionClass? resolution, DateTimeOffset coveredFrom, DateTimeOffset coveredTo,
|
||||
Provenance provenance = Provenance.Measured) =>
|
||||
Series(1, "Haus", [BucketValue.Available(total, provenance)], new BucketValue(total, BucketStatus.Partial, provenance)) with
|
||||
{
|
||||
Resolution = resolution,
|
||||
Availability = AvailableRange.Of(coveredFrom, coveredTo, Berlin),
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void A_live_month_to_date_projects_the_covered_rate_over_the_rest_of_the_month()
|
||||
{
|
||||
var mtd = PeriodResolver.Resolve(PeriodPreset.MonthToDate, null, null, Now, Berlin);
|
||||
var series = MonthSeries(180, ResolutionClass.Day, new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), Now.AddHours(-2));
|
||||
|
||||
var projection = MeterProjection.For(series, mtd);
|
||||
|
||||
Assert.NotNull(projection);
|
||||
var covered = (Now.AddHours(-2) - mtd.From).TotalDays;
|
||||
var remaining = (mtd.NominalEnd()!.Value - Now).TotalDays;
|
||||
Assert.Equal(180 + (180 / covered * remaining), projection!.Value, 6);
|
||||
Assert.Equal((int)Math.Round(covered), projection.Days);
|
||||
Assert.Equal("kWh", projection.Unit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_projection_is_suppressed_for_old_coarse_short_or_opening_balance_data()
|
||||
{
|
||||
var mtd = PeriodResolver.Resolve(PeriodPreset.MonthToDate, null, null, Now, Berlin);
|
||||
var start = new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
|
||||
// Monthly data cannot project a month.
|
||||
Assert.Null(MeterProjection.For(MonthSeries(180, ResolutionClass.Month, start, Now), mtd));
|
||||
|
||||
// Data that stopped days ago is not live: two daily intervals is the limit.
|
||||
Assert.Null(MeterProjection.For(MonthSeries(180, ResolutionClass.Day, start, Now.AddDays(-3)), mtd));
|
||||
|
||||
// Less than a week covered this month.
|
||||
Assert.Null(MeterProjection.For(MonthSeries(180, ResolutionClass.Day, mtd.From.AddDays(12), Now), mtd));
|
||||
|
||||
// An opening balance of unknown start is never extrapolated (D-14).
|
||||
Assert.Null(MeterProjection.For(MonthSeries(180, ResolutionClass.Day, start, Now, Provenance.OpeningBalance), mtd));
|
||||
|
||||
// Only month and year to date are projected.
|
||||
var twelve = PeriodResolver.Resolve(PeriodPreset.Last12Months, null, null, Now, Berlin);
|
||||
Assert.Null(MeterProjection.For(MonthSeries(180, ResolutionClass.Day, start, Now), twelve));
|
||||
|
||||
// A year to date may use monthly data, as long as it is current.
|
||||
var ytd = PeriodResolver.Resolve(PeriodPreset.YearToDate, null, null, Now, Berlin);
|
||||
Assert.NotNull(MeterProjection.For(MonthSeries(1800, ResolutionClass.Month, start, Now.AddDays(-10)), ytd));
|
||||
Assert.Null(MeterProjection.For(MonthSeries(1800, ResolutionClass.Month, start, Now.AddDays(-100)), ytd));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using MeterVault.App;
|
||||
using MeterVault.Core.Domain;
|
||||
using MeterVault.Integration.Tests.Costing;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace MeterVault.Integration.Tests.MeterPage;
|
||||
|
||||
/// <summary>
|
||||
/// Brief §3.2 "Change the source/connector: Meter → Sources → Edit connection": the connector a source uses opens for
|
||||
/// editing from the meter's Sources tab, through the connector page's way back to the meter (the draft detour).
|
||||
/// </summary>
|
||||
[Collection("Timescale")]
|
||||
public sealed class MeterSourcesRenderTests(TimescaleFixture fx)
|
||||
{
|
||||
[Fact]
|
||||
public async Task The_sources_tab_links_the_connector_in_use_for_editing()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync("m³");
|
||||
var meter = await box.MeterAsync(type, MeterMode.CumulativeCounter, "m³", name: $"Wasser {Guid.NewGuid():N}");
|
||||
int endpointId;
|
||||
int sourceId;
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
var endpoint = new IngestionEndpoint
|
||||
{
|
||||
Type = EndpointType.HomeAssistant,
|
||||
Name = $"HA {Guid.NewGuid():N}",
|
||||
Config = """{"baseUrl":"http://ha.local:8123","tokenEnv":"HA_TOKEN"}""",
|
||||
};
|
||||
db.IngestionEndpoints.Add(endpoint);
|
||||
await db.SaveChangesAsync();
|
||||
endpointId = endpoint.Id;
|
||||
var source = new MeterSource
|
||||
{
|
||||
MeterId = meter,
|
||||
SourceType = SourceType.HomeAssistant,
|
||||
EndpointId = endpointId,
|
||||
Config = """{"entityId":"sensor.water_total"}""",
|
||||
};
|
||||
db.MeterSources.Add(source);
|
||||
await db.SaveChangesAsync();
|
||||
sourceId = source.Id;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var factory = new MeterVaultAppFactory(fx.ConnectionString);
|
||||
using var client = factory.CreateClient();
|
||||
var html = System.Net.WebUtility.HtmlDecode(
|
||||
await client.GetStringAsync(new Uri($"/meters/{meter}?tab=sources", UriKind.Relative)));
|
||||
|
||||
var edit = MeterLinks.EditConnector(meter, sourceId, SourceType.HomeAssistant, endpointId);
|
||||
Assert.Contains($"href=\"{edit}\"", html, StringComparison.Ordinal);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
await db.MeterSources.Where(s => s.Id == sourceId).ExecuteDeleteAsync();
|
||||
await db.IngestionEndpoints.Where(e => e.Id == endpointId).ExecuteDeleteAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user