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,250 @@
|
||||
using MeterVault.Core.Analysis;
|
||||
using MeterVault.Core.Analysis.Costing;
|
||||
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 Microsoft.EntityFrameworkCore;
|
||||
using static MeterVault.Integration.Tests.Costing.CostSandbox;
|
||||
|
||||
namespace MeterVault.Integration.Tests.Specialized;
|
||||
|
||||
/// <summary>
|
||||
/// The Tanks & consumables read model (brief §7.5, D-54) on the shared readers, on the frozen clock of
|
||||
/// <see cref="CostSandbox.Now"/> (19 September 2026): the last dipstick kept apart from the contents estimated now; a
|
||||
/// period that is over shows its own end's contents, not today's; deliveries only from the period; usage from the
|
||||
/// analysis reader; burner runtime and the burn rate; and a cost that is unknown stays unknown, never 0 (D-38, A-16).
|
||||
/// </summary>
|
||||
/// <remarks>The view reads every consumable meter, so every test starts from — and leaves — an instance without meters.</remarks>
|
||||
[Collection("Timescale")]
|
||||
public sealed class ConsumableServiceTests(TimescaleFixture fx) : IAsyncLifetime
|
||||
{
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
await SolarServiceTests.ClearDataAsync(db);
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
await SolarServiceTests.ClearDataAsync(db);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Usage_is_up_to_now_and_an_unpriced_cost_is_not_a_zero()
|
||||
{
|
||||
// A dipstick dated after now is no actual: June 200, July 1,800 + 1,000 − 2,600 = 200, not the 25 September draw.
|
||||
// The tank has no tariff: its cost is "not priced", with no value — never a confident 0 €.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync("L");
|
||||
var tank = await TankAsync(box, type, 3000, installedAt: D(2026, 5, 1));
|
||||
await EventsAsync(
|
||||
Level(tank, Midnight(2026, 6, 1), 2000),
|
||||
Level(tank, Midnight(2026, 7, 1), 1800),
|
||||
Delivery(tank, Midnight(2026, 7, 15), 1000),
|
||||
Level(tank, Midnight(2026, 8, 1), 2600),
|
||||
Level(tank, Midnight(2026, 9, 25), 2500));
|
||||
await box.RecomputeAsync(tank);
|
||||
|
||||
var unpriced = await TankAsync(tank, Custom(D(2026, 6, 1), D(2026, 9, 30)));
|
||||
|
||||
Assert.Equal(400, unpriced.Usage!.Total.Value!.Value, 6);
|
||||
Assert.Equal("L", unpriced.Usage.Unit);
|
||||
Assert.Equal((2600d, 0d), (unpriced.EstimatedNow!.Volume, unpriced.EstimatedNow.DeliveredSince));
|
||||
Assert.Equal(Midnight(2026, 8, 1), unpriced.LastDipstick!.Time);
|
||||
Assert.Equal(2600d / 3000, unpriced.FillFraction!.Value, 6);
|
||||
Assert.False(unpriced.PeriodEndsBeforeNow);
|
||||
Assert.Null(unpriced.AtPeriodEnd);
|
||||
|
||||
var cost = unpriced.Cost!.Total;
|
||||
Assert.Equal(CostStatus.NotPriced, cost.Status);
|
||||
Assert.Null(cost.Cost);
|
||||
Assert.Equal(CostStatus.NotPriced, Assert.Single(cost.MissingPrices).Reason);
|
||||
Assert.Contains(unpriced.Cost.Attention, a => a.Kind == CostAttentionKind.MissingPrice);
|
||||
|
||||
await box.TypePriceAsync(type, 1.50, D(2026, 1, 1), unit: "EUR/L");
|
||||
var priced = await TankAsync(tank, Custom(D(2026, 6, 1), D(2026, 9, 30)));
|
||||
Assert.Equal((400 * 1.50, CostStatus.Priced), (Math.Round(priced.Cost!.Total.Cost!.Value, 6), priced.Cost.Total.Status));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_tank_dipped_every_few_months_has_its_cost_and_an_unplaceable_one_is_unknown()
|
||||
{
|
||||
// A-16: dipsticks on 17 January, 3 April, 12 September and 20 December at 1.10 €/L. No month can take a draw, but
|
||||
// the year holds all three whole and one price covers it: 2,100 L cost 2,310 €. The first half cuts the April –
|
||||
// September draw: its cost cannot be placed, and it has no value at all rather than 0 €.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync("L");
|
||||
var tank = await TankAsync(box, type, 7000);
|
||||
await EventsAsync(
|
||||
Level(tank, Midnight(2025, 1, 17), 5000),
|
||||
Level(tank, Midnight(2025, 4, 3), 4200),
|
||||
Level(tank, Midnight(2025, 9, 12), 3600),
|
||||
Level(tank, Midnight(2025, 12, 20), 2900));
|
||||
await box.RecomputeAsync(tank);
|
||||
await box.TypePriceAsync(type, 1.10, D(2025, 1, 1), unit: "EUR/L");
|
||||
|
||||
var year = await TankAsync(tank, Year(2025));
|
||||
Assert.Equal(2100, year.Usage!.Total.Value!.Value, 6);
|
||||
Assert.Equal((2310d, CostStatus.Priced), (Math.Round(year.Cost!.Total.Cost!.Value, 6), year.Cost.Total.Status));
|
||||
|
||||
var half = await TankAsync(tank, Custom(D(2025, 1, 1), D(2025, 6, 30)));
|
||||
Assert.Null(half.Cost!.Total.Cost);
|
||||
Assert.Equal(BucketStatus.Unresolved, half.Cost.Total.Availability);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_period_that_is_over_shows_its_own_end_not_today_and_only_its_deliveries()
|
||||
{
|
||||
// 10 January 3,000 L; 1 February 2,000 L delivered; 1 March 4,000 L; 1 August 2,500 L; 20 August 1,000 L delivered.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync("L");
|
||||
var tank = await TankAsync(box, type, 7000);
|
||||
await EventsAsync(
|
||||
Level(tank, Midnight(2026, 1, 10), 3000),
|
||||
Delivery(tank, Midnight(2026, 2, 1), 2000),
|
||||
Level(tank, Midnight(2026, 3, 1), 4000),
|
||||
Level(tank, Midnight(2026, 8, 1), 2500),
|
||||
Delivery(tank, Midnight(2026, 8, 20), 1000));
|
||||
await box.RecomputeAsync(tank);
|
||||
|
||||
// January – February is over: its end holds the January dipstick plus the February delivery, and only that
|
||||
// delivery is listed. "Now" is still the August dipstick plus the August delivery, apart from it.
|
||||
var winter = await TankAsync(tank, Custom(D(2026, 1, 1), D(2026, 2, 28)));
|
||||
Assert.True(winter.PeriodEndsBeforeNow);
|
||||
Assert.Equal((5000d, 2000d, 1), (winter.AtPeriodEnd!.Volume, winter.AtPeriodEnd.DeliveredSince, winter.AtPeriodEnd.DeliveriesSince));
|
||||
Assert.Equal(Midnight(2026, 1, 10), winter.AtPeriodEnd.Dipstick.Time);
|
||||
Assert.Equal([Midnight(2026, 2, 1)], winter.Deliveries.Select(d => d.Time));
|
||||
Assert.Equal(2000, winter.DeliveredInPeriod, 6);
|
||||
Assert.Equal((3500d, Midnight(2026, 8, 1)), (winter.EstimatedNow!.Volume, winter.EstimatedNow.Dipstick.Time));
|
||||
Assert.Equal(Midnight(2026, 8, 1), winter.LastDipstick!.Time);
|
||||
|
||||
// A period ending the day before a dipstick does not see it: the end is exclusive (D-03).
|
||||
var february = await TankAsync(tank, Custom(D(2026, 2, 1), D(2026, 2, 28)));
|
||||
Assert.Equal(Midnight(2026, 1, 10), february.AtPeriodEnd!.Dipstick.Time);
|
||||
|
||||
// Before the first dipstick there is no contents to show — not a 0 L tank.
|
||||
var december = await TankAsync(tank, Custom(D(2025, 12, 1), D(2025, 12, 31)));
|
||||
Assert.True(december.PeriodEndsBeforeNow);
|
||||
Assert.Null(december.AtPeriodEnd);
|
||||
Assert.Empty(december.Deliveries);
|
||||
|
||||
// A period up to now has no separate end: its deliveries are both, newest first.
|
||||
var year = await TankAsync(tank, Preset(PeriodPreset.YearToDate));
|
||||
Assert.False(year.PeriodEndsBeforeNow);
|
||||
Assert.Null(year.AtPeriodEnd);
|
||||
Assert.Equal([Midnight(2026, 8, 20), Midnight(2026, 2, 1)], year.Deliveries.Select(d => d.Time));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_forecast_is_a_projection_and_hidden_once_the_dipstick_is_older_than_60_days()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync("L");
|
||||
var fresh = await TankAsync(box, type, 7000);
|
||||
await EventsAsync(Level(fresh, Midnight(2026, 6, 1), 3000), Level(fresh, Midnight(2026, 9, 1), 2100));
|
||||
var stale = await TankAsync(box, type, 7000);
|
||||
await EventsAsync(Level(stale, Midnight(2026, 4, 1), 3000), Level(stale, Midnight(2026, 7, 1), 2100));
|
||||
await box.RecomputeAsync(fresh, stale);
|
||||
|
||||
var analysis = await Service().GetAsync(new ConsumableRequest(Preset(PeriodPreset.Last12Months)));
|
||||
|
||||
// 900 L over the 92 days from 1 June to 1 September: 2,100 L last 214.7 days from 1 September.
|
||||
var projected = analysis.Tanks.Single(t => t.MeterId == fresh).Forecast;
|
||||
Assert.Equal(TankForecastState.Projected, projected.State);
|
||||
Assert.Equal(92, projected.BasisDays);
|
||||
Assert.Equal(900d / 92, projected.PerDay!.Value, 6);
|
||||
Assert.Equal(D(2027, 4, 3), projected.EmptyOn);
|
||||
Assert.Equal(18, projected.DipstickAgeDays);
|
||||
|
||||
var hidden = analysis.Tanks.Single(t => t.MeterId == stale).Forecast;
|
||||
Assert.Equal(TankForecastState.DipstickTooOld, hidden.State);
|
||||
Assert.Null(hidden.EmptyOn);
|
||||
Assert.Equal(80, hidden.DipstickAgeDays);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Burner_runtime_and_the_burn_rate_follow_the_period()
|
||||
{
|
||||
// The burner of the tank's energy type ran 100 h in June and 200 h in July; the tank lost 300 L and 400 L. The
|
||||
// empirical rate is 700 L ÷ 300 h. A tank set to a fixed nozzle rate shows that rate instead.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync("L");
|
||||
var tank = await TankAsync(box, type, 7000);
|
||||
await EventsAsync(Level(tank, Midnight(2026, 6, 1), 5000), Level(tank, Midnight(2026, 7, 1), 4700), Level(tank, Midnight(2026, 8, 1), 4300));
|
||||
await box.RecomputeAsync(tank);
|
||||
var burner = await box.MeterAsync(type, MeterMode.RuntimeCounter, "h", D(2026, 6, 1));
|
||||
await box.MonthlyReadingsAsync(burner, D(2026, 6, 1), 100, 200);
|
||||
|
||||
var summer = await TankAsync(tank, Custom(D(2026, 6, 1), D(2026, 7, 31)));
|
||||
|
||||
var runtime = Assert.Single(summer.Runtime);
|
||||
Assert.Equal(burner, runtime.MeterId);
|
||||
Assert.Equal(("h", 300d), (summer.RuntimeUnit, summer.RuntimeTotal!.Value!.Value));
|
||||
Assert.Equal((TankRateSource.Empirical, "L/h"), (summer.Rate!.Source, summer.Rate.Unit));
|
||||
Assert.Equal((700d / 300, BucketStatus.Available), (summer.Rate.Value.Value!.Value, summer.Rate.Value.Status));
|
||||
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
await db.Tanks.Where(t => t.MeterId == tank).ExecuteUpdateAsync(s => s
|
||||
.SetProperty(t => t.RateMode, TankRateMode.Fixed)
|
||||
.SetProperty(t => t.FixedRate, 2.1));
|
||||
}
|
||||
|
||||
var fixedRate = await TankAsync(tank, Custom(D(2026, 6, 1), D(2026, 7, 31)));
|
||||
Assert.Equal((TankRateSource.Fixed, 2.1), (fixedRate.Rate!.Source, fixedRate.Rate.Value.Value!.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_consumable_meter_without_a_tank_is_listed_for_setup()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync("L");
|
||||
var bare = await box.MeterAsync(type, MeterMode.ConsumableBalance, "L", name: $"Tank {Guid.NewGuid():N}");
|
||||
|
||||
var analysis = await Service().GetAsync(new ConsumableRequest(Preset(PeriodPreset.Last12Months)));
|
||||
|
||||
Assert.Empty(analysis.Tanks);
|
||||
Assert.Equal([bare], analysis.Unconfigured.Select(u => u.MeterId));
|
||||
Assert.Null(analysis.Quantities);
|
||||
Assert.Null(await Service().GetAvailabilityAsync(Now));
|
||||
}
|
||||
|
||||
private async Task<TankAnalysis> TankAsync(int tank, ResolvedPeriod period)
|
||||
{
|
||||
var analysis = await Service().GetAsync(new ConsumableRequest(period) { Bucket = BucketSize.Month });
|
||||
return analysis.Tanks.Single(t => t.MeterId == tank);
|
||||
}
|
||||
|
||||
private ConsumableService Service()
|
||||
{
|
||||
var options = Microsoft.Extensions.Options.Options.Create(new MeterVaultOptions { TimeZone = BerlinId, Currency = "EUR" });
|
||||
var reader = new AnalysisReader(fx, options);
|
||||
return new ConsumableService(fx, reader, new CostReader(fx, reader, options));
|
||||
}
|
||||
|
||||
private async Task<int> TankAsync(CostSandbox box, short type, double capacity, DateOnly? installedAt = null)
|
||||
{
|
||||
var meter = await box.MeterAsync(type, MeterMode.ConsumableBalance, "L", installedAt);
|
||||
await using var db = fx.CreateContext();
|
||||
db.Tanks.Add(new Tank { MeterId = meter, Capacity = capacity, Unit = "L" });
|
||||
await db.SaveChangesAsync();
|
||||
return meter;
|
||||
}
|
||||
|
||||
private async Task EventsAsync(params MeterEvent[] events)
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
db.MeterEvents.AddRange(events);
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private static MeterEvent Level(int meterId, DateTimeOffset time, double litres) =>
|
||||
new() { MeterId = meterId, EventType = MeterEventType.TankLevel, Time = time.ToUniversalTime(), Amount = litres, Unit = "L" };
|
||||
|
||||
private static MeterEvent Delivery(int meterId, DateTimeOffset time, double litres) =>
|
||||
new() { MeterId = meterId, EventType = MeterEventType.Delivery, Time = time.ToUniversalTime(), Amount = litres, Unit = "L" };
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using MeterVault.Core.Analysis;
|
||||
using MeterVault.Infrastructure.Dashboard;
|
||||
|
||||
namespace MeterVault.Integration.Tests.Specialized;
|
||||
|
||||
/// <summary>
|
||||
/// The pure arithmetic behind the Solar view's derived figures (brief §4.3, A05): an input without data makes the bucket
|
||||
/// unknown while an observed zero is a valid input; partial stays partial; a total never subtracts two totals over
|
||||
/// different stretches of time; units are never mixed (D-20); a change needs the same buckets on both sides (D-07).
|
||||
/// </summary>
|
||||
public sealed class SolarFiguresTests
|
||||
{
|
||||
private static BucketValue Ok(double value) => BucketValue.Available(value, Provenance.Imported);
|
||||
|
||||
private static BucketValue Part(double value) => new(value, BucketStatus.Partial, Provenance.Imported, ValueIssue.PartialCoverage);
|
||||
|
||||
private static readonly BucketValue None = BucketValue.Missing();
|
||||
|
||||
[Fact]
|
||||
public void An_observed_zero_is_an_input_and_a_missing_value_is_not()
|
||||
{
|
||||
var zero = SolarService.Combine(Ok(300), Ok(0), -1);
|
||||
Assert.Equal((300d, BucketStatus.Available), (zero.Value, zero.Status));
|
||||
Assert.True(zero.Provenance.HasFlag(Provenance.Derived));
|
||||
|
||||
var missing = SolarService.Combine(Ok(300), None, -1);
|
||||
Assert.Equal(((double?)null, BucketStatus.Missing, ValueIssue.MissingSource), (missing.Value, missing.Status, missing.Issue));
|
||||
|
||||
var neither = SolarService.Combine(None, None, -1);
|
||||
Assert.Equal((BucketStatus.Missing, ValueIssue.NoCoverage), (neither.Status, neither.Issue));
|
||||
|
||||
var partial = SolarService.Combine(Part(300), Ok(100), -1);
|
||||
Assert.Equal((200d, BucketStatus.Partial), (partial.Value, partial.Status));
|
||||
|
||||
// Being prepared or too coarse decides the status, even beside a missing input.
|
||||
var pending = SolarService.Combine(None, new BucketValue(null, BucketStatus.Pending, Provenance.None, ValueIssue.AnalysisPending), -1);
|
||||
Assert.Equal(BucketStatus.Pending, pending.Status);
|
||||
var coarse = SolarService.Combine(new BucketValue(null, BucketStatus.Unresolved, Provenance.Imported, ValueIssue.CoarseResolution), Ok(1), 1);
|
||||
Assert.Equal((BucketStatus.Unresolved, ValueIssue.CoarseResolution), (coarse.Status, coarse.Issue));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_total_is_taken_over_the_buckets_both_inputs_know_unless_both_are_complete()
|
||||
{
|
||||
// Load known February and March (700), import known January to March (800): the difference of the totals would
|
||||
// be −100; over the months both know it is 300, partial.
|
||||
List<BucketValue> load = [None, Ok(400), Ok(300)];
|
||||
List<BucketValue> import = [Ok(400), Ok(300), Ok(100)];
|
||||
var a = new SolarFigure(SolarBasis.Measured, "kWh", load, Part(700)) { InputUnits = ["kWh"] };
|
||||
var b = new SolarFigure(SolarBasis.Measured, "kWh", import, Ok(800)) { InputUnits = ["kWh"] };
|
||||
|
||||
var self = SolarService.Derive(SolarBasis.LoadMinusImport, a, b, -1);
|
||||
|
||||
Assert.Equal([null, 100d, 200d], self.Values.Select(v => v.Value));
|
||||
Assert.Equal((300d, BucketStatus.Partial), (self.Total.Value, self.Total.Status));
|
||||
|
||||
// Both complete: the totals decide (a monthly import resolves the period even where it does not resolve days).
|
||||
var whole = SolarService.CombineTotal(Ok(700), Ok(400), -1, [new BucketValue(null, BucketStatus.Unresolved, Provenance.None)]);
|
||||
Assert.Equal((300d, BucketStatus.Available), (whole.Value, whole.Status));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Figures_in_different_units_are_never_combined()
|
||||
{
|
||||
var generation = new SolarFigure(SolarBasis.Measured, "Wh", [Ok(5000)], Ok(5000)) { InputUnits = ["Wh"] };
|
||||
var export = new SolarFigure(SolarBasis.Measured, "kWh", [Ok(1)], Ok(1)) { InputUnits = ["kWh"] };
|
||||
|
||||
var self = SolarService.Derive(SolarBasis.GenerationMinusExport, generation, export, -1);
|
||||
|
||||
Assert.True(self.UnitsDiffer);
|
||||
Assert.Equal(["Wh", "kWh"], self.InputUnits);
|
||||
Assert.Equal(((double?)null, BucketStatus.Invalid), (self.Total.Value, self.Total.Status));
|
||||
Assert.Equal(BucketStatus.Invalid, SolarService.Share(self, generation).Status);
|
||||
Assert.Equal(BucketStatus.Invalid, SolarService.Share(export, generation).Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_share_needs_a_positive_base_and_says_when_it_is_partial()
|
||||
{
|
||||
var part = new SolarFigure(SolarBasis.Measured, "kWh", [Ok(30), None], Part(30)) { InputUnits = ["kWh"] };
|
||||
var whole = new SolarFigure(SolarBasis.Measured, "kWh", [Ok(60), Ok(40)], Ok(100)) { InputUnits = ["kWh"] };
|
||||
var share = SolarService.Share(part, whole);
|
||||
Assert.Equal((50d, BucketStatus.Partial), (share.Value, share.Status));
|
||||
|
||||
var zero = new SolarFigure(SolarBasis.Measured, "kWh", [Ok(0)], Ok(0)) { InputUnits = ["kWh"] };
|
||||
Assert.Equal(BucketStatus.Invalid, SolarService.Share(zero, zero).Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_change_compares_the_same_complete_buckets_on_both_sides()
|
||||
{
|
||||
// Complete totals: between them. Otherwise only the pairs complete on both sides (here the first).
|
||||
Assert.Equal(20, SolarService.MatchedChange(Ok(120), [Ok(120)], Ok(100), [Ok(100)]).Absolute);
|
||||
|
||||
var matched = SolarService.MatchedChange(Part(150), [Ok(120), Part(30)], Ok(200), [Ok(100), Ok(100)]);
|
||||
Assert.Equal((20d, 20d), (matched.Absolute, matched.Percent));
|
||||
|
||||
Assert.False(SolarService.MatchedChange(Part(30), [None, Part(30)], Ok(200), [Ok(100), Ok(100)]).IsAvailable);
|
||||
Assert.False(SolarService.MatchedChange(Ok(1), [Ok(1)], null, null).IsAvailable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
using MeterVault.Core.Analysis;
|
||||
using MeterVault.Core.Analysis.Costing;
|
||||
using MeterVault.Core.Analysis.Quantities;
|
||||
using MeterVault.Core.Domain;
|
||||
using MeterVault.Infrastructure.Analysis;
|
||||
using MeterVault.Infrastructure.Costing;
|
||||
using MeterVault.Infrastructure.Dashboard;
|
||||
using MeterVault.Infrastructure.Import;
|
||||
using MeterVault.Infrastructure.Options;
|
||||
using MeterVault.Infrastructure.Persistence;
|
||||
using MeterVault.Integration.Tests.Costing;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using static MeterVault.Integration.Tests.Costing.CostSandbox;
|
||||
using static MeterVault.Integration.Tests.Reconciliation.ReconciliationSupport;
|
||||
|
||||
namespace MeterVault.Integration.Tests.Specialized;
|
||||
|
||||
/// <summary>
|
||||
/// The Solar view's read model (brief §7.5, D-54) on the shared readers: generation from the type's generation measure
|
||||
/// (a virtual sum is listed, never added twice), self-consumption / feed-in / site use / autarky as far as the roles
|
||||
/// allow — unknown where an input has no data, never a zero — each role that nobody holds with its candidates, units from
|
||||
/// the meters (D-20), and savings and the feed-in credit from the cost engine (D-34 – D-38).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The view reads every energy type with generation, so every test starts from — and leaves — an instance without meters,
|
||||
/// tariffs or manual costs (like <see cref="DashboardServicesTests"/>); the sandbox tests pick their own type's section.
|
||||
/// </remarks>
|
||||
[Collection("Timescale")]
|
||||
public sealed class SolarServiceTests(TimescaleFixture fx) : IAsyncLifetime
|
||||
{
|
||||
private const int SolarErzeugung = 12;
|
||||
private const int NetzEinsparung = 13;
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
await ClearDataAsync(db);
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
await ClearDataAsync(db);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_seeded_solar_view_reproduces_the_sheet()
|
||||
{
|
||||
// Generation month by month is the sheet's Solar Erzeugung; self-consumption (Haus − Netz) its Netz Einsparung;
|
||||
// feed-in, without a grid export meter, generation − self-consumption — the sheet's 16,481 − 8,368 = 8,113 kWh.
|
||||
await LoadReferenceDataAsync();
|
||||
var rows = ReadRows(Electricity);
|
||||
|
||||
var solar = await Service().GetAsync(new SolarRequest(Custom(D(1997, 1, 1), D(2026, 12, 31))) { Bucket = BucketSize.Month });
|
||||
|
||||
var site = Assert.Single(solar.Sites);
|
||||
var months = site.Quantities.Plan.Buckets;
|
||||
Assert.Equal("kWh", site.Unit);
|
||||
Assert.Equal("kWh", site.Generation!.Unit);
|
||||
AssertReconciles(ByMonth(months, site.Generation.Values), OracleByMonth(rows, 0, SolarErzeugung, 1), 0.5, "generation", minMatches: 20);
|
||||
AssertReconciles(ByMonth(months, site.SelfConsumption!.Values), OracleByMonth(rows, 0, NetzEinsparung, 1), 0.5, "self-consumption", minMatches: 20);
|
||||
Assert.InRange(site.Generation.Total.Value!.Value, 16481 - 1, 16481 + 1);
|
||||
Assert.InRange(site.SelfConsumption.Total.Value!.Value, 8368 - 1, 8368 + 1);
|
||||
Assert.Equal(SolarBasis.LoadMinusImport, site.SelfConsumption.Basis);
|
||||
Assert.Equal(SolarBasis.GenerationMinusSelfConsumption, site.FeedIn!.Basis);
|
||||
Assert.InRange(site.FeedIn.Total.Value!.Value, 8113 - 2, 8113 + 2);
|
||||
Assert.Equal(SolarBasis.Measured, site.SiteUse!.Basis);
|
||||
Assert.InRange(site.SiteUse.Total.Value!.Value, 51909 - 1, 51909 + 1);
|
||||
|
||||
// Summe Solar (= Solar 1 + Solar 2) is listed as a calculated view and not added a second time.
|
||||
await using var db = fx.CreateContext();
|
||||
var byName = await db.Meters.ToDictionaryAsync(m => m.Name, m => m.Id);
|
||||
Assert.Equal(
|
||||
[("Zähler Solar 1", true), ("Zähler Solar 2", true), ("Summe Solar", false)],
|
||||
site.Meters.Select(m => (m.Name, m.IsCounted)));
|
||||
Assert.True(site.Meters.Single(m => m.Name == "Summe Solar").IsVirtual);
|
||||
Assert.Equal(site.Generation.Total.Value!.Value, site.Meters.Where(m => m.IsCounted).Sum(m => m.Total.Value!.Value), 6);
|
||||
|
||||
// Roles: the house and the grid meter hold theirs; nobody exports, and the car meter could.
|
||||
Assert.Equal([byName["Zähler Haus"]], site.RoleOf(MeterRole.TotalLoad).Holders.Select(h => h.MeterId));
|
||||
Assert.Equal([byName["Zähler Netz"]], site.RoleOf(MeterRole.GridImport).Holders.Select(h => h.MeterId));
|
||||
var export = site.RoleOf(MeterRole.GridExport);
|
||||
Assert.False(export.IsSet);
|
||||
Assert.Equal(["Zähler Auto"], export.Candidates.Select(c => c.Name));
|
||||
|
||||
// Savings: self-consumption at the grid meter's price, month by month — the priced history starts in September
|
||||
// 2022, before the first self-consumption — and no feed-in credit without an export meter.
|
||||
var savings = site.Savings!;
|
||||
Assert.Equal([byName["Zähler Netz"]], savings.MeterIds);
|
||||
Assert.Equal(CostStatus.Priced, savings.Total.Status);
|
||||
Assert.Equal(savings.Buckets.Sum(b => b.Cost ?? 0), savings.Total.Cost!.Value, 6);
|
||||
var january2025 = months.Select((b, i) => (b, i)).Single(p => p.b.FirstDay == D(2025, 1, 1)).i;
|
||||
Assert.Equal(site.SelfConsumption.Values[january2025].Value!.Value * 0.36, savings.Buckets[january2025].Cost!.Value, 6);
|
||||
Assert.Null(site.FeedInCredit);
|
||||
Assert.InRange(site.Autarky!.Value!.Value, (8368.0 / 51909 * 100) - 0.1, (8368.0 / 51909 * 100) + 0.1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Self_consumption_is_unknown_where_a_role_meter_has_no_data()
|
||||
{
|
||||
// A05: the house meter starts in February, so January has no self-consumption — not "0 − grid" and not "all of
|
||||
// the grid". Savings are priced from March, when the grid meter's price starts: February's are unknown, not free.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
await box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2026, 1, 1), 100, 200, 300);
|
||||
var grid = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridImport));
|
||||
await box.MonthlyReadingsAsync(grid, D(2026, 1, 1), 400, 300, 100);
|
||||
var house = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 2, 1), MeterMeta.WithRole("{}", MeterRoles.TotalLoad));
|
||||
await box.MonthlyReadingsAsync(house, D(2026, 2, 1), 400, 300);
|
||||
await box.TypePriceAsync(type, 0.30, D(2026, 3, 1));
|
||||
|
||||
var site = await SiteAsync(type, Custom(D(2026, 1, 1), D(2026, 3, 31)));
|
||||
|
||||
var self = site.SelfConsumption!;
|
||||
Assert.Equal(
|
||||
[(null, BucketStatus.Missing, ValueIssue.MissingSource), (100d, BucketStatus.Available, ValueIssue.None), (200d, BucketStatus.Available, ValueIssue.None)],
|
||||
self.Values.Select(v => (v.Value, v.Status, v.Issue)));
|
||||
Assert.Equal((300d, BucketStatus.Partial), (self.Total.Value!.Value, self.Total.Status));
|
||||
Assert.True(self.Values[1].Provenance.HasFlag(Provenance.Derived));
|
||||
|
||||
// Feed-in (generation − self-consumption) has the same gap; generation itself is complete.
|
||||
Assert.Equal([null, 100d, 100d], site.FeedIn!.Values.Select(v => v.Value));
|
||||
Assert.Equal((600d, BucketStatus.Available), (site.Generation!.Total.Value!.Value, site.Generation.Total.Status));
|
||||
|
||||
// Shares over the months both figures know: autarky 300 / 700, self-consumption share 300 / (200 + 300).
|
||||
Assert.Equal((300d / 700 * 100, BucketStatus.Partial), (site.Autarky!.Value!.Value, site.Autarky.Status));
|
||||
Assert.Equal((60d, BucketStatus.Partial), (Math.Round(site.SelfConsumptionShare!.Value!.Value, 6), site.SelfConsumptionShare.Status));
|
||||
|
||||
// Savings: January unknown (no self-consumption), February a price gap, March 200 × 0.30.
|
||||
var savings = site.Savings!;
|
||||
Assert.Equal([null, null, 60d], savings.Buckets.Select(b => b.Cost is { } c ? Math.Round(c, 6) : (double?)null));
|
||||
Assert.Equal(CostStatus.PriceGap, savings.Buckets[1].Status);
|
||||
Assert.Equal((60d, CostStatus.Partial), (Math.Round(savings.Total.Cost!.Value, 6), savings.Total.Status));
|
||||
Assert.Contains(site.CostAttention, a => a.Kind == CostAttentionKind.MissingPrice && a.Price!.Reason == CostStatus.PriceGap);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_missing_role_is_named_with_the_meters_that_could_take_it()
|
||||
{
|
||||
// Only a generation meter and two ordinary meters: every role is missing, the figures that need them are absent
|
||||
// (not zero), and each role lists the meters whose mode may hold it — never the generation, runtime or virtual one.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
var pv = await box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2026, 1, 1), 100, 120);
|
||||
await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", name: $"B {Guid.NewGuid():N}");
|
||||
await box.MeterAsync(type, MeterMode.DirectDelta, "kWh", name: $"A {Guid.NewGuid():N}");
|
||||
await box.MeterAsync(type, MeterMode.RuntimeCounter, "h");
|
||||
await box.VirtualAsync(type, $"m{pv}", QuantityKind.Generation, "kWh", MeterVault.Core.Analysis.Virtual.VirtualCostRule.None);
|
||||
|
||||
var site = await SiteAsync(type, Custom(D(2026, 1, 1), D(2026, 2, 28)));
|
||||
|
||||
Assert.Equal(220, site.Generation!.Total.Value!.Value, 6);
|
||||
Assert.Null(site.SelfConsumption);
|
||||
Assert.Null(site.FeedIn);
|
||||
Assert.Null(site.SiteUse);
|
||||
Assert.Null(site.Autarky);
|
||||
Assert.Null(site.Savings);
|
||||
Assert.Null(site.FeedInCredit);
|
||||
Assert.Equal(MeterRoleRules.All, site.Roles.Select(r => r.Role));
|
||||
Assert.All(site.Roles, role =>
|
||||
{
|
||||
Assert.False(role.IsSet);
|
||||
Assert.Equal(2, role.Candidates.Count);
|
||||
Assert.StartsWith("A ", role.Candidates[0].Name, StringComparison.Ordinal);
|
||||
Assert.StartsWith("B ", role.Candidates[1].Name, StringComparison.Ordinal);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_grid_export_meter_gives_measured_feed_in_and_its_credit()
|
||||
{
|
||||
// Generation 500 a month, export 200, import 100, no house meter: self-consumption is generation − export (300),
|
||||
// site use self-consumption + import (400), autarky 75 %. The credit is the bill's feed-in line: 200 × 0.08.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
await box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2026, 1, 1), 500, 500);
|
||||
var export = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridExport));
|
||||
await box.MonthlyReadingsAsync(export, D(2026, 1, 1), 200, 200);
|
||||
var import = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridImport));
|
||||
await box.MonthlyReadingsAsync(import, D(2026, 1, 1), 100, 100);
|
||||
await box.TypePriceAsync(type, 0.30, D(2025, 1, 1));
|
||||
await box.TariffAsync(TariffScope.EnergyType, type, TariffComponent.FeedIn, 0.08, "EUR/kWh", D(2025, 1, 1));
|
||||
|
||||
var site = await SiteAsync(type, Custom(D(2026, 1, 1), D(2026, 2, 28)));
|
||||
|
||||
Assert.Equal((SolarBasis.GenerationMinusExport, 600d), (site.SelfConsumption!.Basis, site.SelfConsumption.Total.Value!.Value));
|
||||
Assert.Equal((SolarBasis.Measured, 400d), (site.FeedIn!.Basis, site.FeedIn.Total.Value!.Value));
|
||||
Assert.Equal([export], site.FeedIn.MeterIds);
|
||||
Assert.Equal((SolarBasis.SelfConsumptionPlusImport, 800d), (site.SiteUse!.Basis, site.SiteUse.Total.Value!.Value));
|
||||
Assert.Equal(75, site.Autarky!.Value!.Value, 6);
|
||||
Assert.Equal(60, site.SelfConsumptionShare!.Value!.Value, 6);
|
||||
Assert.Equal(600 * 0.30, site.Savings!.Total.Cost!.Value, 6);
|
||||
Assert.Equal([import], site.Savings.MeterIds);
|
||||
Assert.Equal((32d, CostStatus.Priced), (Math.Round(site.FeedInCredit!.Total.FeedInCredit!.Value, 6), site.FeedInCredit.Total.Status));
|
||||
Assert.Equal([16d, 16d], site.FeedInCredit.Buckets.Select(b => Math.Round(b.FeedInCredit!.Value, 6)));
|
||||
Assert.True(site.RoleOf(MeterRole.GridExport).IsSet);
|
||||
Assert.False(site.RoleOf(MeterRole.TotalLoad).IsSet);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Units_come_from_the_meters_and_are_never_combined()
|
||||
{
|
||||
// D-20: a generation counter in Wh reads in Wh — nothing assumes kWh. A second one in kWh is its own measure, not
|
||||
// added; and an export meter in kWh cannot be subtracted from generation in Wh.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync("Wh");
|
||||
var small = await box.MeterAsync(type, MeterMode.GenerationCounter, "Wh", D(2026, 1, 1));
|
||||
await box.MonthlyReadingsAsync(small, D(2026, 1, 1), 5000, 7000);
|
||||
|
||||
var single = await SiteAsync(type, Custom(D(2026, 1, 1), D(2026, 2, 28)));
|
||||
Assert.Equal(("Wh", "Wh", 12000d), (single.Unit, single.Generation!.Unit, single.Generation.Total.Value!.Value));
|
||||
Assert.Empty(single.OtherGeneration);
|
||||
|
||||
var big = await box.MeterAsync(type, MeterMode.GenerationCounter, "kWh", D(2026, 1, 1));
|
||||
await box.MonthlyReadingsAsync(big, D(2026, 1, 1), 3, 4);
|
||||
var export = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 1, 1), MeterMeta.WithRole("{}", MeterRoles.GridExport));
|
||||
await box.MonthlyReadingsAsync(export, D(2026, 1, 1), 1, 1);
|
||||
|
||||
var mixed = await SiteAsync(type, Custom(D(2026, 1, 1), D(2026, 2, 28)));
|
||||
|
||||
// The export meter's unit picks the generation measure in kWh; the one in Wh is reported apart.
|
||||
Assert.Equal(("kWh", 7d), (mixed.Generation!.Unit, mixed.Generation.Total.Value!.Value));
|
||||
var other = Assert.Single(mixed.OtherGeneration);
|
||||
Assert.Equal(("Wh", 12000d), (other.Unit, other.Total.Value!.Value));
|
||||
Assert.Equal(5, mixed.SelfConsumption!.Total.Value!.Value, 6);
|
||||
|
||||
// An export in another unit than generation: self-consumption cannot be calculated, and says which units clash.
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
await db.Readings.Where(r => r.MeterId == big).ExecuteDeleteAsync();
|
||||
await db.Consumption.Where(c => c.MeterId == big).ExecuteDeleteAsync();
|
||||
await db.Meters.Where(m => m.Id == big).ExecuteDeleteAsync();
|
||||
}
|
||||
|
||||
var clash = await SiteAsync(type, Custom(D(2026, 1, 1), D(2026, 2, 28)));
|
||||
Assert.Equal("Wh", clash.Generation!.Unit);
|
||||
Assert.True(clash.SelfConsumption!.UnitsDiffer);
|
||||
Assert.Equal(["Wh", "kWh"], clash.SelfConsumption.InputUnits);
|
||||
Assert.All(clash.SelfConsumption.Values, v => Assert.Equal((null, BucketStatus.Invalid), (v.Value, v.Status)));
|
||||
Assert.Equal(BucketStatus.Invalid, clash.SelfConsumptionShare!.Status);
|
||||
Assert.Null(clash.Savings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Without_a_generation_meter_there_is_no_section()
|
||||
{
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2026, 1, 1), 100);
|
||||
|
||||
var solar = await Service().GetAsync(new SolarRequest(Custom(D(2026, 1, 1), D(2026, 1, 31))));
|
||||
|
||||
Assert.Empty(solar.Sites);
|
||||
Assert.Null(solar.Plan);
|
||||
Assert.Null(await Service().GetAvailabilityAsync(Now));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_period_without_data_is_missing_not_zero_and_the_availability_says_where_data_is()
|
||||
{
|
||||
// The seeded case of the brief: data until May 2026, today 19 September — month to date has nothing.
|
||||
await using var box = new CostSandbox(fx);
|
||||
var type = await box.TypeAsync();
|
||||
await box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2026, 3, 1), 100, 120, 130);
|
||||
var grid = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 3, 1), MeterMeta.WithRole("{}", MeterRoles.GridImport));
|
||||
await box.MonthlyReadingsAsync(grid, D(2026, 3, 1), 50, 50, 50);
|
||||
var house = await box.MeterAsync(type, MeterMode.CumulativeCounter, "kWh", D(2026, 3, 1), MeterMeta.WithRole("{}", MeterRoles.TotalLoad));
|
||||
await box.MonthlyReadingsAsync(house, D(2026, 3, 1), 90, 90, 90);
|
||||
|
||||
var site = await SiteAsync(type, Preset(PeriodPreset.MonthToDate));
|
||||
|
||||
Assert.Equal(BucketStatus.Missing, site.Generation!.Total.Status);
|
||||
Assert.Null(site.Generation.Total.Value);
|
||||
Assert.Equal(BucketStatus.Missing, site.SelfConsumption!.Total.Status);
|
||||
Assert.Null(site.SelfConsumption.Total.Value);
|
||||
Assert.Null(site.Autarky!.Value);
|
||||
Assert.Null(site.Savings?.Total.Cost);
|
||||
Assert.Equal(D(2026, 5, 31), site.Availability!.LastDay);
|
||||
Assert.Equal(D(2026, 5, 31), (await Service().GetAvailabilityAsync(Now))!.LastDay);
|
||||
}
|
||||
|
||||
private async Task<SolarSite> SiteAsync(short type, ResolvedPeriod period)
|
||||
{
|
||||
var solar = await Service().GetAsync(new SolarRequest(period) { Bucket = BucketSize.Month });
|
||||
return solar.Sites.Single(s => s.EnergyTypeId == type);
|
||||
}
|
||||
|
||||
private SolarService Service()
|
||||
{
|
||||
var options = Microsoft.Extensions.Options.Options.Create(new MeterVaultOptions { TimeZone = BerlinId, Currency = "EUR" });
|
||||
var reader = new AnalysisReader(fx, options);
|
||||
return new SolarService(fx, reader, new CostReader(fx, reader, options));
|
||||
}
|
||||
|
||||
private static Dictionary<DateOnly, double> ByMonth(IReadOnlyList<AnalysisBucket> buckets, IReadOnlyList<BucketValue> values) =>
|
||||
buckets.Select((b, i) => (b.FirstDay, values[i].Value))
|
||||
.Where(p => p.Value is not null)
|
||||
.ToDictionary(p => p.FirstDay, p => p.Value!.Value);
|
||||
|
||||
private async Task LoadReferenceDataAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
var importer = new ReferenceDataImporter(db, new ImportService(db, Normalization(db)), new CsvImporter());
|
||||
await importer.LoadAsync(Path.Combine(AppContext.BaseDirectory, "fixtures"));
|
||||
}
|
||||
|
||||
internal static async Task ClearDataAsync(MeterVaultDbContext db)
|
||||
{
|
||||
await db.MeterLinks.ExecuteDeleteAsync();
|
||||
await db.Consumption.ExecuteDeleteAsync();
|
||||
await db.Readings.ExecuteDeleteAsync();
|
||||
await db.MeterEvents.ExecuteDeleteAsync();
|
||||
await db.ManualCosts.ExecuteDeleteAsync();
|
||||
await db.CostCategoryMembers.ExecuteDeleteAsync();
|
||||
await db.Tariffs.ExecuteDeleteAsync();
|
||||
await db.Tanks.ExecuteDeleteAsync();
|
||||
await db.MeterSources.ExecuteDeleteAsync();
|
||||
await db.Meters.ExecuteDeleteAsync();
|
||||
await db.ImportBatches.ExecuteDeleteAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using MeterVault.Core.Domain;
|
||||
using MeterVault.Core.Normalization;
|
||||
using MeterVault.Infrastructure.Dashboard;
|
||||
|
||||
namespace MeterVault.Integration.Tests.Specialized;
|
||||
|
||||
/// <summary>
|
||||
/// The pure rules behind a tank's contents and forecast (D-54, D-09): contents at an instant are the last dipstick up to it
|
||||
/// plus the deliveries after it; the forecast is a straight line through the dipsticks of the year before the last one,
|
||||
/// hidden when that one is older than 60 days or the line too short.
|
||||
/// </summary>
|
||||
public sealed class TankLevelsTests
|
||||
{
|
||||
private static readonly TimeZoneInfo Berlin = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin");
|
||||
private static readonly DateTimeOffset Now = new(2026, 9, 19, 14, 37, 0, TimeSpan.FromHours(2));
|
||||
|
||||
[Fact]
|
||||
public void Contents_are_the_last_dipstick_plus_the_deliveries_after_it()
|
||||
{
|
||||
List<MeterEvent> events =
|
||||
[
|
||||
Level(At(2026, 8, 1), 2000),
|
||||
Delivery(At(2026, 8, 1), 500), // at the dipstick's instant: already in it, as the normalizer books it
|
||||
Delivery(At(2026, 8, 10), 1000),
|
||||
Delivery(At(2026, 9, 1), 300),
|
||||
];
|
||||
|
||||
var now = TankLevels.ContentsAt(events, Now, inclusive: true, calibration: null)!;
|
||||
Assert.Equal((3300d, 1300d, 2), (now.Volume, now.DeliveredSince, now.DeliveriesSince));
|
||||
|
||||
// An exclusive end leaves out what happens at that instant.
|
||||
var end = TankLevels.ContentsAt(events, At(2026, 9, 1), inclusive: false, calibration: null)!;
|
||||
Assert.Equal((3000d, 1), (end.Volume, end.DeliveriesSince));
|
||||
|
||||
Assert.Null(TankLevels.ContentsAt(events, At(2026, 7, 31), inclusive: true, calibration: null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_centimetre_dipstick_is_calibrated_and_keeps_what_was_read()
|
||||
{
|
||||
var level = new MeterEvent { MeterId = 1, EventType = MeterEventType.TankLevel, Time = At(2026, 9, 1), Amount = 85, Unit = "cm" };
|
||||
|
||||
var calibrated = TankLevels.Dipstick(level, new CalibrationCurve(46.67));
|
||||
Assert.Equal((85 * 46.67, 85d, "cm", true), (calibrated.Volume, calibrated.Reading, calibrated.ReadingUnit, calibrated.IsCalibrated));
|
||||
|
||||
// Without a calibration the reading is taken as the volume it is — and says it was not calibrated.
|
||||
var raw = TankLevels.Dipstick(level, calibration: null);
|
||||
Assert.Equal((85d, false), (raw.Volume, raw.IsCalibrated));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_forecast_says_why_it_is_missing()
|
||||
{
|
||||
Assert.Equal(TankForecastState.NoDipstick, TankLevels.Forecast([Delivery(At(2026, 9, 1), 1000)], Now, Berlin, null).State);
|
||||
|
||||
// One recent dipstick is no line.
|
||||
var single = TankLevels.Forecast([Level(At(2026, 9, 1), 2000)], Now, Berlin, null);
|
||||
Assert.Equal((TankForecastState.NotEnoughHistory, 18), (single.State, single.DipstickAgeDays));
|
||||
|
||||
// Two dipsticks 20 days apart are too short a line (at least 30 days).
|
||||
var short_ = TankLevels.Forecast([Level(At(2026, 8, 20), 2200), Level(At(2026, 9, 9), 2000)], Now, Berlin, null);
|
||||
Assert.Equal(TankForecastState.NotEnoughHistory, short_.State);
|
||||
|
||||
// Nothing drawn between the dipsticks (the delivery filled what was used): no end to project.
|
||||
var none = TankLevels.Forecast([Level(At(2026, 6, 1), 2000), Delivery(At(2026, 7, 1), 500), Level(At(2026, 9, 1), 2500)], Now, Berlin, null);
|
||||
Assert.Equal((TankForecastState.NoUse, 92), (none.State, none.BasisDays));
|
||||
|
||||
// A dipstick of 61 days is too old, whatever came before.
|
||||
var old = TankLevels.Forecast([Level(At(2026, 5, 1), 3000), Level(At(2026, 7, 20), 2000)], Now, Berlin, null);
|
||||
Assert.Equal((TankForecastState.DipstickTooOld, 61, (DateOnly?)null), (old.State, old.DipstickAgeDays, old.EmptyOn));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_forecast_draws_through_a_year_of_dipsticks_and_adds_the_deliveries_back()
|
||||
{
|
||||
// 1 October 2025: 5,000 L; 1 January 2026 a 2,000 L delivery; 1 September 2026: 1,500 L. Dipsticks older than a
|
||||
// year before the last one are ignored. Draw 5,000 + 2,000 − 1,500 = 5,500 L over 335 days; 1,500 L plus the
|
||||
// 200 L delivered on 10 September last 1,700 ÷ (5,500 ÷ 335) = 103.5 days from 1 September.
|
||||
List<MeterEvent> events =
|
||||
[
|
||||
Level(At(2024, 1, 1), 9000),
|
||||
Level(At(2025, 10, 1), 5000),
|
||||
Delivery(At(2026, 1, 1), 2000),
|
||||
Level(At(2026, 9, 1), 1500),
|
||||
Delivery(At(2026, 9, 10), 200),
|
||||
];
|
||||
|
||||
var forecast = TankLevels.Forecast(events, Now, Berlin, null);
|
||||
|
||||
Assert.Equal(TankForecastState.Projected, forecast.State);
|
||||
Assert.Equal(335, forecast.BasisDays);
|
||||
Assert.Equal(5500d / 335, forecast.PerDay!.Value, 6);
|
||||
Assert.Equal(new DateOnly(2026, 12, 13), forecast.EmptyOn);
|
||||
}
|
||||
|
||||
private static DateTimeOffset At(int year, int month, int day) =>
|
||||
GapAttribution.LocalMidnight(new DateOnly(year, month, day), Berlin);
|
||||
|
||||
private static MeterEvent Level(DateTimeOffset time, double litres) =>
|
||||
new() { MeterId = 1, EventType = MeterEventType.TankLevel, Time = time, Amount = litres, Unit = "L" };
|
||||
|
||||
private static MeterEvent Delivery(DateTimeOffset time, double litres) =>
|
||||
new() { MeterId = 1, EventType = MeterEventType.Delivery, Time = time, Amount = litres, Unit = "L" };
|
||||
}
|
||||
Reference in New Issue
Block a user