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.
335 lines
14 KiB
C#
335 lines
14 KiB
C#
using MeterVault.App.Analysis;
|
|
using MeterVault.Core.Analysis;
|
|
using MeterVault.Core.Analysis.Quantities;
|
|
using MeterVault.Infrastructure.Analysis;
|
|
|
|
namespace MeterVault.App.AnalysisPage;
|
|
|
|
/// <summary>Why the Analysis page cannot show what its address asks for, and explains instead (brief §7.4).</summary>
|
|
public enum AnalysisPageRefusal
|
|
{
|
|
None,
|
|
|
|
/// <summary>The energy type, category or meter does not exist (any more).</summary>
|
|
UnknownScope,
|
|
|
|
/// <summary>More meters than can be compared side by side (<see cref="AnalysisLimits.MaxSeries"/>); never cut silently.</summary>
|
|
TooManyMeters,
|
|
|
|
/// <summary>A category asked for a quantity while its meters measure different kinds or units.</summary>
|
|
CategoryMixed,
|
|
|
|
/// <summary>A category asked for a quantity has no meters (its costs are manual costs only).</summary>
|
|
CategoryWithoutMeters,
|
|
|
|
/// <summary>A category asked for a quantity has more meters than can be charted side by side.</summary>
|
|
CategoryTooManyMeters,
|
|
}
|
|
|
|
/// <summary>What the page did differently from the address, and says so.</summary>
|
|
public enum AnalysisPageNoticeKind
|
|
{
|
|
/// <summary>The metric does not apply to the selection; its natural metric is shown instead.</summary>
|
|
MetricNotAvailable,
|
|
|
|
/// <summary>Some selected meters do not exist and were left out.</summary>
|
|
UnknownMetersLeftOut,
|
|
}
|
|
|
|
/// <summary>A page notice with the metric it is about (for <see cref="AnalysisPageNoticeKind.MetricNotAvailable"/>).</summary>
|
|
public sealed record AnalysisPageNotice(AnalysisPageNoticeKind Kind, AnalysisMetric? Requested = null, AnalysisMetric? Shown = null);
|
|
|
|
/// <summary>Meters of one kind and unit, e.g. the consumption meters of a mixed category, in kWh.</summary>
|
|
public sealed record AnalysisMeterGroup(QuantityKind Kind, string Unit, IReadOnlyList<int> MeterIds)
|
|
{
|
|
public AnalysisMetric? Metric => AnalysisMetrics.MetricOf(Kind);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The Analysis page's reading of its address against what exists (brief §7.4, D-47): the scope and its name, the metrics
|
|
/// the scope supports and the one shown, the meters shown as series, and — when the address asks for something that
|
|
/// cannot be shown as one quantity — the reason in <see cref="Refusal"/>. Pure: the page, the CSV link and the tests read
|
|
/// the same answer.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// <b>Metrics.</b> The portfolio and an energy type offer the quantity metrics of their per-type measures (D-22) and the
|
|
/// cost; a meter its own quantity and — when it can be costed — its cost; a comparison the metrics of its meters and the
|
|
/// cost. A cost category is analysed by cost, and by a quantity only when all its meters measure one kind in one unit.
|
|
/// A metric the scope does not support falls back to the scope's natural one with a notice (D-02), except a category
|
|
/// quantity, which is explained, never silently turned into a cost.
|
|
/// </para>
|
|
/// <para>
|
|
/// <b>Series.</b> A comparison shows the meters that measure the chosen metric (a meter measures what it measures) and
|
|
/// names the others; its cost shows the meters that can have one. A category's quantity is its meters side by side —
|
|
/// each from the shared reader, never added up, because members may overlap (D-22).
|
|
/// </para>
|
|
/// </remarks>
|
|
public sealed record AnalysisSelection
|
|
{
|
|
private AnalysisSelection(QueryScope scope, AnalysisMetric? metric)
|
|
{
|
|
Scope = scope;
|
|
Metric = metric;
|
|
}
|
|
|
|
/// <summary>The scope shown (unknown meters of a comparison left out).</summary>
|
|
public QueryScope Scope { get; private init; }
|
|
|
|
/// <summary>The metric shown; null for a meter's own quantity when it has no metric (an indicator).</summary>
|
|
public AnalysisMetric? Metric { get; private init; }
|
|
|
|
/// <summary>The metrics the scope supports, in the order the selector lists them.</summary>
|
|
public IReadOnlyList<AnalysisMetric> Metrics { get; private init; } = [];
|
|
|
|
/// <summary>What the scope shows without a <c>metric</c> key.</summary>
|
|
public AnalysisMetric? NaturalMetric { get; private init; }
|
|
|
|
/// <summary>The meters shown as series (meter, comparison, category quantity); empty for measure and whole-scope cost views.</summary>
|
|
public IReadOnlyList<int> SeriesMeterIds { get; private init; } = [];
|
|
|
|
/// <summary>Selected meters not shown for this metric (another kind, or no cost of their own).</summary>
|
|
public IReadOnlyList<int> HiddenMeterIds { get; private init; } = [];
|
|
|
|
/// <summary>For <see cref="AnalysisPageRefusal.CategoryMixed"/>: the category's meters by kind and unit.</summary>
|
|
public IReadOnlyList<AnalysisMeterGroup> Groups { get; private init; } = [];
|
|
|
|
public AnalysisPageRefusal Refusal { get; private init; }
|
|
|
|
public IReadOnlyList<AnalysisPageNotice> Notices { get; private init; } = [];
|
|
|
|
/// <summary>The scope's name (a type, category or meter — user data); null for the portfolio and a comparison.</summary>
|
|
public string? ScopeName { get; private init; }
|
|
|
|
/// <summary>The energy type the scope belongs to (a type, or a meter's type).</summary>
|
|
public int? EnergyTypeId { get; private init; }
|
|
|
|
/// <summary>True when the metric shown is the cost.</summary>
|
|
public bool IsCost => Metric == AnalysisMetric.Cost;
|
|
|
|
/// <summary>True when the values shown are meters' own series (a meter, a comparison, a category's meters).</summary>
|
|
public bool ShowsMeters => !IsCost && Scope.Kind is QueryScopeKind.Meter or QueryScopeKind.Meters or QueryScopeKind.Category;
|
|
|
|
/// <summary>
|
|
/// The query the readers are asked with: the metric shown written out, and for a view of meters their explicit
|
|
/// selection — so resolving <c>all</c> (D-19), reading and the CSV export all see the same scope.
|
|
/// </summary>
|
|
public AnalysisQuery ReadQuery(AnalysisQuery query)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(query);
|
|
|
|
var read = query.WithMetric(Metric);
|
|
return ShowsMeters && Scope.Kind != QueryScopeKind.Meter && SeriesMeterIds.Count > 0
|
|
? read.WithScope(QueryScope.ForMeters(SeriesMeterIds))
|
|
: read.WithScope(Scope);
|
|
}
|
|
|
|
/// <summary>
|
|
/// <paramref name="query"/> as the page shows it: the scope shown and the metric shown, with no <c>metric</c> key
|
|
/// when it is the scope's natural one — the state the selectors and the drill-downs build on.
|
|
/// </summary>
|
|
public AnalysisQuery Shown(AnalysisQuery query)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(query);
|
|
|
|
return query.WithScope(Scope).WithMetric(Metric == NaturalMetric ? null : Metric);
|
|
}
|
|
|
|
/// <summary>Reads <paramref name="query"/> against <paramref name="options"/>.</summary>
|
|
public static AnalysisSelection Resolve(AnalysisQuery query, AnalysisPageOptions options)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(query);
|
|
ArgumentNullException.ThrowIfNull(options);
|
|
|
|
return query.Scope.Kind switch
|
|
{
|
|
QueryScopeKind.EnergyType => ForType(query, options),
|
|
QueryScopeKind.Category => ForCategory(query, options),
|
|
QueryScopeKind.Meter => ForMeter(query, options),
|
|
QueryScopeKind.Meters => ForMeters(query, options),
|
|
_ => ForPortfolio(query, options),
|
|
};
|
|
}
|
|
|
|
/// <summary>The metric a scope's natural choice is: consumption when offered, else the first quantity, else the cost.</summary>
|
|
private static AnalysisMetric NaturalOf(IReadOnlyList<AnalysisMetric> quantities) =>
|
|
quantities.Contains(AnalysisMetric.Consumption) ? AnalysisMetric.Consumption : quantities.Count > 0 ? quantities[0] : AnalysisMetric.Cost;
|
|
|
|
private static AnalysisSelection ForPortfolio(AnalysisQuery query, AnalysisPageOptions options)
|
|
{
|
|
var quantities = options.Types.SelectMany(t => t.QuantityMetrics).ToHashSet();
|
|
List<AnalysisMetric> metrics = [AnalysisMetric.Cost, .. AnalysisPageOptions.QuantityOrder.Where(quantities.Contains)];
|
|
return WithMetric(new AnalysisSelection(QueryScope.Portfolio, null) { Metrics = metrics, NaturalMetric = AnalysisMetric.Cost }, query.Metric);
|
|
}
|
|
|
|
private static AnalysisSelection ForType(AnalysisQuery query, AnalysisPageOptions options)
|
|
{
|
|
if (options.Type(query.Scope.Id) is not { } type)
|
|
{
|
|
return Refused(query.Scope, AnalysisPageRefusal.UnknownScope);
|
|
}
|
|
|
|
List<AnalysisMetric> metrics = [.. type.QuantityMetrics, AnalysisMetric.Cost];
|
|
var selection = new AnalysisSelection(query.Scope, null)
|
|
{
|
|
Metrics = metrics,
|
|
NaturalMetric = NaturalOf(type.QuantityMetrics),
|
|
ScopeName = type.Name,
|
|
EnergyTypeId = type.Id,
|
|
};
|
|
return WithMetric(selection, query.Metric);
|
|
}
|
|
|
|
private static AnalysisSelection ForCategory(AnalysisQuery query, AnalysisPageOptions options)
|
|
{
|
|
if (options.Category(query.Scope.Id) is not { } category)
|
|
{
|
|
return Refused(query.Scope, AnalysisPageRefusal.UnknownScope);
|
|
}
|
|
|
|
var members = category.MeterIds.Select(id => options.Meter(id)).OfType<AnalysisPageMeter>().ToList();
|
|
var groups = GroupsOf(members);
|
|
|
|
// A quantity only when every meter measures one kind in one unit (brief §7.4).
|
|
var single = groups.Count == 1 && groups[0].Metric is { } only ? only : (AnalysisMetric?)null;
|
|
List<AnalysisMetric> metrics = single is { } metric ? [AnalysisMetric.Cost, metric] : [AnalysisMetric.Cost];
|
|
var selection = new AnalysisSelection(query.Scope, AnalysisMetric.Cost)
|
|
{
|
|
Metrics = metrics,
|
|
NaturalMetric = AnalysisMetric.Cost,
|
|
ScopeName = category.Name,
|
|
Groups = groups,
|
|
};
|
|
|
|
if (query.Metric is not { } requested || requested == AnalysisMetric.Cost)
|
|
{
|
|
return selection;
|
|
}
|
|
|
|
if (!requested.IsQuantity() || (single is { } supported && supported != requested))
|
|
{
|
|
// A metric its meters do not measure (or the tank balance): the cost, with a notice.
|
|
return selection with { Notices = [new AnalysisPageNotice(AnalysisPageNoticeKind.MetricNotAvailable, requested, AnalysisMetric.Cost)] };
|
|
}
|
|
|
|
// The quantity asked for cannot be one: explained, never silently shown as the cost.
|
|
var refusal = members.Count == 0 ? AnalysisPageRefusal.CategoryWithoutMeters
|
|
: single is null ? AnalysisPageRefusal.CategoryMixed
|
|
: members.Count > AnalysisLimits.MaxSeries ? AnalysisPageRefusal.CategoryTooManyMeters
|
|
: AnalysisPageRefusal.None;
|
|
|
|
return selection with
|
|
{
|
|
Metric = requested,
|
|
SeriesMeterIds = refusal == AnalysisPageRefusal.None ? [.. members.Select(m => m.Id)] : [],
|
|
Refusal = refusal,
|
|
};
|
|
}
|
|
|
|
private static AnalysisSelection ForMeter(AnalysisQuery query, AnalysisPageOptions options)
|
|
{
|
|
if (options.Meter(query.Scope.Id) is not { } meter)
|
|
{
|
|
return Refused(query.Scope, AnalysisPageRefusal.UnknownScope);
|
|
}
|
|
|
|
List<AnalysisMetric> metrics = [];
|
|
if (meter.Metric is { } own)
|
|
{
|
|
metrics.Add(own);
|
|
}
|
|
|
|
if (meter.IsCostable)
|
|
{
|
|
metrics.Add(AnalysisMetric.Cost);
|
|
}
|
|
|
|
var selection = new AnalysisSelection(query.Scope, null)
|
|
{
|
|
Metrics = metrics,
|
|
NaturalMetric = meter.Metric,
|
|
SeriesMeterIds = [meter.Id],
|
|
ScopeName = meter.Name,
|
|
EnergyTypeId = meter.EnergyTypeId,
|
|
};
|
|
return WithMetric(selection, query.Metric);
|
|
}
|
|
|
|
private static AnalysisSelection ForMeters(AnalysisQuery query, AnalysisPageOptions options)
|
|
{
|
|
var requested = query.Scope.MeterIds;
|
|
if (requested.Count > AnalysisLimits.MaxSeries)
|
|
{
|
|
return Refused(query.Scope, AnalysisPageRefusal.TooManyMeters);
|
|
}
|
|
|
|
var meters = requested.Select(id => options.Meter(id)).OfType<AnalysisPageMeter>().ToList();
|
|
if (meters.Count == 0)
|
|
{
|
|
return Refused(query.Scope, AnalysisPageRefusal.UnknownScope);
|
|
}
|
|
|
|
List<AnalysisPageNotice> notices = meters.Count < requested.Count ? [new AnalysisPageNotice(AnalysisPageNoticeKind.UnknownMetersLeftOut)] : [];
|
|
var scope = QueryScope.ForMeters(meters.Select(m => m.Id));
|
|
|
|
List<AnalysisMetric> metrics =
|
|
[
|
|
.. meters.Select(m => m.Metric).OfType<AnalysisMetric>().Distinct().OrderBy(IndexOf),
|
|
];
|
|
if (meters.Any(m => m.IsCostable))
|
|
{
|
|
metrics.Add(AnalysisMetric.Cost);
|
|
}
|
|
|
|
var selection = WithMetric(
|
|
new AnalysisSelection(scope, null) { Metrics = metrics, NaturalMetric = meters[0].Metric, Notices = notices },
|
|
query.Metric);
|
|
|
|
// A meter measures what it measures: the metric picks which of the selected meters are compared.
|
|
var shown = selection.IsCost
|
|
? meters.Where(m => m.IsCostable).ToList()
|
|
: meters.Where(m => m.Metric == selection.Metric).ToList();
|
|
return selection with
|
|
{
|
|
SeriesMeterIds = [.. shown.Select(m => m.Id)],
|
|
HiddenMeterIds = [.. meters.Except(shown).Select(m => m.Id)],
|
|
};
|
|
}
|
|
|
|
/// <summary>The metric shown for a requested one: the request when supported, else the natural metric with a notice.</summary>
|
|
private static AnalysisSelection WithMetric(AnalysisSelection selection, AnalysisMetric? requested)
|
|
{
|
|
if (requested is not { } metric || metric == selection.NaturalMetric)
|
|
{
|
|
return selection with { Metric = selection.NaturalMetric };
|
|
}
|
|
|
|
if (selection.Metrics.Contains(metric))
|
|
{
|
|
return selection with { Metric = metric };
|
|
}
|
|
|
|
return selection with
|
|
{
|
|
Metric = selection.NaturalMetric,
|
|
Notices = [.. selection.Notices, new AnalysisPageNotice(AnalysisPageNoticeKind.MetricNotAvailable, metric, selection.NaturalMetric)],
|
|
};
|
|
}
|
|
|
|
private static AnalysisSelection Refused(QueryScope scope, AnalysisPageRefusal refusal) =>
|
|
new(scope, null) { Refusal = refusal };
|
|
|
|
private static List<AnalysisMeterGroup> GroupsOf(IEnumerable<AnalysisPageMeter> meters) =>
|
|
[
|
|
.. meters
|
|
.GroupBy(m => (m.Kind, Unit: Units.Normalize(m.Unit)))
|
|
.Select(g => new AnalysisMeterGroup(g.Key.Kind, g.Key.Unit, [.. g.Select(m => m.Id)])),
|
|
];
|
|
|
|
private static int IndexOf(AnalysisMetric metric)
|
|
{
|
|
var index = AnalysisPageOptions.QuantityOrder.ToList().IndexOf(metric);
|
|
return index < 0 ? int.MaxValue : index;
|
|
}
|
|
}
|