using MeterVault.App.Analysis; using MeterVault.App.AnalysisPage; using MeterVault.Core.Analysis; using MeterVault.Core.Analysis.Virtual; using MeterVault.Core.Domain; using MeterVault.Infrastructure.Analysis; using MeterVault.Infrastructure.Costing; using MeterVault.Infrastructure.Options; using MeterVault.Integration.Tests.Costing; using static MeterVault.Integration.Tests.Costing.CostSandbox; namespace MeterVault.Integration.Tests.Analysis; /// /// What the Analysis page reads (brief §7.4): the portfolio cost is the bill the cost reader prices for the same range — /// manual costs once, the same total whatever the bucket (D-36) — two historical years compare bucket by bucket from the /// shared reader, and a selection that cannot be one chart (seven meters, a category of mixed units) reads nothing and /// explains. Frozen clock of , Berlin. /// [Collection("Timescale")] public sealed class AnalysisPageLoaderTests(TimescaleFixture fx) { [Fact] public async Task The_portfolio_cost_is_the_bill_with_manual_costs_once_whatever_the_bucket() { await using var box = new CostSandbox(fx); var type = await box.TypeAsync(); await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2024, 1, 1), 100, 50); await box.TypePriceAsync(type, 0.30, D(2023, 1, 1)); await box.ManualCostAsync(D(2024, 2, 10), 40); var view = await LoadAsync("/trends?from=2024-01-01&to=2024-02-29&bucket=month&compare=none"); Assert.Equal(AnalysisPageViewKind.Cost, view.Kind); Assert.Equal(QueryScope.Portfolio, view.Selection.Scope); var cost = Assert.Single(view.Costs); Assert.Null(cost.Comparison); // The very figure the cost reader gives the Overview for the same range. var bill = await Readers().Costs.ReadAsync(new CostAnalysisRequest(CostScope.Portfolio, Custom(D(2024, 1, 1), D(2024, 2, 29))) { Bucket = BucketSize.Month }); Assert.Equal(bill.Total.Cost, cost.Current.Total.Cost); CostAssert.Priced(30 + 15 + 40, cost.Current.Total); Assert.Equal(40, cost.Current.Total.Manual!.Value, 6); Assert.Equal(45, cost.Current.Total.Usage!.Value, 6); CostAssert.Cost(30, cost.Current.Buckets[0]); CostAssert.Cost(15 + 40, cost.Current.Buckets[1]); // One chart series and one table series, in the currency. var chart = Assert.Single(view.Chart); Assert.Equal("EUR", chart.Currency); Assert.True(Assert.Single(view.Table).IsMoney); // A finer or coarser bucket never changes the period total (D-36). foreach (var bucket in new[] { "week", "day", "year" }) { var other = await LoadAsync($"/trends?from=2024-01-01&to=2024-02-29&bucket={bucket}&compare=none"); Assert.Equal(cost.Current.Total.Cost!.Value, other.Costs.Single().Current.Total.Cost!.Value, 6); Assert.Equal(40, other.Costs.Single().Current.Total.Manual!.Value, 6); } } [Fact] public async Task Two_historical_years_compare_bucket_by_bucket_with_the_overlay_and_the_table() { await using var box = new CostSandbox(fx); var type = await box.TypeAsync(); var meter = await box.MonthlyAsync( type, MeterMode.CumulativeCounter, D(2023, 1, 1), 80, 40, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 100, 50, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20); await box.TypePriceAsync(type, 0.30, D(2023, 1, 1)); var view = await LoadAsync($"/trends?scope=meter&id={meter}&from=2024-01-01&to=2024-12-31&compare=year:2023"); Assert.Equal(AnalysisPageViewKind.Quantity, view.Kind); Assert.Equal(BucketSize.Month, view.Plan!.Size); var series = Assert.Single(view.Series); Assert.Equal(meter, series.MeterId); Assert.Equal(350, series.Total.Value!.Value, 6); // The comparison year, bucket by bucket, and the change over what both years cover. Assert.True(view.Comparison!.IsApplicable); Assert.Equal(12, view.Pairs!.Count); Assert.Equal(D(2023, 1, 1), view.Pairs[0].Comparison.FirstDay); var comparison = series.Comparison!; Assert.Equal(80, comparison.Values[0].Value!.Value, 6); Assert.Equal(40, comparison.Values[1].Value!.Value, 6); Assert.Equal(220, comparison.Total.Value!.Value, 6); Assert.True(view.Matched!.IsComparable); Assert.Equal(130, comparison.Change.Absolute!.Value, 6); // The overlay shares the meter's colour; the table carries the comparison and the meter's cost by its rule. Assert.Contains(view.Chart, c => c.IsComparison && c.BaseKey == series.Key.Id); var table = Assert.Single(view.Table); Assert.NotNull(table.Comparison); Assert.NotNull(table.Costs); CostAssert.Priced(350 * 0.30, view.MeterCost!.Total); // The previous year as a preset is the same comparison. var previous = await LoadAsync($"/trends?scope=meter&id={meter}&from=2024-01-01&to=2024-12-31"); Assert.Equal(220, previous.Series.Single().Comparison!.Total.Value!.Value, 6); } [Fact] public async Task Seven_meters_are_refused_before_anything_is_read() { await using var box = new CostSandbox(fx); var type = await box.TypeAsync(); var ids = new List(); for (var i = 0; i < 7; i++) { ids.Add(await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2024, 1, 1), 10 + i)); } var (loader, reader, _) = Readers(); var options = await AnalysisPageOptions.LoadAsync(fx, reader); var query = AnalysisQuery.Default(AnalysisDefaults.History).WithScope(QueryScope.ForMeters(ids)); var selection = AnalysisSelection.Resolve(query, options); var view = await loader.LoadAsync(query, selection, options, Now); Assert.Equal(AnalysisPageRefusal.TooManyMeters, view.Selection.Refusal); Assert.True(view.IsRefused); Assert.Null(view.Plan); Assert.Empty(view.Series); Assert.Empty(view.Chart); // Six of them compare side by side, each its own series from the shared reader. var six = query.WithScope(QueryScope.ForMeters(ids.Take(6))); var shown = await loader.LoadAsync(six, AnalysisSelection.Resolve(six, options), options, Now); Assert.False(shown.IsRefused); Assert.Equal(ids.Take(6), shown.Series.Select(s => s.MeterId!.Value)); } [Fact] public async Task A_category_of_mixed_units_explains_while_one_of_a_single_unit_shows_its_meters_side_by_side() { await using var box = new CostSandbox(fx); var power = await box.TypeAsync(); var water = await box.TypeAsync("m³"); var house = await box.MonthlyAsync(power, MeterMode.CumulativeCounter, D(2024, 1, 1), 100, 50); var car = await box.MonthlyAsync(power, MeterMode.CumulativeCounter, D(2024, 1, 1), 10, 20); var tap = await box.MeterAsync(water, MeterMode.CumulativeCounter, "m³", installedAt: D(2024, 1, 1)); await box.MonthlyReadingsAsync(tap, D(2024, 1, 1), 5, 6); await box.TypePriceAsync(power, 0.30, D(2023, 1, 1)); var mixed = await box.CategoryAsync($"mixed-{Guid.NewGuid():N}", 91, meters: [house, tap]); var single = await box.CategoryAsync($"single-{Guid.NewGuid():N}", 92, meters: [house, car]); const string Range = "&from=2024-01-01&to=2024-02-29&bucket=month&compare=none"; // kWh and m³: no quantity, and nothing read — the explanation names each group. var refused = await LoadAsync($"/trends?scope=category&id={mixed}&metric=consumption{Range}"); Assert.Equal(AnalysisPageRefusal.CategoryMixed, refused.Selection.Refusal); Assert.True(refused.IsRefused); Assert.Null(refused.Plan); Assert.Empty(refused.Series); Assert.Equal(2, refused.Selection.Groups.Count); // Its cost is always there. var mixedCost = await LoadAsync($"/trends?scope=category&id={mixed}{Range}"); Assert.Equal(AnalysisPageViewKind.Cost, mixedCost.Kind); var categoryBill = await Readers().Costs.ReadAsync( new CostAnalysisRequest(CostScope.ForCategory(mixed), Custom(D(2024, 1, 1), D(2024, 2, 29))) { Bucket = BucketSize.Month }); Assert.Equal(categoryBill.Total.Cost, mixedCost.Costs.Single().Current.Total.Cost); // Two kWh consumption meters: side by side, each exactly as the reader reads it on its own, never added up. var shown = await LoadAsync($"/trends?scope=category&id={single}&metric=consumption{Range}"); Assert.False(shown.IsRefused); Assert.Equal([house, car], shown.Series.Select(s => s.MeterId!.Value)); Assert.Equal(150, shown.Series[0].Total.Value!.Value, 6); Assert.Equal(30, shown.Series[1].Total.Value!.Value, 6); Assert.Equal(2, shown.Table.Count); Assert.DoesNotContain(shown.Table, t => t.Total?.Value is 180); } [Fact] public async Task An_energy_type_shows_its_measures_side_by_side_named_by_the_meters_they_count() { await using var box = new CostSandbox(fx); var type = await box.TypeAsync(); await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2024, 1, 1), 100, 50); var view = await LoadAsync($"/trends?scope=type&id={type}&from=2024-01-01&to=2024-02-29&bucket=month"); Assert.Equal(AnalysisMetric.Consumption, view.Selection.Metric); var use = Assert.Single(view.Series); Assert.Equal(Core.Analysis.Totals.TotalsMeasure.Use, use.Key.Measure); Assert.Equal(150, use.Total.Value!.Value, 6); Assert.Equal(use.Total.Value, view.Quantities!.MeasureFor(type, Core.Analysis.Totals.TotalsMeasure.Use)!.Total.Value); // Nothing in the range but data before it: no data for this period, and the dates that have some. var empty = await LoadAsync($"/trends?scope=type&id={type}&from=2025-01-01&to=2025-02-28"); Assert.True(empty.HasNoData); Assert.Equal(D(2024, 1, 1), empty.Availability!.FirstDay); } [Fact] public async Task A_source_without_data_is_named_in_the_figures_of_a_virtual_meter() { // Brief §4.3 "name the problem and affected source": the table and chart of /trends?scope=meter name the source a // bucket misses by its name — as the attention list does — never "#id". await using var box = new CostSandbox(fx); var type = await box.TypeAsync(); var a = await box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2025, 1, 1), 100, 80); var b = await box.MonthlyAsync(type, MeterMode.GenerationCounter, D(2025, 1, 1), 150); var sum = await box.VirtualAsync(type, $"m{a} + m{b}", QuantityKind.Generation, "kWh", VirtualCostRule.None); string bName; await using (var db = fx.CreateContext()) { bName = (await db.Meters.FindAsync(b))!.Name; } var view = await AnalysisUiTestData.In("en", () => LoadAsync($"/trends?scope=meter&id={sum}&from=2025-01-01&to=2025-02-28&bucket=month&compare=none")); var table = Assert.Single(view.Table); var february = table.Values[1]; Assert.Null(february.Value); Assert.Contains(bName, february.Status.Detail, StringComparison.Ordinal); Assert.DoesNotContain("#" + b.ToString(System.Globalization.CultureInfo.InvariantCulture), february.Status.Detail!, StringComparison.Ordinal); Assert.Contains(bName, table.Total!.Status.Detail, StringComparison.Ordinal); Assert.Contains(bName, view.Chart.Single().Values[1].Note, StringComparison.Ordinal); } [Fact] public async Task A_type_of_monthly_meters_resolves_months_so_a_month_has_no_finer_bucket_to_open() { // D-51: drilling goes to the next finer bucket the data supports. A type's measure carries the resolution of the // meters it counts — monthly here — so a month is not opened into 31 days of "only coarser data". await using var box = new CostSandbox(fx); var type = await box.TypeAsync(); await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2025, 1, 1), 100, 80, 90); var (_, reader, _) = Readers(); var result = await reader.ReadAsync( new AnalysisRequest(AnalysisScope.ForEnergyType(type), Custom(D(2025, 1, 1), D(2025, 3, 31))) { Bucket = BucketSize.Month }); Assert.Equal(ResolutionClass.Month, Assert.Single(result.Measures).Resolution); var view = await LoadAsync($"/trends?scope=type&id={type}&metric=consumption&from=2025-01-01&to=2025-03-31&bucket=month"); Assert.Equal(ResolutionClass.Month, view.Resolution); Assert.Null(AnalysisNavigation.DrillInto(view.Query, view.Plan!.Buckets[1], view.Resolution)); } [Fact] public async Task A_category_of_calculated_views_explains_itself_instead_of_no_data_yet() { // Brief §4.3: an explained result, not "nothing has been recorded yet" — its member has data and a cost of its own. await using var box = new CostSandbox(fx); var type = await box.TypeAsync(); var a = await box.MonthlyAsync(type, MeterMode.CumulativeCounter, D(2025, 1, 1), 100, 80); await box.TypePriceAsync(type, 0.30, D(2024, 1, 1)); var view = await box.VirtualAsync(type, $"m{a}", QuantityKind.Consumption, "kWh", VirtualCostRule.SourceCosts); var category = await box.CategoryAsync($"views-{Guid.NewGuid():N}", 95, meters: [view]); var page = await LoadAsync($"/trends?scope=category&id={category}&metric=cost&from=2025-01-01&to=2025-02-28&bucket=month&compare=none"); Assert.False(page.HasNoData); Assert.Contains(page.CostAttention, x => x.Kind == CostAttentionKind.CategoryPricesNothing && x.MeterIds.Contains(view)); } private (AnalysisPageLoader Loader, AnalysisReader Reader, CostReader Costs) Readers() { var options = Microsoft.Extensions.Options.Options.Create(new MeterVaultOptions { TimeZone = BerlinId, Currency = "EUR" }); var reader = new AnalysisReader(fx, options); var costs = new CostReader(fx, reader, options); return (new AnalysisPageLoader(reader, costs, new AnalysisPeriods(reader, costs)), reader, costs); } private async Task LoadAsync(string url) { var (loader, reader, _) = Readers(); var options = await AnalysisPageOptions.LoadAsync(fx, reader); var query = AnalysisQuery.Parse(url, AnalysisDefaults.History); return await loader.LoadAsync(query, AnalysisSelection.Resolve(query, options), options, Now); } }