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.
154 lines
6.7 KiB
C#
154 lines
6.7 KiB
C#
using MeterVault.Core.Analysis;
|
||
using MeterVault.Core.Analysis.Costing;
|
||
using MeterVault.Core.Analysis.Totals;
|
||
using MeterVault.Core.Domain;
|
||
|
||
namespace MeterVault.Core.Tests.Analysis.Costing;
|
||
|
||
/// <summary>
|
||
/// Builders for the cost-calculator tests: real buckets from the period resolver and bucket planner (Berlin), tariffs,
|
||
/// and quantities per part. Nothing here reads the wall clock.
|
||
/// </summary>
|
||
internal static class CostingTestData
|
||
{
|
||
public const int Electricity = 1;
|
||
public const int Water = 2;
|
||
public const int Oil = 3;
|
||
|
||
public const int Grid = 10;
|
||
public const int Heater = 11;
|
||
public const int Export = 12;
|
||
public const int WaterMeter = 20;
|
||
public const int OilTank = 30;
|
||
|
||
/// <summary>A "now" long after every range the tests price, so custom ranges resolve as complete.</summary>
|
||
public static readonly DateTimeOffset FarFuture = AnalysisClock.Utc(2040, 1, 1);
|
||
|
||
public static DateOnly D(int year, int month, int day) => new(year, month, day);
|
||
|
||
/// <summary>The buckets of the complete range <paramref name="first"/> – <paramref name="last"/> (inclusive), as the planner cuts them.</summary>
|
||
public static IReadOnlyList<AnalysisBucket> Buckets(BucketSize size, DateOnly first, DateOnly last)
|
||
{
|
||
var period = PeriodResolver.Resolve(PeriodPreset.Custom, first, last, FarFuture, AnalysisClock.Berlin);
|
||
return Plan(period, size);
|
||
}
|
||
|
||
/// <summary>The buckets of a to-date preset at <paramref name="now"/> (Berlin).</summary>
|
||
public static IReadOnlyList<AnalysisBucket> ToDate(PeriodPreset preset, DateTimeOffset now, BucketSize size) =>
|
||
Plan(PeriodResolver.Resolve(preset, null, null, now, AnalysisClock.Berlin), size);
|
||
|
||
/// <summary>A bucket spelled out, for the cases a planner never produces (a bucket reaching past today).</summary>
|
||
public static AnalysisBucket Bucket(DateOnly first, DateOnly end, BucketSize size = BucketSize.Month) =>
|
||
new(first, end, AnalysisClock.At(AnalysisClock.Berlin, first.Year, first.Month, first.Day),
|
||
AnalysisClock.At(AnalysisClock.Berlin, end.Year, end.Month, end.Day), size);
|
||
|
||
public static Tariff Tariff(
|
||
int id,
|
||
TariffScope scope,
|
||
int? scopeId,
|
||
TariffComponent component,
|
||
double value,
|
||
string unit,
|
||
DateOnly from,
|
||
DateOnly? to = null) => new()
|
||
{
|
||
Id = id,
|
||
ScopeType = scope,
|
||
ScopeId = scopeId,
|
||
Component = component,
|
||
Value = value,
|
||
Unit = unit,
|
||
ValidFrom = from,
|
||
ValidTo = to,
|
||
};
|
||
|
||
/// <summary>A unit price of an energy type.</summary>
|
||
public static Tariff TypePrice(int id, int energyTypeId, double value, string unit, DateOnly from, DateOnly? to = null) =>
|
||
Tariff(id, TariffScope.EnergyType, energyTypeId, TariffComponent.UnitPrice, value, unit, from, to);
|
||
|
||
/// <summary>A meter's own unit price.</summary>
|
||
public static Tariff MeterPrice(int id, int meterId, double value, string unit, DateOnly from, DateOnly? to = null) =>
|
||
Tariff(id, TariffScope.Meter, meterId, TariffComponent.UnitPrice, value, unit, from, to);
|
||
|
||
public static Tariff BasePrice(int id, TariffScope scope, int? scopeId, double value, string unit, DateOnly from, DateOnly? to = null) =>
|
||
Tariff(id, scope, scopeId, TariffComponent.BasePrice, value, unit, from, to);
|
||
|
||
public static Tariff FeedInPrice(int id, int energyTypeId, double value, string unit, DateOnly from) =>
|
||
Tariff(id, TariffScope.EnergyType, energyTypeId, TariffComponent.FeedIn, value, unit, from);
|
||
|
||
public static TariffBook Book(params Tariff[] tariffs) => TariffBook.Create(tariffs, "EUR");
|
||
|
||
/// <summary>Every part's quantity from a per-day amount: the sum over its days.</summary>
|
||
public static List<CostQuantity> Daily(IReadOnlyList<AnalysisBucket> buckets, Func<DateOnly, double> perDay) =>
|
||
[.. CostCalculator.Parts(buckets).Select(p => CostQuantity.Known(p, DaysOf(p).Sum(perDay)))];
|
||
|
||
/// <summary>Every part's quantity from an amount per whole local month, prorated by days when a part is shorter.</summary>
|
||
public static List<CostQuantity> Monthly(IReadOnlyList<AnalysisBucket> buckets, Func<DateOnly, double?> perMonth) =>
|
||
[.. CostCalculator.Parts(buckets).Select(p => perMonth(p.Month) is { } amount
|
||
? CostQuantity.Known(p, amount * p.Days / DateTime.DaysInMonth(p.Month.Year, p.Month.Month))
|
||
: CostQuantity.Unknown(p))];
|
||
|
||
/// <summary>Every part the same amount.</summary>
|
||
public static List<CostQuantity> Each(IReadOnlyList<AnalysisBucket> buckets, double amount) =>
|
||
[.. CostCalculator.Parts(buckets).Select(p => CostQuantity.Known(p, amount))];
|
||
|
||
public static CostLine Line(
|
||
int meterId,
|
||
int energyTypeId,
|
||
IReadOnlyList<CostQuantity> quantities,
|
||
string unit = "kWh",
|
||
BillLineKind kind = BillLineKind.UnitPrice,
|
||
ServicePeriod? service = null) =>
|
||
new(meterId, energyTypeId, kind, unit, quantities, service);
|
||
|
||
public static CostResult Price(
|
||
IReadOnlyList<AnalysisBucket> buckets,
|
||
TariffBook book,
|
||
IEnumerable<CostLine> lines,
|
||
DateOnly? today = null,
|
||
IEnumerable<StandingChargeScope>? standing = null,
|
||
IEnumerable<ManualCost>? manual = null) =>
|
||
CostCalculator.Calculate(new CostRequest(
|
||
buckets,
|
||
today ?? D(2039, 12, 31),
|
||
book,
|
||
[.. lines],
|
||
standing is null ? null : [.. standing],
|
||
manual is null ? null : [.. manual]));
|
||
|
||
public static ManualCost Manual(int id, DateOnly start, double amount, int? categoryId = null, int? meterId = null, DateOnly? end = null, string currency = "EUR") => new()
|
||
{
|
||
Id = id,
|
||
CategoryId = categoryId,
|
||
MeterId = meterId,
|
||
PeriodStart = start,
|
||
PeriodEnd = end ?? start,
|
||
Amount = amount,
|
||
Currency = currency,
|
||
};
|
||
|
||
/// <summary>The cost of the bucket starting on <paramref name="first"/>.</summary>
|
||
public static CostAmount At(this IReadOnlyList<CostAmount> cells, IReadOnlyList<AnalysisBucket> buckets, DateOnly first)
|
||
{
|
||
for (var i = 0; i < buckets.Count; i++)
|
||
{
|
||
if (buckets[i].FirstDay == first)
|
||
{
|
||
return cells[i];
|
||
}
|
||
}
|
||
|
||
throw new InvalidOperationException($"No bucket starts on {first:yyyy-MM-dd}.");
|
||
}
|
||
|
||
private static IEnumerable<DateOnly> DaysOf(CostPart part) =>
|
||
Enumerable.Range(0, part.Days).Select(part.FirstDay.AddDays);
|
||
|
||
private static IReadOnlyList<AnalysisBucket> Plan(ResolvedPeriod period, BucketSize size)
|
||
{
|
||
var plan = BucketPlanner.Plan(period, size, maxPoints: 10_000);
|
||
Assert.False(plan.Refused);
|
||
return plan.Buckets;
|
||
}
|
||
}
|