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,104 @@
|
||||
using System.Net;
|
||||
using MeterVault.App;
|
||||
using MeterVault.Core.Domain;
|
||||
using Microsoft.AspNetCore.Localization;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace MeterVault.Integration.Tests.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// The tariff and settings pages as the server prerenders them (D-37, D-52, D-57): a scoped tariff link lists what can
|
||||
/// price that meter and nothing else, Bonus/Discount/Tax say they are not applied, and settings label raw retention as
|
||||
/// not enforced, with the reason, beside the analysis data state.
|
||||
/// </summary>
|
||||
[Collection("Timescale")]
|
||||
public sealed class AdminPagesRenderTests(TimescaleFixture fx) : IAsyncLifetime
|
||||
{
|
||||
private short _type;
|
||||
private short _otherType;
|
||||
private int _meter;
|
||||
private readonly List<int> _tariffs = [];
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
var type = new EnergyType { Key = $"tariffs-{Guid.NewGuid():N}", DisplayName = "Tariff water", BaseUnit = "m3", DefaultMode = MeterMode.CumulativeCounter };
|
||||
var other = new EnergyType { Key = $"tariffs-{Guid.NewGuid():N}", DisplayName = "Tariff heat", BaseUnit = "kWh", DefaultMode = MeterMode.CumulativeCounter };
|
||||
db.EnergyTypes.AddRange(type, other);
|
||||
await db.SaveChangesAsync();
|
||||
_type = type.Id;
|
||||
_otherType = other.Id;
|
||||
|
||||
var meter = new Meter { Name = "Tap meter", EnergyTypeId = _type, Mode = MeterMode.CumulativeCounter, Unit = "m3", Meta = "{}" };
|
||||
db.Meters.Add(meter);
|
||||
await db.SaveChangesAsync();
|
||||
_meter = meter.Id;
|
||||
|
||||
Tariff[] tariffs =
|
||||
[
|
||||
Tariff(TariffScope.Meter, _meter, TariffComponent.UnitPrice, 1.2345, "EUR/m3"),
|
||||
Tariff(TariffScope.EnergyType, _type, TariffComponent.Bonus, 2.3456, "EUR"),
|
||||
Tariff(TariffScope.EnergyType, _otherType, TariffComponent.UnitPrice, 9.8765, "EUR/kWh"),
|
||||
];
|
||||
db.Tariffs.AddRange(tariffs);
|
||||
await db.SaveChangesAsync();
|
||||
_tariffs.AddRange(tariffs.Select(t => t.Id));
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
await db.Tariffs.Where(t => _tariffs.Contains(t.Id)).ExecuteDeleteAsync();
|
||||
await db.Meters.Where(m => m.Id == _meter).ExecuteDeleteAsync();
|
||||
await db.EnergyTypes.Where(t => t.Id == _type || t.Id == _otherType).ExecuteDeleteAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_scoped_tariff_link_lists_what_can_price_the_meter()
|
||||
{
|
||||
using var factory = new MeterVaultAppFactory(fx.ConnectionString);
|
||||
using var client = factory.CreateClient();
|
||||
|
||||
var scoped = WebUtility.HtmlDecode(await client.GetStringAsync(new Uri($"{TariffLinks.Path}?scope=meter&id={_meter}", UriKind.Relative)));
|
||||
Assert.Contains("Tariffs that can price Tap meter: its own, its energy type's and global ones.", scoped, StringComparison.Ordinal);
|
||||
Assert.Contains("1.2345", scoped, StringComparison.Ordinal); // its own price
|
||||
Assert.Contains("2.3456", scoped, StringComparison.Ordinal); // its type's bonus …
|
||||
Assert.Contains("Not applied yet", scoped, StringComparison.Ordinal); // … which is not applied yet
|
||||
Assert.DoesNotContain("9.8765", scoped, StringComparison.Ordinal); // another type's price is not listed
|
||||
Assert.Contains("Bonus, discount and tax tariffs are stored but not applied to costs yet.", scoped, StringComparison.Ordinal);
|
||||
|
||||
var all = WebUtility.HtmlDecode(await client.GetStringAsync(new Uri(TariffLinks.Path, UriKind.Relative)));
|
||||
Assert.Contains("9.8765", all, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Tariffs that can price", all, StringComparison.Ordinal);
|
||||
|
||||
// The deep link of a missing price renders; its dialog opens only once the page is interactive.
|
||||
var link = TariffLinks.New(TariffScope.Meter, _meter, TariffComponent.UnitPrice, new DateOnly(2027, 1, 1));
|
||||
(await client.GetAsync(new Uri(link, UriKind.Relative))).EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Settings_label_raw_retention_as_not_enforced_in_both_languages()
|
||||
{
|
||||
using var factory = new MeterVaultAppFactory(fx.ConnectionString);
|
||||
using var client = factory.CreateClient();
|
||||
|
||||
var english = WebUtility.HtmlDecode(await client.GetStringAsync(new Uri("/admin/settings", UriKind.Relative)));
|
||||
Assert.Contains("Not enforced", english, StringComparison.Ordinal);
|
||||
Assert.Contains("Raw readings are kept indefinitely (configured: 1095 days).", english, StringComparison.Ordinal);
|
||||
Assert.Contains("Analysis data", english, StringComparison.Ordinal);
|
||||
Assert.Contains("Meters with current analysis data", english, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("could not be read", english, StringComparison.Ordinal);
|
||||
|
||||
using var german = factory.CreateClient();
|
||||
german.DefaultRequestHeaders.Add(
|
||||
"Cookie",
|
||||
CookieRequestCultureProvider.DefaultCookieName + "="
|
||||
+ Uri.EscapeDataString(CookieRequestCultureProvider.MakeCookieValue(new RequestCulture("de"))));
|
||||
var deutsch = WebUtility.HtmlDecode(await german.GetStringAsync(new Uri("/admin/settings", UriKind.Relative)));
|
||||
Assert.Contains("Nicht aktiv", deutsch, StringComparison.Ordinal);
|
||||
Assert.Contains("Auswertungsdaten", deutsch, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static Tariff Tariff(TariffScope scope, int id, TariffComponent component, double value, string unit) =>
|
||||
new() { ScopeType = scope, ScopeId = id, Component = component, Value = value, Unit = unit, ValidFrom = new DateOnly(2020, 1, 1) };
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
using MeterVault.App.Analysis;
|
||||
using MeterVault.App.MeterEditing;
|
||||
using MeterVault.Core.Analysis;
|
||||
using MeterVault.Core.Analysis.Virtual;
|
||||
using MeterVault.Core.Domain;
|
||||
using MeterVault.Core.Normalization;
|
||||
using MeterVault.Infrastructure.Analysis;
|
||||
using MeterVault.Infrastructure.Normalization;
|
||||
using MeterVault.Infrastructure.Options;
|
||||
using MeterVault.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace MeterVault.Integration.Tests.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// The meter editor's live preview (D-31): an unsaved calculation evaluated through the shared reader over the stored
|
||||
/// sources, with nothing written. The brief's worked example (§5.4): A = 100/80 and B = 150/120 kWh give A+B = 250/200
|
||||
/// and A−B = −50/−40, and a source month that is missing makes the result's month incomplete rather than a number.
|
||||
/// </summary>
|
||||
[Collection("Timescale")]
|
||||
public sealed class MeterDraftPreviewTests(TimescaleFixture fx) : IAsyncLifetime
|
||||
{
|
||||
private const string BerlinId = "Europe/Berlin";
|
||||
|
||||
private static readonly TimeZoneInfo Berlin = TimeZoneInfo.FindSystemTimeZoneById(BerlinId);
|
||||
|
||||
/// <summary>The frozen "now" of every preview here (D-01).</summary>
|
||||
private static readonly DateTimeOffset Now = new DateTimeOffset(2026, 9, 19, 14, 37, 0, TimeSpan.FromHours(2)).ToUniversalTime();
|
||||
|
||||
private readonly List<int> _meters = [];
|
||||
private readonly List<short> _types = [];
|
||||
|
||||
public Task InitializeAsync() => Task.CompletedTask;
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
var ids = _meters.ToArray();
|
||||
await db.Consumption.Where(c => ids.Contains(c.MeterId)).ExecuteDeleteAsync();
|
||||
await db.Readings.Where(r => ids.Contains(r.MeterId)).ExecuteDeleteAsync();
|
||||
await db.MeterLinks.Where(l => ids.Contains(l.FromMeterId) || ids.Contains(l.ToMeterId)).ExecuteDeleteAsync();
|
||||
await db.Meters.Where(m => ids.Contains(m.Id)).ExecuteDeleteAsync();
|
||||
var types = _types.ToArray();
|
||||
await db.EnergyTypes.Where(t => types.Contains(t.Id)).ExecuteDeleteAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_unsaved_sum_previews_the_worked_example_without_storing_anything()
|
||||
{
|
||||
var type = await TypeAsync();
|
||||
var a = await GenerationAsync(type, 100, 80);
|
||||
var b = await GenerationAsync(type, 150, 120);
|
||||
var analysis = Analysis();
|
||||
var catalog = await analysis.LoadCatalogAsync();
|
||||
|
||||
// A new meter: Sum mode picks A and B; nothing is declared, so the kind and unit come from the sources (A-08).
|
||||
var draft = new MeterDraft(0, "A + B", type, MeterMode.Virtual, "kWh") { Definition = new VirtualDefinition($"m{a} + m{b}") };
|
||||
var validation = MeterDraftAnalysis.Validate(catalog, draft);
|
||||
Assert.True(validation.IsSavable);
|
||||
var effective = validation.EffectiveDefinition!;
|
||||
Assert.Equal(QuantityKind.Generation, effective.ResultKind);
|
||||
Assert.Equal(VirtualCostRule.None, effective.CostRule); // a generation sum is not costed by default (A-15)
|
||||
|
||||
var result = await analysis.PreviewAsync(MeterDraftAnalysis.Overlay(catalog, draft, effective), draft, JanFeb());
|
||||
|
||||
var series = result.SeriesFor(MeterDraft.NewMeterId)!;
|
||||
Assert.Equal(SeriesBasis.Virtual, series.Basis);
|
||||
Assert.Equal(QuantityKind.Generation, series.Kind);
|
||||
Assert.Equal("kWh", series.Unit);
|
||||
AssertValues(series.Values, 250, 200);
|
||||
AssertAvailable(series.Total, 450);
|
||||
Assert.True(series.IsAdditive);
|
||||
|
||||
// Each source's own values, as the preview table shows them beside the result.
|
||||
var sources = series.Contributions.ToDictionary(c => c.MeterId);
|
||||
AssertValues(sources[a].Values, 100, 80);
|
||||
AssertValues(sources[b].Values, 150, 120);
|
||||
|
||||
// Nothing was written: no meter, no link, no definition.
|
||||
await using var db = fx.CreateContext();
|
||||
Assert.False(await db.Meters.AnyAsync(m => m.EnergyTypeId == type && m.Mode == MeterMode.Virtual));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_unsaved_difference_stays_negative_and_an_edited_meter_previews_its_draft()
|
||||
{
|
||||
var type = await TypeAsync();
|
||||
var a = await GenerationAsync(type, 100, 80);
|
||||
var b = await GenerationAsync(type, 150, 120);
|
||||
var existing = await VirtualAsync(type, $"m{a} + m{b}");
|
||||
var analysis = Analysis();
|
||||
var catalog = await analysis.LoadCatalogAsync();
|
||||
|
||||
// Editing the stored sum into a difference: the preview shows the draft, not what is stored.
|
||||
var draft = new MeterDraft(existing, "A − B", type, MeterMode.Virtual, "kWh") { Definition = new VirtualDefinition($"m{a} - m{b}") };
|
||||
var effective = MeterDraftAnalysis.Validate(catalog, draft).EffectiveDefinition!;
|
||||
Assert.Equal(VirtualCostRule.None, effective.CostRule);
|
||||
|
||||
var result = await analysis.PreviewAsync(MeterDraftAnalysis.Overlay(catalog, draft, effective), draft, JanFeb());
|
||||
|
||||
var series = result.SeriesFor(existing)!;
|
||||
AssertValues(series.Values, -50, -40);
|
||||
AssertAvailable(series.Total, -90);
|
||||
Assert.Equal(-1d, series.Contributions.Single(c => c.MeterId == b).Coefficient);
|
||||
|
||||
// The stored definition is still the sum.
|
||||
var stored = await analysis.PreviewAsync(catalog, draft, JanFeb());
|
||||
AssertValues(stored.SeriesFor(existing)!.Values, 250, 200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_missing_source_month_makes_the_preview_month_incomplete_not_a_number()
|
||||
{
|
||||
var type = await TypeAsync();
|
||||
var a = await GenerationAsync(type, 100, 80);
|
||||
var b = await GenerationAsync(type, 150); // B has January only
|
||||
var analysis = Analysis();
|
||||
var catalog = await analysis.LoadCatalogAsync();
|
||||
var draft = new MeterDraft(0, "A + B", type, MeterMode.Virtual, "kWh") { Definition = new VirtualDefinition($"m{a} + m{b}") };
|
||||
var effective = MeterDraftAnalysis.Validate(catalog, draft).EffectiveDefinition!;
|
||||
|
||||
var series = (await analysis.PreviewAsync(MeterDraftAnalysis.Overlay(catalog, draft, effective), draft, JanFeb()))
|
||||
.SeriesFor(MeterDraft.NewMeterId)!;
|
||||
|
||||
AssertAvailable(series.Values[0], 250);
|
||||
Assert.NotEqual(BucketStatus.Available, series.Values[1].Status);
|
||||
Assert.NotEqual(80, series.Values[1].Value);
|
||||
Assert.NotEqual(BucketStatus.Available, series.Total.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_draft_that_reads_a_calculation_reading_it_is_a_named_loop()
|
||||
{
|
||||
var type = await TypeAsync();
|
||||
var a = await GenerationAsync(type, 100, 80);
|
||||
var first = await VirtualAsync(type, $"m{a}");
|
||||
var second = await VirtualAsync(type, $"m{first}");
|
||||
var catalog = await Analysis().LoadCatalogAsync();
|
||||
|
||||
var draft = new MeterDraft(first, "First", type, MeterMode.Virtual, "kWh") { Definition = new VirtualDefinition($"m{second} + m{a}") };
|
||||
var validation = MeterDraftAnalysis.Validate(catalog, draft);
|
||||
|
||||
Assert.False(validation.IsValid);
|
||||
var cycle = Assert.Single(validation.Problems, p => p.Kind == VirtualProblemKind.DependencyCycle);
|
||||
Assert.Equal([first, second, first], cycle.MeterIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_preview_opens_on_the_page_period_and_reaches_history_older_than_24_months()
|
||||
{
|
||||
// Brief §5.1 / D-31: "a preview for the selected historical period" — the page's period carries into the editor,
|
||||
// and all available history spans the sources' data however old it is (here 2022, beyond every relative preset).
|
||||
var type = await TypeAsync();
|
||||
var a = await GenerationAsync(type, new DateOnly(2022, 1, 1), 100, 80);
|
||||
var b = await GenerationAsync(type, new DateOnly(2022, 1, 1), 150, 120);
|
||||
var analysis = Analysis();
|
||||
var catalog = await analysis.LoadCatalogAsync();
|
||||
var draft = new MeterDraft(0, "A + B", type, MeterMode.Virtual, "kWh") { Definition = new VirtualDefinition($"m{a} + m{b}") };
|
||||
var effective = MeterDraftAnalysis.Validate(catalog, draft).EffectiveDefinition!;
|
||||
draft = draft with { Definition = effective };
|
||||
var overlay = MeterDraftAnalysis.Overlay(catalog, draft, effective);
|
||||
|
||||
// Without a page period the preview opens on the last 12 months — where these sources have nothing.
|
||||
Assert.Equal(PeriodPreset.Last12Months, VirtualPreviewPeriod.Initial(null).Period);
|
||||
|
||||
// Opened from /meters/..?from=2022-01-01&to=2022-02-28 it shows exactly that range.
|
||||
var page = AnalysisQuery.Parse("?from=2022-01-01&to=2022-02-28&bucket=day&compare=none", AnalysisDefaults.History);
|
||||
var initial = VirtualPreviewPeriod.Initial(page);
|
||||
Assert.True(initial.IsCustom);
|
||||
var period = await VirtualPreviewPeriod.ResolveAsync(analysis, overlay, draft, initial, Now);
|
||||
Assert.Equal(new DateOnly(2022, 1, 1), period.FirstDay);
|
||||
var result = await analysis.PreviewAsync(overlay, draft, period);
|
||||
AssertValues(result.SeriesFor(MeterDraft.NewMeterId)!.Values, 250, 200);
|
||||
|
||||
// All available history: the sources' own dates, and their values.
|
||||
var all = await VirtualPreviewPeriod.ResolveAsync(analysis, overlay, draft, initial.WithPeriod(PeriodPreset.AllHistory), Now);
|
||||
Assert.Equal(new DateOnly(2022, 1, 1), all.FirstDay);
|
||||
var whole = await analysis.PreviewAsync(overlay, draft, all);
|
||||
AssertAvailable(whole.SeriesFor(MeterDraft.NewMeterId)!.Total, 450);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ helpers
|
||||
|
||||
private MeterDraftAnalysis Analysis()
|
||||
{
|
||||
var options = Microsoft.Extensions.Options.Options.Create(new MeterVaultOptions { TimeZone = BerlinId });
|
||||
return new MeterDraftAnalysis(new AnalysisReader(fx, options), fx);
|
||||
}
|
||||
|
||||
private static ResolvedPeriod JanFeb() =>
|
||||
PeriodResolver.Resolve(PeriodPreset.Custom, new DateOnly(2026, 1, 1), new DateOnly(2026, 2, 28), Now, Berlin);
|
||||
|
||||
private static void AssertAvailable(BucketValue value, double expected)
|
||||
{
|
||||
Assert.Equal(BucketStatus.Available, value.Status);
|
||||
Assert.Equal(expected, value.Value!.Value, 9);
|
||||
}
|
||||
|
||||
private static void AssertValues(IReadOnlyList<BucketValue> values, params double[] expected)
|
||||
{
|
||||
Assert.Equal(expected.Length, values.Count);
|
||||
for (var i = 0; i < expected.Length; i++)
|
||||
{
|
||||
AssertAvailable(values[i], expected[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<short> TypeAsync()
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
var type = new EnergyType
|
||||
{
|
||||
Key = $"editor-{Guid.NewGuid():N}",
|
||||
DisplayName = "Editor test",
|
||||
BaseUnit = "kWh",
|
||||
DefaultMode = MeterMode.GenerationCounter,
|
||||
};
|
||||
db.EnergyTypes.Add(type);
|
||||
await db.SaveChangesAsync();
|
||||
_types.Add(type.Id);
|
||||
return type.Id;
|
||||
}
|
||||
|
||||
private async Task<int> MeterAsync(short type, MeterMode mode, string meta = "{}", DateOnly? installedAt = null)
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
var meter = new Meter
|
||||
{
|
||||
Name = $"editor-{Guid.NewGuid():N}",
|
||||
EnergyTypeId = type,
|
||||
Mode = mode,
|
||||
Unit = "kWh",
|
||||
InstalledAt = installedAt,
|
||||
Meta = meta,
|
||||
};
|
||||
db.Meters.Add(meter);
|
||||
await db.SaveChangesAsync();
|
||||
_meters.Add(meter.Id);
|
||||
return meter.Id;
|
||||
}
|
||||
|
||||
/// <summary>A generation counter installed on 1 January 2026 whose months book the given amounts (read on the 1st after each).</summary>
|
||||
private Task<int> GenerationAsync(short type, params double[] months) => GenerationAsync(type, new DateOnly(2026, 1, 1), months);
|
||||
|
||||
/// <summary>A generation counter installed on <paramref name="first"/> (a 1st) whose months book the given amounts.</summary>
|
||||
private async Task<int> GenerationAsync(short type, DateOnly first, params double[] months)
|
||||
{
|
||||
var meter = await MeterAsync(type, MeterMode.GenerationCounter, installedAt: first);
|
||||
var register = 0d;
|
||||
await using (var db = fx.CreateContext())
|
||||
{
|
||||
for (var i = 0; i < months.Length; i++)
|
||||
{
|
||||
register += months[i];
|
||||
db.Readings.Add(new Reading
|
||||
{
|
||||
MeterId = meter,
|
||||
Time = GapAttribution.LocalMidnight(first.AddMonths(i + 1), Berlin).ToUniversalTime(),
|
||||
Value = register,
|
||||
Quality = ReadingQuality.Manual,
|
||||
});
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
await RecomputeAsync(meter);
|
||||
return meter;
|
||||
}
|
||||
|
||||
private async Task<int> VirtualAsync(short type, string expression)
|
||||
{
|
||||
var meta = VirtualDefinitionJson.Write("{}", new VirtualDefinition(expression, QuantityKind.Generation, "kWh", VirtualCostRule.None));
|
||||
var meter = await MeterAsync(type, MeterMode.Virtual, meta);
|
||||
await RecomputeAsync(meter);
|
||||
return meter;
|
||||
}
|
||||
|
||||
private async Task RecomputeAsync(int meterId)
|
||||
{
|
||||
await using var db = fx.CreateContext();
|
||||
await using var tx = await db.Database.BeginTransactionAsync();
|
||||
var normalization = new NormalizationService(
|
||||
db,
|
||||
NormalizationEngine.CreateDefault(),
|
||||
Microsoft.Extensions.Options.Options.Create(new MeterVaultOptions { TimeZone = BerlinId }),
|
||||
new FixedTimeProvider(Now));
|
||||
await normalization.RecomputeMeterAsync(meterId, null);
|
||||
await db.SaveChangesAsync();
|
||||
await tx.CommitAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
using MeterVault.App.MeterEditing;
|
||||
using MeterVault.Core.Analysis;
|
||||
using MeterVault.Core.Analysis.Totals;
|
||||
using MeterVault.Core.Analysis.Virtual;
|
||||
using MeterVault.Core.Domain;
|
||||
using MeterVault.Infrastructure.Analysis;
|
||||
using MeterVault.Integration.Tests.Analysis;
|
||||
|
||||
namespace MeterVault.Integration.Tests.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// The meter editor's rules without a browser or a database (brief §5.1, D-23, D-26, D-28, D-31, D-39, A-08, A-15): how
|
||||
/// a calculation is written in Sum, Difference and Formula mode, which sources and cost rules are offered, when a save is
|
||||
/// blocked, what a legacy meter proposes, and the words for a loop, a unit mismatch and a refused totals override. The
|
||||
/// catalog is built from entities (<see cref="AnalysisCatalog.Build"/>), exactly as a request builds it.
|
||||
/// </summary>
|
||||
public sealed class MeterEditorLogicTests
|
||||
{
|
||||
private const int SolarA = 1;
|
||||
private const int SolarB = 2;
|
||||
private const int House = 3;
|
||||
private const int Water = 4;
|
||||
private const int SolarSum = 5;
|
||||
private const int HalfHouse = 6;
|
||||
private const int Draft = 7;
|
||||
private const int ReadsDraft = 8;
|
||||
private const int Garage = 9;
|
||||
private const int Car = 10;
|
||||
private const int Legacy = 11;
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ writing a calculation
|
||||
|
||||
[Theory]
|
||||
[InlineData("m1 + m2", CalculationMode.Sum, new[] { 1, 2 })]
|
||||
[InlineData("m2 + m1", CalculationMode.Sum, new[] { 2, 1 })]
|
||||
[InlineData("(m1) + m2", CalculationMode.Sum, new[] { 1, 2 })]
|
||||
[InlineData("m3 - m1 - m2", CalculationMode.Difference, new[] { 3, 1, 2 })]
|
||||
[InlineData("m3 - (m1 - m2)", CalculationMode.Advanced, new[] { 3, 1, 2 })]
|
||||
[InlineData("(m1 - m2) * 0.5", CalculationMode.Advanced, new[] { 1, 2 })]
|
||||
[InlineData("m1 + m1", CalculationMode.Advanced, new[] { 1, 1 })]
|
||||
[InlineData("m1 + 5", CalculationMode.Advanced, new[] { 1 })]
|
||||
public void A_stored_formula_reopens_in_the_mode_its_shape_allows(string expression, CalculationMode mode, int[] meters)
|
||||
{
|
||||
var draft = CalculationDraft.From(new VirtualDefinition(expression, QuantityKind.Consumption, "kWh", VirtualCostRule.None));
|
||||
|
||||
Assert.Equal(mode, draft.Mode);
|
||||
switch (mode)
|
||||
{
|
||||
case CalculationMode.Sum:
|
||||
Assert.Equal(meters, draft.SumSources);
|
||||
break;
|
||||
case CalculationMode.Difference:
|
||||
Assert.Equal(meters[0], draft.Minuend);
|
||||
Assert.Equal(meters[1..], draft.Subtrahends);
|
||||
break;
|
||||
default:
|
||||
Assert.Equal(expression, draft.Text);
|
||||
break;
|
||||
}
|
||||
|
||||
// Whatever the mode, the text it writes is the same calculation.
|
||||
Assert.Equal(Formula.Parse(expression), Formula.Parse(draft.Text));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Switching_modes_carries_the_meters_and_the_formula_text()
|
||||
{
|
||||
var draft = new CalculationDraft();
|
||||
Assert.True(draft.IsIncomplete);
|
||||
Assert.Equal(string.Empty, draft.Text);
|
||||
|
||||
draft.SetSumSources([SolarA, SolarB]);
|
||||
Assert.Equal("m1 + m2", draft.Text);
|
||||
draft.SetSumSources([SolarB, SolarA, House]); // picking a meter never reorders the ones already there
|
||||
Assert.Equal("m1 + m2 + m3", draft.Text);
|
||||
|
||||
draft.SwitchTo(CalculationMode.Difference);
|
||||
Assert.Equal("m1 - m2 - m3", draft.Text);
|
||||
draft.SetMinuend(SolarB); // the start is never also subtracted
|
||||
Assert.Equal("m2 - m3", draft.Text);
|
||||
draft.SetSubtrahends([SolarB]);
|
||||
Assert.True(draft.IsIncomplete); // nothing left to subtract
|
||||
draft.SetSubtrahends([House, SolarA]);
|
||||
|
||||
draft.SwitchTo(CalculationMode.Advanced);
|
||||
Assert.Equal("m2 - m3 - m1", draft.Expression);
|
||||
draft.Expression = "m1 / m3";
|
||||
draft.InsertReference(SolarB);
|
||||
Assert.Equal("m1 / m3 + m2", draft.Expression);
|
||||
draft.Expression = "m1 * (";
|
||||
draft.InsertReference(House);
|
||||
Assert.Equal("m1 * ( m3", draft.Expression);
|
||||
|
||||
// Back from a formula of another shape: the pickers start from the meters it names.
|
||||
draft.Expression = "(m3 - m1) / m2";
|
||||
draft.SwitchTo(CalculationMode.Sum);
|
||||
Assert.Equal([House, SolarA, SolarB], draft.SumSources);
|
||||
Assert.Equal(CalculationMode.Sum, draft.Mode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_definition_leaves_undeclared_parts_to_inference()
|
||||
{
|
||||
var draft = new CalculationDraft { ResultUnit = " " };
|
||||
draft.SetSumSources([SolarA, SolarB]);
|
||||
|
||||
var definition = draft.Definition;
|
||||
|
||||
Assert.Equal("m1 + m2", definition.Expression);
|
||||
Assert.Null(definition.ResultKind);
|
||||
Assert.Null(definition.ResultUnit);
|
||||
Assert.Null(definition.CostRule);
|
||||
Assert.Equal([SolarA, SolarB], definition.ReferencedMeterIds);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ sources and cost rules
|
||||
|
||||
[Fact]
|
||||
public void Sum_and_difference_pickers_offer_only_compatible_sources()
|
||||
{
|
||||
var catalog = Catalog();
|
||||
var options = CalculationSources.For(catalog, MeterDraft.NewMeterId, energyTypeId: 1);
|
||||
|
||||
// Nothing picked: every meter that can be added up; the draft's own type first.
|
||||
var open = CalculationSources.ForSum(options, []).Select(o => o.MeterId).ToList();
|
||||
Assert.Contains(SolarA, open);
|
||||
Assert.Contains(Water, open);
|
||||
Assert.True(open.IndexOf(Water) > open.IndexOf(House), "meters of the draft's own energy type come first");
|
||||
|
||||
// Once a generation meter in kWh is picked, only generation in kWh fits a sum.
|
||||
var afterSolar = CalculationSources.ForSum(options, [SolarA]).Select(o => o.MeterId).ToHashSet();
|
||||
Assert.Equal(new HashSet<int> { SolarA, SolarB, SolarSum, Draft, ReadsDraft, Legacy }, afterSolar);
|
||||
|
||||
// A difference subtracts meters of its start's unit, of any additive kind (import minus export is a net balance).
|
||||
var fromHouse = CalculationSources.ForSubtrahends(options, House, []).Select(o => o.MeterId).ToHashSet();
|
||||
Assert.Contains(SolarA, fromHouse);
|
||||
Assert.Contains(Garage, fromHouse);
|
||||
Assert.DoesNotContain(House, fromHouse);
|
||||
Assert.DoesNotContain(Water, fromHouse);
|
||||
Assert.True(CalculationSources.MixesKinds(options, [House, SolarA]));
|
||||
|
||||
// Editing a meter never offers itself, nor a calculation that already reads it (that would close a loop).
|
||||
var forDraft = CalculationSources.For(catalog, Draft, energyTypeId: 1).Select(o => o.MeterId).ToHashSet();
|
||||
Assert.DoesNotContain(Draft, forDraft);
|
||||
Assert.DoesNotContain(ReadsDraft, forDraft);
|
||||
Assert.Contains(SolarSum, forDraft);
|
||||
|
||||
// Each option says what it measures, in its normalized unit.
|
||||
var water = options.Single(o => o.MeterId == Water);
|
||||
Assert.Equal("m³", water.Unit);
|
||||
Assert.Equal(QuantityKind.Consumption, water.Kind);
|
||||
Assert.Equal(new DateOnly(2021, 3, 1), options.Single(o => o.MeterId == SolarA).InstalledAt);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("m3 + m9", null, new[] { VirtualCostRule.None, VirtualCostRule.SourceCosts, VirtualCostRule.OwnQuantity })]
|
||||
[InlineData("m1 + m2", null, new[] { VirtualCostRule.None, VirtualCostRule.OwnQuantity })]
|
||||
[InlineData("m3 - m9", null, new[] { VirtualCostRule.None, VirtualCostRule.OwnQuantity })]
|
||||
[InlineData("0.5 * m3", null, new[] { VirtualCostRule.None, VirtualCostRule.OwnQuantity })]
|
||||
[InlineData("m3 + 5", null, new[] { VirtualCostRule.None })]
|
||||
[InlineData("m3 / m9", QuantityKind.Indicator, new[] { VirtualCostRule.None })]
|
||||
[InlineData("m6 + m9", null, new[] { VirtualCostRule.None, VirtualCostRule.OwnQuantity })]
|
||||
public void Cost_rules_are_offered_only_where_the_calculation_supports_them(string expression, QuantityKind? kind, VirtualCostRule[] offered)
|
||||
{
|
||||
var catalog = Catalog();
|
||||
var validation = VirtualValidator.Validate(new VirtualDefinition(expression, kind, kind == QuantityKind.Indicator ? "%" : null), MeterDraft.NewMeterId, catalog.Catalog);
|
||||
|
||||
Assert.Equal(offered, CalculationSources.OfferedCostRules(validation.Formula, validation.Kind, MeterDraft.NewMeterId, catalog.Catalog));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_rule_that_is_not_offered_says_why()
|
||||
{
|
||||
var catalog = Catalog().Catalog;
|
||||
CostRuleUnavailable? Why(VirtualCostRule rule, string expression, QuantityKind? kind = null)
|
||||
{
|
||||
var v = VirtualValidator.Validate(new VirtualDefinition(expression, kind, kind == QuantityKind.Indicator ? "%" : null), MeterDraft.NewMeterId, catalog);
|
||||
return CalculationSources.WhyNot(rule, v.Formula, v.Kind, MeterDraft.NewMeterId, catalog);
|
||||
}
|
||||
|
||||
Assert.Null(Why(VirtualCostRule.SourceCosts, "m3 + m9"));
|
||||
Assert.Equal(CostRuleBlock.Generation, Why(VirtualCostRule.SourceCosts, "m1 + m2")!.Reason);
|
||||
Assert.Equal(CostRuleBlock.NotPureSum, Why(VirtualCostRule.SourceCosts, "m3 - m9")!.Reason);
|
||||
Assert.Equal(new CostRuleUnavailable(CostRuleBlock.NestedNotPureSum, HalfHouse), Why(VirtualCostRule.SourceCosts, "m6 + m9"));
|
||||
Assert.Equal(CostRuleBlock.NotLinear, Why(VirtualCostRule.OwnQuantity, "m3 + 5")!.Reason);
|
||||
Assert.Equal(CostRuleBlock.Indicator, Why(VirtualCostRule.OwnQuantity, "m3 / m9", QuantityKind.Indicator)!.Reason);
|
||||
Assert.Null(Why(VirtualCostRule.None, "m3 / m9", QuantityKind.Indicator));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ the calculation section
|
||||
|
||||
[Fact]
|
||||
public void A_new_calculation_is_saved_only_once_it_is_complete_and_valid()
|
||||
{
|
||||
var model = new VirtualCalculationModel(Catalog(), MeterDraft.NewMeterId, energyTypeId: 1);
|
||||
Assert.False(model.CanSave);
|
||||
Assert.Null(model.EffectiveDefinition);
|
||||
Assert.Empty(model.Problems); // incomplete asks for input, it does not report errors
|
||||
|
||||
model.Draft.SetSumSources([SolarA, SolarB]);
|
||||
model.Refresh();
|
||||
|
||||
// A-08: what a save writes is the effective definition — the inferred kind, the canonical unit, the default rule.
|
||||
Assert.True(model.CanSave);
|
||||
Assert.Equal(QuantityKind.Generation, model.InferredKind);
|
||||
Assert.Equal("kWh", model.InferredUnit);
|
||||
Assert.Equal(VirtualCostRule.None, model.DefaultCostRule); // a generation sum is not costed (A-15)
|
||||
Assert.Equal(new VirtualDefinition("m1 + m2", QuantityKind.Generation, "kWh", VirtualCostRule.None), model.EffectiveDefinition);
|
||||
|
||||
// A new sum links its sources in the flow view unless told not to (links never change the calculation).
|
||||
Assert.True(model.OffersLinkSync);
|
||||
Assert.True(model.SyncLinks);
|
||||
Assert.Equal([SolarA, SolarB], model.LinksAfterSave);
|
||||
model.SyncLinks = false;
|
||||
Assert.Empty(model.LinksAfterSave);
|
||||
|
||||
// A unit mismatch blocks the save and says so.
|
||||
model.Draft.SwitchTo(CalculationMode.Advanced);
|
||||
model.Draft.Expression = "m1 + m4";
|
||||
model.Refresh();
|
||||
Assert.False(model.CanSave);
|
||||
Assert.Contains(model.Problems, p => p.Kind == VirtualProblemKind.UnitMismatch);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_cost_rule_the_formula_stops_supporting_falls_back_to_the_default()
|
||||
{
|
||||
var model = new VirtualCalculationModel(Catalog(), MeterDraft.NewMeterId, energyTypeId: 1);
|
||||
model.Draft.SetSumSources([House, Garage]);
|
||||
model.Refresh();
|
||||
Assert.Equal(VirtualCostRule.SourceCosts, model.DefaultCostRule);
|
||||
model.Draft.CostRule = VirtualCostRule.OwnQuantity;
|
||||
model.Refresh();
|
||||
Assert.False(model.CostRuleReset);
|
||||
Assert.Equal(VirtualCostRule.OwnQuantity, model.EffectiveDefinition!.CostRule);
|
||||
|
||||
// m3 + 5 is not linear: the chosen rule is dropped rather than left as an error the user did not make.
|
||||
model.Draft.SwitchTo(CalculationMode.Advanced);
|
||||
model.Draft.Expression = "m3 + 5";
|
||||
model.Refresh();
|
||||
Assert.True(model.CostRuleReset);
|
||||
Assert.Null(model.Draft.CostRule);
|
||||
Assert.Equal([VirtualCostRule.None], model.OfferedCostRules);
|
||||
Assert.Equal(VirtualCostRule.None, model.EffectiveDefinition!.CostRule);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_source_cost_rule_over_a_nested_calculation_that_is_not_a_sum_blocks_the_save()
|
||||
{
|
||||
// The formula is a plain sum at its own level, but its source Half house is 0.5 × House (A-15): the validator's
|
||||
// CostRuleProblem must stop a save that stores sourceCosts, even though the definition itself is valid.
|
||||
var catalog = Catalog();
|
||||
var validation = MeterDraftAnalysis.Validate(catalog, NewVirtual() with
|
||||
{
|
||||
Definition = new VirtualDefinition("m6 + m9", null, null, VirtualCostRule.SourceCosts),
|
||||
});
|
||||
|
||||
Assert.True(validation.IsValid);
|
||||
Assert.False(validation.IsSavable);
|
||||
Assert.Equal(VirtualProblemKind.CostRuleNeedsPureSum, validation.CostRuleProblem!.Kind);
|
||||
var text = AnalysisUiTestData.In("en", () => MeterEditorText.Problem(validation.CostRuleProblem, Name(catalog)));
|
||||
Assert.Equal("“Sum of the sources' costs” needs plain sums throughout, but Half house is not a plain sum.", text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_stored_calculation_reopens_with_what_its_sources_imply_as_automatic()
|
||||
{
|
||||
// Solar sum is stored with everything declared (A-08); what merely repeats the sources shows as automatic, so a
|
||||
// change of sources carries the kind along instead of contradicting it.
|
||||
var model = new VirtualCalculationModel(Catalog(), SolarSum, energyTypeId: 1);
|
||||
|
||||
Assert.Equal(VirtualMeterStatus.Valid, model.Status);
|
||||
Assert.Equal(CalculationMode.Sum, model.Draft.Mode);
|
||||
Assert.Equal([SolarA, SolarB], model.Draft.SumSources);
|
||||
Assert.Null(model.Draft.ResultKind);
|
||||
Assert.Null(model.Draft.ResultUnit);
|
||||
Assert.Null(model.Draft.CostRule);
|
||||
Assert.True(model.CanSave);
|
||||
Assert.False(model.OffersLinkSync); // its links already are its sources
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_legacy_meter_opens_with_its_implied_sum_as_a_proposal_to_confirm()
|
||||
{
|
||||
var model = new VirtualCalculationModel(Catalog(), Legacy, energyTypeId: 1);
|
||||
|
||||
Assert.True(model.IsLegacyProposal);
|
||||
Assert.Equal(CalculationMode.Sum, model.Draft.Mode);
|
||||
Assert.Equal([SolarA, SolarB], model.Draft.SumSources.Order());
|
||||
Assert.True(model.CanSave);
|
||||
Assert.Equal(QuantityKind.Generation, model.EffectiveDefinition!.ResultKind);
|
||||
Assert.False(model.OffersLinkSync);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ findings in words
|
||||
|
||||
[Fact]
|
||||
public void A_loop_is_named_by_its_path_in_both_languages()
|
||||
{
|
||||
var catalog = Catalog();
|
||||
var validation = MeterDraftAnalysis.Validate(catalog, new MeterDraft(Draft, "Draft", 1, MeterMode.Virtual, "kWh")
|
||||
{
|
||||
Definition = new VirtualDefinition($"m{ReadsDraft}"),
|
||||
});
|
||||
|
||||
var cycle = Assert.Single(validation.Problems, p => p.Kind == VirtualProblemKind.DependencyCycle);
|
||||
Assert.Equal([Draft, ReadsDraft, Draft], cycle.MeterIds);
|
||||
Assert.Equal(
|
||||
"The calculation goes round in a circle: Draft → Reads draft → Draft.",
|
||||
AnalysisUiTestData.In("en", () => MeterEditorText.Problem(cycle, Name(catalog))));
|
||||
Assert.Equal(
|
||||
"Die Berechnung dreht sich im Kreis: Draft → Reads draft → Draft.",
|
||||
AnalysisUiTestData.In("de", () => MeterEditorText.Problem(cycle, Name(catalog))));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_unit_mismatch_names_both_meters_and_their_units()
|
||||
{
|
||||
var catalog = Catalog();
|
||||
var validation = MeterDraftAnalysis.Validate(catalog, NewVirtual() with { Definition = new VirtualDefinition("m1 + m4") });
|
||||
|
||||
var mismatch = Assert.Single(validation.Problems, p => p.Kind == VirtualProblemKind.UnitMismatch);
|
||||
Assert.Equal(
|
||||
"Solar A (kWh) and Water (m³) cannot be added or subtracted: their units differ.",
|
||||
AnalysisUiTestData.In("en", () => MeterEditorText.Problem(mismatch, Name(catalog))));
|
||||
Assert.Equal(
|
||||
"Solar A (kWh) und Water (m³) lassen sich nicht addieren oder subtrahieren: Ihre Einheiten unterscheiden sich.",
|
||||
AnalysisUiTestData.In("de", () => MeterEditorText.Problem(mismatch, Name(catalog))));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("m1 +", "The formula ends where a meter or a number is expected.")]
|
||||
[InlineData("m1 + n2", "“n2” is not a meter; refer to meters as m and their number, e.g. m12.")]
|
||||
[InlineData("(m1 + m2", "The parenthesis at position 1 is never closed.")]
|
||||
[InlineData("m1 % m2", "“%” is not allowed in a formula (position 4).")]
|
||||
[InlineData("m1 + m3 + m99", "m99 is not a meter.")]
|
||||
[InlineData("m1 + m2 - m3", "Solar A (Generation) and House (Consumption) measure different things; to combine them, set the result to Net.")]
|
||||
[InlineData("m3 * m9", "Multiplying or dividing meters (House, Garage) gives a ratio: set the result to Indicator.")]
|
||||
[InlineData("5", "The formula refers to no meter; a number alone is not a meter.")]
|
||||
public void Validation_problems_read_as_sentences(string expression, string expected)
|
||||
{
|
||||
var catalog = Catalog();
|
||||
var validation = MeterDraftAnalysis.Validate(catalog, NewVirtual() with { Definition = new VirtualDefinition(expression, KindFor(expression)) });
|
||||
|
||||
var texts = AnalysisUiTestData.In("en", () => validation.Problems.Select(p => MeterEditorText.Problem(p, Name(catalog))).ToList());
|
||||
Assert.Contains(expected, texts);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ totals override (D-23)
|
||||
|
||||
[Fact]
|
||||
public void Always_on_a_breakdown_is_refused_naming_the_counted_parent()
|
||||
{
|
||||
var catalog = Catalog();
|
||||
var car = new MeterDraft(Car, "Car", 1, MeterMode.CumulativeCounter, "kWh");
|
||||
var overlay = MeterDraftAnalysis.Overlay(catalog, car, null);
|
||||
|
||||
var always = MeterDraftAnalysis.CheckTotals(overlay, car, TotalsOverride.Always);
|
||||
Assert.False(always.IsAllowed);
|
||||
Assert.Equal(new TotalsConflict(TotalsConflictReason.OverlapsCountedMeter, House), always.Conflict);
|
||||
Assert.Equal(
|
||||
"“Always count” would count energy twice: House is already counted and overlaps this meter.",
|
||||
AnalysisUiTestData.In("en", () => MeterEditorText.Conflict(always.Conflict!, Name(catalog))));
|
||||
|
||||
Assert.True(MeterDraftAnalysis.CheckTotals(overlay, car, TotalsOverride.Never).IsAllowed);
|
||||
Assert.True(MeterDraftAnalysis.CheckTotals(overlay, car, TotalsOverride.Auto).IsAllowed);
|
||||
|
||||
// Unlinked from House in the dialog, the same meter is a root of its own and may be counted.
|
||||
var unlinked = car with { Upstream = [] };
|
||||
Assert.True(MeterDraftAnalysis.CheckTotals(MeterDraftAnalysis.Overlay(catalog, unlinked, null), unlinked, TotalsOverride.Always).IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_new_virtual_draft_is_laid_over_the_catalog_with_its_effective_definition()
|
||||
{
|
||||
var catalog = Catalog();
|
||||
var draft = NewVirtual() with { Definition = new VirtualDefinition("m1 + m2"), Upstream = [SolarA, SolarB] };
|
||||
var effective = MeterDraftAnalysis.Validate(catalog, draft).EffectiveDefinition!;
|
||||
|
||||
var overlay = MeterDraftAnalysis.Overlay(catalog, draft, effective);
|
||||
|
||||
var meter = overlay.Find(MeterDraft.NewMeterId)!;
|
||||
Assert.Equal(VirtualMeterStatus.Valid, meter.VirtualStatus);
|
||||
Assert.Equal(QuantityKind.Generation, meter.Quantity.Kind);
|
||||
Assert.Equal([SolarA, SolarB], overlay.Graph.DirectDependencies(MeterDraft.NewMeterId));
|
||||
Assert.Equal(2, overlay.Links.Count(l => l.ToMeterId == MeterDraft.NewMeterId));
|
||||
Assert.Equal(catalog.Meters.Count + 1, overlay.Meters.Count);
|
||||
Assert.Equal(MeterTotalsClass.AnalysisOnly, overlay.Totals.Meters[MeterDraft.NewMeterId].Class);
|
||||
|
||||
// The stored catalog is untouched.
|
||||
Assert.Null(catalog.Find(MeterDraft.NewMeterId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_totals_override_is_written_beside_every_other_key()
|
||||
{
|
||||
var meta = MeterDraftAnalysis.WithTotalsOverride("""{"role":"grid_import","expression":"m1"}""", TotalsOverride.Always);
|
||||
Assert.Equal(TotalsOverride.Always, TotalsOverrideTokens.FromMeta(meta));
|
||||
Assert.Equal("grid_import", MeterMeta.Role(meta));
|
||||
Assert.Contains("\"expression\":\"m1\"", meta, StringComparison.Ordinal);
|
||||
|
||||
var auto = MeterDraftAnalysis.WithTotalsOverride(meta, TotalsOverride.Auto);
|
||||
Assert.DoesNotContain("totals", auto, StringComparison.Ordinal);
|
||||
Assert.Equal("grid_import", MeterMeta.Role(auto));
|
||||
|
||||
Assert.Equal("""{"totals":"never"}""", MeterDraftAnalysis.WithTotalsOverride("not json", TotalsOverride.Never));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ helpers
|
||||
|
||||
/// <summary>A declared kind where a case needs one: a product declared as consumption, a mixed sum declared as generation.</summary>
|
||||
private static QuantityKind? KindFor(string expression) => expression switch
|
||||
{
|
||||
"m1 + m2 - m3" => QuantityKind.Generation,
|
||||
_ when expression.Contains('*', StringComparison.Ordinal) => QuantityKind.Consumption,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static MeterDraft NewVirtual() => new(0, "New", 1, MeterMode.Virtual, "kWh");
|
||||
|
||||
private static Func<int, string> Name(AnalysisCatalog catalog) =>
|
||||
id => catalog.Find(id)?.Name ?? (id == MeterDraft.NewMeterId ? "New" : CalculationDraft.Token(id));
|
||||
|
||||
/// <summary>
|
||||
/// Two solar meters and their stored sum, a house with a garage and a car below it, water in another type, a
|
||||
/// calculation that is not a sum (half the house), an edited virtual meter another one reads, and a legacy sum.
|
||||
/// </summary>
|
||||
private static AnalysisCatalog Catalog()
|
||||
{
|
||||
static string Def(string expression, QuantityKind kind, string unit, VirtualCostRule rule) =>
|
||||
VirtualDefinitionJson.Write("{}", new VirtualDefinition(expression, kind, unit, rule));
|
||||
|
||||
Meter M(int id, string name, MeterMode mode, string unit = "kWh", short type = 1, string meta = "{}") =>
|
||||
new() { Id = id, Name = name, EnergyTypeId = type, Mode = mode, Unit = unit, Meta = meta };
|
||||
|
||||
var solarA = M(SolarA, "Solar A", MeterMode.GenerationCounter);
|
||||
solarA.InstalledAt = new DateOnly(2021, 3, 1);
|
||||
Meter[] meters =
|
||||
[
|
||||
solarA,
|
||||
M(SolarB, "Solar B", MeterMode.GenerationCounter),
|
||||
M(House, "House", MeterMode.CumulativeCounter),
|
||||
M(Water, "Water", MeterMode.CumulativeCounter, "m3", type: 2),
|
||||
M(SolarSum, "Solar sum", MeterMode.Virtual, meta: Def("m1 + m2", QuantityKind.Generation, "kWh", VirtualCostRule.None)),
|
||||
M(HalfHouse, "Half house", MeterMode.Virtual, meta: Def("0.5 * m3", QuantityKind.Consumption, "kWh", VirtualCostRule.None)),
|
||||
M(Draft, "Draft", MeterMode.Virtual, meta: Def("m1 + m2", QuantityKind.Generation, "kWh", VirtualCostRule.None)),
|
||||
M(ReadsDraft, "Reads draft", MeterMode.Virtual, meta: Def("m7", QuantityKind.Generation, "kWh", VirtualCostRule.None)),
|
||||
M(Garage, "Garage", MeterMode.CumulativeCounter),
|
||||
M(Car, "Car", MeterMode.CumulativeCounter),
|
||||
M(Legacy, "Legacy sum", MeterMode.Virtual),
|
||||
];
|
||||
|
||||
MeterLink[] links =
|
||||
[
|
||||
new() { FromMeterId = SolarA, ToMeterId = SolarSum },
|
||||
new() { FromMeterId = SolarB, ToMeterId = SolarSum },
|
||||
new() { FromMeterId = House, ToMeterId = Car },
|
||||
new() { FromMeterId = SolarA, ToMeterId = Legacy },
|
||||
new() { FromMeterId = SolarB, ToMeterId = Legacy },
|
||||
];
|
||||
|
||||
return AnalysisCatalog.Build(meters, [], links, [], AnalysisUiTestData.Berlin);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
using MeterVault.App;
|
||||
using MeterVault.App.TariffEditing;
|
||||
using MeterVault.Core.Domain;
|
||||
using MeterVault.Infrastructure.Analysis;
|
||||
using MeterVault.Integration.Tests.Analysis;
|
||||
|
||||
namespace MeterVault.Integration.Tests.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// The tariff editor's link and unit rules (D-37, D-52): what <c>/admin/tariffs?scope=&id=&component=&from=&action=new</c>
|
||||
/// asks for and lists, and which units a save accepts for the scope's normalized units — pure, no database.
|
||||
/// </summary>
|
||||
public sealed class TariffEditingTests
|
||||
{
|
||||
// ------------------------------------------------------------------------------------------------ value (D-38)
|
||||
|
||||
[Fact]
|
||||
public void A_new_tariff_without_a_value_cannot_be_saved_while_a_typed_zero_is_a_deliberate_free_price()
|
||||
{
|
||||
// D-38: an explicit zero tariff is a valid zero — so it must be typed, never the default of an untouched field. The
|
||||
// deep link that explains a missing price must not turn it into a free period with one click.
|
||||
Assert.Equal(TariffValueVerdict.Missing, TariffValue.Check(null, TariffComponent.UnitPrice));
|
||||
Assert.True(TariffValue.Check(null, TariffComponent.BasePrice).BlocksSave());
|
||||
|
||||
var zero = TariffValue.Check(0, TariffComponent.UnitPrice);
|
||||
Assert.Equal(TariffValueVerdict.FreeOfCharge, zero);
|
||||
Assert.False(zero.BlocksSave());
|
||||
Assert.Equal(TariffValueVerdict.FreeOfCharge, TariffValue.Check(0, TariffComponent.BasePrice));
|
||||
Assert.Equal(TariffValueVerdict.Valid, TariffValue.Check(0.31, TariffComponent.UnitPrice));
|
||||
Assert.Equal(TariffValueVerdict.Valid, TariffValue.Check(0, TariffComponent.Tax));
|
||||
|
||||
AnalysisUiTestData.In("en", () =>
|
||||
{
|
||||
Assert.Equal("A price of 0 makes this period free of charge.", TariffValue.Note(TariffValueVerdict.FreeOfCharge));
|
||||
Assert.Equal("Enter a value.", TariffValue.Note(TariffValueVerdict.Missing));
|
||||
Assert.Null(TariffValue.Note(TariffValueVerdict.Valid));
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ deep link (D-52)
|
||||
|
||||
[Fact]
|
||||
public void A_missing_price_link_round_trips_into_a_prefilled_new_tariff()
|
||||
{
|
||||
var url = TariffLinks.New(TariffScope.Meter, 12, TariffComponent.UnitPrice, new DateOnly(2024, 1, 17));
|
||||
var query = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(new Uri("http://x" + url).Query);
|
||||
|
||||
var link = TariffDeepLink.Parse(query["scope"], query["id"], query["component"], query["from"], query["action"]);
|
||||
|
||||
Assert.Equal(new TariffDeepLink(TariffScope.Meter, 12, TariffComponent.UnitPrice, new DateOnly(2024, 1, 1), OpenNew: true), link);
|
||||
Assert.True(link.HasScope);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("type", "3", "feed-in", "2026-02-01", "new", TariffScope.EnergyType, 3, TariffComponent.FeedIn, true)]
|
||||
[InlineData("Meter", "7", "UnitPrice", null, null, TariffScope.Meter, 7, TariffComponent.UnitPrice, false)]
|
||||
[InlineData("global", "5", "base-price", "2025-06-01", "NEW", TariffScope.Global, null, TariffComponent.BasePrice, true)]
|
||||
public void Scope_component_date_and_action_are_read_case_insensitively(
|
||||
string scope, string id, string component, string? from, string? action,
|
||||
TariffScope expectedScope, int? expectedId, TariffComponent expectedComponent, bool openNew)
|
||||
{
|
||||
var link = TariffDeepLink.Parse(scope, id, component, from, action);
|
||||
|
||||
Assert.Equal(expectedScope, link.Scope);
|
||||
Assert.Equal(expectedId, link.ScopeId); // global takes no id, whatever the link says
|
||||
Assert.Equal(expectedComponent, link.Component);
|
||||
Assert.Equal(from is null ? null : DateOnly.Parse(from, System.Globalization.CultureInfo.InvariantCulture), link.From);
|
||||
Assert.Equal(openNew, link.OpenNew);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("planet", "3", "unit-price", "2026-01-01", "new")]
|
||||
[InlineData("type", null, "unit-price", "2026-01-01", "new")]
|
||||
[InlineData("meter", "0", "unit-price", "2026-01-01", "new")]
|
||||
[InlineData("meter", "-4", "unit-price", "2026-01-01", "new")]
|
||||
[InlineData("meter", "abc", "unit-price", "2026-01-01", "new")]
|
||||
public void A_scope_without_a_usable_target_scopes_nothing(string? scope, string? id, string? component, string? from, string? action)
|
||||
{
|
||||
var link = TariffDeepLink.Parse(scope, id, component, from, action);
|
||||
|
||||
Assert.Null(link.Scope);
|
||||
Assert.Null(link.ScopeId);
|
||||
Assert.False(link.HasScope);
|
||||
Assert.True(link.OpenNew); // the dialog still opens, just not prefilled with a scope
|
||||
Assert.Equal(TariffComponent.UnitPrice, link.Component);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Unknown_tokens_are_ignored_one_by_one()
|
||||
{
|
||||
var link = TariffDeepLink.Parse("meter", "4", "rebate", "31.12.2026", "open");
|
||||
|
||||
Assert.Equal(TariffScope.Meter, link.Scope);
|
||||
Assert.Equal(4, link.ScopeId);
|
||||
Assert.Null(link.Component);
|
||||
Assert.Null(link.From);
|
||||
Assert.False(link.OpenNew);
|
||||
Assert.Equal(TariffDeepLink.None, TariffDeepLink.Parse(null, null, null, null, null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_scoped_list_shows_what_can_price_the_scope_in_precedence_order()
|
||||
{
|
||||
// Meter 12 and 13 are electricity (type 1), meter 20 is water (type 2).
|
||||
int? TypeOf(int meter) => meter switch { 12 or 13 => 1, 20 => 2, _ => null };
|
||||
var global = Tariff(TariffScope.Global, null);
|
||||
var electricity = Tariff(TariffScope.EnergyType, 1);
|
||||
var water = Tariff(TariffScope.EnergyType, 2);
|
||||
var meter12 = Tariff(TariffScope.Meter, 12);
|
||||
var meter13 = Tariff(TariffScope.Meter, 13);
|
||||
var meter20 = Tariff(TariffScope.Meter, 20);
|
||||
Tariff[] all = [global, electricity, water, meter12, meter13, meter20];
|
||||
|
||||
IEnumerable<Tariff> Listed(TariffDeepLink link) => all.Where(t => link.Lists(t, TypeOf));
|
||||
|
||||
Assert.Equal([global, electricity, meter12], Listed(TariffDeepLink.Parse("meter", "12", null, null, null)));
|
||||
Assert.Equal([global, electricity, meter12, meter13], Listed(TariffDeepLink.Parse("type", "1", null, null, null)));
|
||||
Assert.Equal([global], Listed(TariffDeepLink.Parse("global", null, null, null, null)));
|
||||
Assert.Equal(all, Listed(TariffDeepLink.None));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ unit check (D-37)
|
||||
|
||||
[Theory]
|
||||
[InlineData("EUR/kWh", "kWh", TariffUnitVerdictKind.Fits)]
|
||||
[InlineData("ct/kWh", "kWh", TariffUnitVerdictKind.Fits)]
|
||||
[InlineData("EUR/MWh", "kWh", TariffUnitVerdictKind.Fits)]
|
||||
[InlineData("EUR/100 L", "L", TariffUnitVerdictKind.Fits)]
|
||||
[InlineData("EUR/m3", "m³", TariffUnitVerdictKind.Fits)]
|
||||
[InlineData("EUR/kWh brutto", "kWh", TariffUnitVerdictKind.Fits)]
|
||||
[InlineData("EUR/kWh", "m³", TariffUnitVerdictKind.Blocked)]
|
||||
[InlineData("EUR/month", "kWh", TariffUnitVerdictKind.Blocked)]
|
||||
[InlineData("USD/kWh", "kWh", TariffUnitVerdictKind.Blocked)]
|
||||
[InlineData("pauschal", "kWh", TariffUnitVerdictKind.Warning)]
|
||||
public void A_unit_price_must_be_quoted_per_the_unit_the_scope_bills(string unit, string meterUnit, TariffUnitVerdictKind expected)
|
||||
{
|
||||
var verdict = TariffUnitCheck.Check(unit, TariffComponent.UnitPrice, [new TariffUnitTarget("Netz", meterUnit)], "EUR");
|
||||
|
||||
Assert.Equal(expected, verdict.Kind);
|
||||
Assert.Equal(expected == TariffUnitVerdictKind.Blocked, verdict.Blocks);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("EUR/month", TariffUnitVerdictKind.Fits)]
|
||||
[InlineData("EUR/Tag", TariffUnitVerdictKind.Fits)]
|
||||
[InlineData("€/Jahr inkl. MwSt.", TariffUnitVerdictKind.Fits)]
|
||||
[InlineData("EUR/Quartal", TariffUnitVerdictKind.Fits)]
|
||||
[InlineData("EUR/kWh", TariffUnitVerdictKind.Blocked)]
|
||||
[InlineData("EUR/2 Monate", TariffUnitVerdictKind.Blocked)]
|
||||
[InlineData("CHF/month", TariffUnitVerdictKind.Blocked)]
|
||||
[InlineData("monthly fee", TariffUnitVerdictKind.Warning)]
|
||||
public void A_base_price_must_be_quoted_per_day_month_quarter_or_year(string unit, TariffUnitVerdictKind expected)
|
||||
{
|
||||
Assert.Equal(expected, TariffUnitCheck.Check(unit, TariffComponent.BasePrice, [], "EUR").Kind);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(TariffComponent.Bonus)]
|
||||
[InlineData(TariffComponent.Discount)]
|
||||
[InlineData(TariffComponent.Tax)]
|
||||
public void Bonus_discount_and_tax_are_stored_but_say_they_are_not_applied(TariffComponent component)
|
||||
{
|
||||
var verdict = TariffUnitCheck.Check("EUR/kWh", component, [new TariffUnitTarget("Wasser", "m³")], "EUR");
|
||||
|
||||
Assert.Equal(TariffUnitVerdictKind.NotApplied, verdict.Kind);
|
||||
Assert.False(verdict.Blocks);
|
||||
var lines = AnalysisUiTestData.In("en", () => TariffUnitCheck.Describe(verdict, "EUR"));
|
||||
Assert.Equal([(false, "Bonus, discount and tax tariffs are stored but not applied to costs yet.")], lines);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_global_price_over_several_units_fits_some_and_warns_about_the_rest()
|
||||
{
|
||||
TariffUnitTarget[] targets = [new("Netz", "kWh"), new("Wasser", "m³")];
|
||||
|
||||
var verdict = TariffUnitCheck.Check("EUR/kWh", TariffComponent.UnitPrice, targets, "EUR");
|
||||
|
||||
Assert.Equal(TariffUnitVerdictKind.Warning, verdict.Kind);
|
||||
Assert.Equal(TariffUnitProblem.PartlyFits, verdict.Problem);
|
||||
var lines = AnalysisUiTestData.In("en", () => TariffUnitCheck.Describe(verdict, "EUR"));
|
||||
Assert.Equal(
|
||||
[(false, "Read as EUR per kWh."), (false, "Fits Netz (kWh)."), (true, "Does not fit Wasser, which measures in m³.")],
|
||||
lines);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_verdict_reads_in_german_too()
|
||||
{
|
||||
var blocked = TariffUnitCheck.Check("EUR/kWh", TariffComponent.UnitPrice, [new TariffUnitTarget("Zähler Wasser", "m³")], "EUR");
|
||||
var monthly = TariffUnitCheck.Check("EUR/month", TariffComponent.BasePrice, [], "EUR");
|
||||
|
||||
AnalysisUiTestData.In("de", () =>
|
||||
{
|
||||
Assert.Equal(
|
||||
[(false, "Gelesen als EUR pro kWh."), (true, "Passt nicht zu Zähler Wasser (gemessen in m³).")],
|
||||
TariffUnitCheck.Describe(blocked, "EUR"));
|
||||
Assert.Equal([(false, "Gelesen als EUR pro Monat, verteilt auf die Tage dieses Zeitraums.")], TariffUnitCheck.Describe(monthly, "EUR"));
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Targets_are_what_the_scope_bills_by_normalized_unit()
|
||||
{
|
||||
// Electricity: House (total load), Grid (grid import, billed), PV (generation), Export (grid export). Water: one meter.
|
||||
Meter M(int id, string name, MeterMode mode, string unit, short type, string? role = null) => new()
|
||||
{
|
||||
Id = id, Name = name, EnergyTypeId = type, Mode = mode, Unit = unit, Meta = role is null ? "{}" : MeterMeta.SetRole("{}", role),
|
||||
};
|
||||
Meter[] meters =
|
||||
[
|
||||
M(1, "House", MeterMode.CumulativeCounter, "kWh", 1, "total_load"),
|
||||
M(2, "Grid", MeterMode.CumulativeCounter, "kWh", 1, "grid_import"),
|
||||
M(3, "PV", MeterMode.GenerationCounter, "kWh", 1),
|
||||
M(4, "Export", MeterMode.CumulativeCounter, "kWh", 1, "grid_export"),
|
||||
M(5, "Water", MeterMode.CumulativeCounter, "m3", 2),
|
||||
];
|
||||
var catalog = AnalysisCatalog.Build(meters, [], [new MeterLink { FromMeterId = 2, ToMeterId = 1 }], [], AnalysisUiTestData.Berlin);
|
||||
(string, string)? TypeInfo(int id) => id switch { 1 => ("Strom", "kWh"), 2 => ("Wasser", "m³"), 3 => ("Gas", "kWh"), _ => null };
|
||||
|
||||
Assert.Equal([new TariffUnitTarget("Grid", "kWh")], TariffUnitCheck.TargetsFor(catalog, TariffScope.EnergyType, 1, TariffComponent.UnitPrice, TypeInfo));
|
||||
Assert.Equal([new TariffUnitTarget("Export", "kWh")], TariffUnitCheck.TargetsFor(catalog, TariffScope.EnergyType, 1, TariffComponent.FeedIn, TypeInfo));
|
||||
Assert.Equal([new TariffUnitTarget("Water", "m³")], TariffUnitCheck.TargetsFor(catalog, TariffScope.Meter, 5, TariffComponent.UnitPrice, TypeInfo));
|
||||
Assert.Equal(
|
||||
[new TariffUnitTarget("Grid", "kWh"), new TariffUnitTarget("Water", "m³")],
|
||||
TariffUnitCheck.TargetsFor(catalog, TariffScope.Global, null, TariffComponent.UnitPrice, TypeInfo));
|
||||
|
||||
// A type that bills nothing yet is checked against its base unit; a base price has no quantity to check.
|
||||
Assert.Equal([new TariffUnitTarget("Gas", "kWh")], TariffUnitCheck.TargetsFor(catalog, TariffScope.EnergyType, 3, TariffComponent.UnitPrice, TypeInfo));
|
||||
Assert.Empty(TariffUnitCheck.TargetsFor(catalog, TariffScope.EnergyType, 1, TariffComponent.BasePrice, TypeInfo));
|
||||
Assert.Empty(TariffUnitCheck.TargetsFor(catalog, TariffScope.Meter, 99, TariffComponent.UnitPrice, TypeInfo));
|
||||
|
||||
// Nothing billed at all: the unit is read, and the check says it had nothing to compare with.
|
||||
var none = TariffUnitCheck.Check("EUR/kWh", TariffComponent.FeedIn, [], "EUR");
|
||||
Assert.Equal(TariffUnitProblem.NoTargets, none.Problem);
|
||||
Assert.False(none.Blocks);
|
||||
}
|
||||
|
||||
private static Tariff Tariff(TariffScope scope, int? id) =>
|
||||
new() { ScopeType = scope, ScopeId = id, Component = TariffComponent.UnitPrice, Unit = "EUR/kWh", Value = 0.3 };
|
||||
}
|
||||
Reference in New Issue
Block a user