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.
141 lines
6.2 KiB
C#
141 lines
6.2 KiB
C#
using System.Globalization;
|
|
using System.Text;
|
|
|
|
namespace MeterVault.App.Analysis;
|
|
|
|
/// <summary>
|
|
/// One row of the analysis CSV (D-55): one series in one bucket.
|
|
/// </summary>
|
|
/// <param name="SeriesId">The stable series identity (<c>m12</c>, <c>t3:use:kWh</c>, <c>portfolio</c>, <c>c4</c>).</param>
|
|
/// <param name="SeriesName">The series' name: a meter's, a type's or a category's (user data), or a worded measure.</param>
|
|
/// <param name="Kind">What the value measures, as its invariant identifier (<c>Consumption</c>, <c>Cost</c>).</param>
|
|
/// <param name="Unit">The value's unit (normalized, D-20), or the currency code for a cost series.</param>
|
|
/// <param name="BucketStart">The bucket's first instant, in the instance zone's local time with its offset.</param>
|
|
/// <param name="BucketEnd">The bucket's end (exclusive): the next local midnight, or now for a bucket cut at now.</param>
|
|
/// <param name="TimeZone">The instance zone id the bounds are local to.</param>
|
|
/// <param name="Value">The value; null when it is unavailable (missing, unresolved, invalid, being prepared).</param>
|
|
/// <param name="Status">The value's availability (<c>Available</c>, <c>Partial</c>, …).</param>
|
|
/// <param name="Provenance">Where the value comes from, as flag identifiers joined by <c>|</c> (<c>Measured|Estimated</c>); empty when none.</param>
|
|
/// <param name="Cost">The cost in the bucket; null when not priced or not costed.</param>
|
|
/// <param name="CostStatus">The cost's price coverage (<c>Priced</c>, <c>NotPriced</c>, …); null when the series has no cost.</param>
|
|
/// <param name="Currency">The currency of <paramref name="Cost"/>; null when the series has no cost.</param>
|
|
/// <param name="ComparisonValue">The value in the paired comparison bucket (D-06); null without a comparison or when unavailable.</param>
|
|
public sealed record AnalysisCsvRow(
|
|
string SeriesId,
|
|
string SeriesName,
|
|
string Kind,
|
|
string Unit,
|
|
DateTimeOffset BucketStart,
|
|
DateTimeOffset BucketEnd,
|
|
string TimeZone,
|
|
double? Value,
|
|
string Status,
|
|
string Provenance,
|
|
double? Cost,
|
|
string? CostStatus,
|
|
string? Currency,
|
|
double? ComparisonValue);
|
|
|
|
/// <summary>
|
|
/// Writes the analysis table as CSV (D-55): RFC 4180 quoting, a header of invariant column names, invariant numbers at
|
|
/// full precision, ISO-8601 local bucket bounds with their offset, and empty cells for unavailable values — a spreadsheet
|
|
/// or a script reads the same figures the page shows, never a fabricated zero.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Names and units are user data. A cell that starts with <c>=</c>, <c>+</c>, <c>-</c>, <c>@</c> or a control character
|
|
/// is prefixed with an apostrophe, so a spreadsheet shows it as text instead of running it as a formula; numbers are
|
|
/// written by this class and never need it.
|
|
/// </remarks>
|
|
public static class AnalysisCsvWriter
|
|
{
|
|
/// <summary>The header, in column order.</summary>
|
|
public static IReadOnlyList<string> Columns { get; } =
|
|
[
|
|
"series_id", "series_name", "kind", "unit", "bucket_start", "bucket_end", "timezone",
|
|
"value", "status", "provenance", "cost", "cost_status", "currency", "comparison_value",
|
|
];
|
|
|
|
private const string InstantFormat = "yyyy-MM-dd'T'HH:mm:sszzz";
|
|
|
|
/// <summary>Writes the header and one line per row.</summary>
|
|
public static async Task WriteAsync(TextWriter writer, IEnumerable<AnalysisCsvRow> rows, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(writer);
|
|
ArgumentNullException.ThrowIfNull(rows);
|
|
|
|
await writer.WriteAsync(Line(Columns).AsMemory(), cancellationToken).ConfigureAwait(false);
|
|
foreach (var row in rows)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
await writer.WriteAsync(Line(Fields(row)).AsMemory(), cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>The whole CSV as a string (tests, small exports).</summary>
|
|
public static string Write(IEnumerable<AnalysisCsvRow> rows)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(rows);
|
|
|
|
var builder = new StringBuilder();
|
|
builder.Append(Line(Columns));
|
|
foreach (var row in rows)
|
|
{
|
|
builder.Append(Line(Fields(row)));
|
|
}
|
|
|
|
return builder.ToString();
|
|
}
|
|
|
|
/// <summary>One CSV field: quoted when it holds a comma, a quote or a line break, with quotes doubled.</summary>
|
|
public static string Escape(string? field)
|
|
{
|
|
if (string.IsNullOrEmpty(field))
|
|
{
|
|
return string.Empty;
|
|
}
|
|
|
|
var needsQuotes = field.AsSpan().IndexOfAny(",\"\r\n") >= 0;
|
|
return needsQuotes ? "\"" + field.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : field;
|
|
}
|
|
|
|
/// <summary>A number at full precision in invariant form; empty when unknown or not finite.</summary>
|
|
public static string Number(double? value) =>
|
|
value is { } number && double.IsFinite(number) ? number.ToString("R", CultureInfo.InvariantCulture) : string.Empty;
|
|
|
|
/// <summary>An instant as local ISO-8601 with its offset (<c>2026-09-01T00:00:00+02:00</c>).</summary>
|
|
public static string Instant(DateTimeOffset value) => value.ToString(InstantFormat, CultureInfo.InvariantCulture);
|
|
|
|
/// <summary>User text made safe to open in a spreadsheet: a leading formula character becomes literal text.</summary>
|
|
public static string Text(string? value)
|
|
{
|
|
if (string.IsNullOrEmpty(value))
|
|
{
|
|
return string.Empty;
|
|
}
|
|
|
|
return value[0] is '=' or '+' or '-' or '@' or '\t' or '\r' or '\n' ? "'" + value : value;
|
|
}
|
|
|
|
private static IEnumerable<string> Fields(AnalysisCsvRow row) =>
|
|
[
|
|
row.SeriesId,
|
|
Text(row.SeriesName),
|
|
row.Kind,
|
|
Text(row.Unit),
|
|
Instant(row.BucketStart),
|
|
Instant(row.BucketEnd),
|
|
row.TimeZone,
|
|
Number(row.Value),
|
|
row.Status,
|
|
row.Provenance,
|
|
Number(row.Cost),
|
|
row.CostStatus ?? string.Empty,
|
|
row.Currency ?? string.Empty,
|
|
Number(row.ComparisonValue),
|
|
];
|
|
|
|
private static string Line(IEnumerable<string> fields) => string.Join(',', fields.Select(Escape)) + "\r\n";
|
|
}
|