A bundle of related portal work — picked up while ensuring per-customer
isolation actually works end-to-end and replacing the placeholder Client
landing page. Build green, full test suite 66/66.
Frontend — Client surface
- DashboardPage: replace placeholder with 4 KPI cards (kWh, current kW,
active devices, estimated cost), 24h active-power ECharts mini-chart,
per-device "today/range" table, and a date-range picker with shortcuts
(Today / 7d / 30d / This month / Custom). 30s auto-refresh.
- New Measurements page (/measurements, Client mode, any authenticated
user) with multi-select device filter, full date range incl. an
"All time" shortcut, server-paginated preview, and Excel export.
- "Export to Excel" buttons on: Client Dashboard summary, Client Dashboard
raw measurements, Admin fleet dashboard, Admin customer-detail Cost tab.
- DashboardsPage sidebar items: let the menu item grow and reset
line-height so the two-line title+description doesn't crush.
Frontend — Admin / user mgmt
- RestrictedAdmin role: admin who only sees their assigned customers.
New UserFormDrawer choice + CustomerAccessModal for granting/revoking
per-customer access; surfaced from the Users page.
Backend
- ClosedXML 0.104.2 + ExcelExportService (pure formatter; frozen header,
currency/kWh/kW/date number formats, AdjustToContents).
- DashboardSummaryService computes per-device totals + estimated cost
(hourly bucketing × site's municipality's active tariff, mirroring
FleetCostService for the Admin side).
- New endpoints:
GET /api/dashboard/summary[+/export.xlsx]
GET /api/measurements/raw[+/export.xlsx] (deviceIds, paginated)
GET /api/sites/devices (flat list w/ site name)
GET /api/fleet/dashboard/export.xlsx
GET /api/fleet/customers/{id}/cost/export.xlsx
GET /api/auth/check (cookie-only liveness)
- AdminCustomerAccess: per-user customer scoping for RestrictedAdmin via
Postgres-row-level filter — RlsContext (per-DI-scope state) +
CustomerFilterMiddleware (populates from claims after auth) +
fleet.* DbSets gain HasQueryFilter expressions. Bootstrappers
Elevate() to bypass the filter for trusted system code.
- Migration: 20260518095759_AddAdminCustomerAccess (mapping table,
composite PK on UserId+CustomerId).
Infra / templating (the "spin it up via the template" piece)
- docker-compose.prod.yml + docker-compose.yml: pass WhiteLabel__*,
Application__RunMode, FleetIngest__* through to the container as
${VAR:-default} substitutions. Previously these were silently dropped
in prod — a customer's .env settings for branding/fleet-push never
reached the running process. Latent bug, fixed.
- docker-compose.prod.yml: forwardAuth middleware labels on the
Grafana router pointing at /api/auth/check. Option (a) from the
README's three prod-auth modes — every Grafana request now gates on
a valid portal cookie. Anonymous stays off.
- .env.example rewritten with a Client section, optional FleetIngest
block, and an Admin variant block — annotated on what's required vs.
optional and where the seed-only-on-first-boot caveat applies.
- README "Grafana embedding" table: option (a) now marked active with
an inline note on how to switch modes later.
- OPERATIONS.md step 3 includes the white-label pre-brand .env snippet;
step 4 (formerly "decide Grafana auth mode") updated to reflect
that auth is wired by default.
Tests
- New BrandingSeedFromOptionsTests (5 tests) pins the env-var → IOptions
→ DB seed contract: first read seeds from options; subsequent reads
return the DB row (UI edits survive restarts); EnsureSeededAsync is
idempotent; UpdateAsync falls back to options for blanked fields.
- CustomerTokenGraceTests helper: pass the new RlsContext to
AdminDbContext (SetAll() so existing semantics hold).
Verified end-to-end
- Real Docker spin-up with WhiteLabel__* in a throwaway .env →
/api/branding returned all six fields verbatim (ApplicationName,
LogoUrl, three colors, FooterText).
- curl login → /api/dashboard/summary returned valid JSON →
/api/dashboard/summary/export.xlsx returned a 6.9 KB file the
`file` command identifies as "Microsoft Excel 2007+".
- /api/measurements/raw with and without deviceIds filter returned
correct paginated rows; /export.xlsx with filter produced a valid
7.1 KB xlsx with the meter count in the filename.
- Frontend tsc -b clean; backend dotnet build 0/0; xunit 66/66.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
109 lines
4.5 KiB
C#
109 lines
4.5 KiB
C#
using Tau.Acuvim.Portal.Constants;
|
|
using Tau.Acuvim.Portal.DTOs;
|
|
using Tau.Acuvim.Portal.Services;
|
|
|
|
namespace Tau.Acuvim.Portal.Endpoints;
|
|
|
|
public static class MeasurementsEndpoints
|
|
{
|
|
private const string XlsxContentType =
|
|
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
|
|
|
public static IEndpointRouteBuilder MapMeasurementsEndpoints(this IEndpointRouteBuilder app)
|
|
{
|
|
var read = app.MapGroup("/api/measurements")
|
|
.RequireAuthorization()
|
|
.WithTags("Measurements");
|
|
|
|
read.MapGet("/", async (
|
|
Guid deviceId, DateTime from, DateTime to, string bucket,
|
|
MeasurementQueryService svc, CancellationToken ct) =>
|
|
{
|
|
if (!svc.IsValidBucket(bucket))
|
|
{
|
|
return Results.BadRequest(new { error = "bucket must be one of: minute, 5min, 15min, hour, day." });
|
|
}
|
|
if (to <= from) return Results.BadRequest(new { error = "'to' must be after 'from'." });
|
|
var rows = await svc.GetBucketsAsync(deviceId, from, to, bucket, ct);
|
|
return Results.Ok(rows);
|
|
});
|
|
|
|
// Raw measurement list (Measurements page). Optional comma-separated
|
|
// deviceIds. Paginated; preview-friendly limits.
|
|
read.MapGet("/raw", async (
|
|
DateTime from, DateTime to,
|
|
string? deviceIds, int? limit, int? offset,
|
|
DashboardSummaryService svc, CancellationToken ct) =>
|
|
{
|
|
if (to <= from) return Results.BadRequest(new { error = "'to' must be after 'from'." });
|
|
if (!TryParseDeviceIds(deviceIds, out var ids, out var parseError))
|
|
{
|
|
return Results.BadRequest(new { error = parseError });
|
|
}
|
|
var resolvedLimit = limit is > 0 and <= 1000 ? limit.Value : 200;
|
|
var resolvedOffset = offset is > 0 ? offset.Value : 0;
|
|
var rows = await svc.ReadRawAsync(from, to, ids, resolvedLimit, resolvedOffset, ct);
|
|
var total = await svc.CountRawAsync(from, to, ids, ct);
|
|
return Results.Ok(new RawMeasurementsPage(total, resolvedLimit, resolvedOffset, rows));
|
|
});
|
|
|
|
// Raw measurement export. Same filters as /raw but no pagination — capped
|
|
// at 250 000 rows for memory safety.
|
|
read.MapGet("/raw/export.xlsx", async (
|
|
DateTime from, DateTime to,
|
|
string? deviceIds, int? rowCap,
|
|
DashboardSummaryService svc, ExcelExportService excel, CancellationToken ct) =>
|
|
{
|
|
if (to <= from) return Results.BadRequest(new { error = "'to' must be after 'from'." });
|
|
if (!TryParseDeviceIds(deviceIds, out var ids, out var parseError))
|
|
{
|
|
return Results.BadRequest(new { error = parseError });
|
|
}
|
|
var cap = rowCap is > 0 and <= 250_000 ? rowCap.Value : 100_000;
|
|
var rows = await svc.ReadRawAsync(from, to, ids, cap, offset: 0, ct);
|
|
var bytes = excel.BuildRawMeasurements(rows, from, to);
|
|
var meterSuffix = ids is { Count: 1 } ? "-1meter" : ids is { Count: > 1 } ? $"-{ids.Count}meters" : "";
|
|
var filename = $"measurements{meterSuffix}-{from:yyyyMMdd}-{to:yyyyMMdd}.xlsx";
|
|
return Results.File(bytes, XlsxContentType, filename);
|
|
});
|
|
|
|
var ingest = app.MapGroup("/api/ingest")
|
|
.RequireAuthorization(Policies.AdminOnly)
|
|
.WithTags("Ingest");
|
|
|
|
ingest.MapPost("/measurements", async (
|
|
MeasurementIngestRow[] rows, MeasurementIngestService svc, CancellationToken ct) =>
|
|
{
|
|
if (rows is null || rows.Length == 0)
|
|
{
|
|
return Results.BadRequest(new { error = "At least one row required." });
|
|
}
|
|
var result = await svc.IngestAsync(rows, ct);
|
|
return Results.Ok(result);
|
|
});
|
|
|
|
return app;
|
|
}
|
|
|
|
private static bool TryParseDeviceIds(string? raw, out List<Guid>? ids, out string? error)
|
|
{
|
|
ids = null;
|
|
error = null;
|
|
if (string.IsNullOrWhiteSpace(raw)) return true;
|
|
|
|
var parts = raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
|
var parsed = new List<Guid>(parts.Length);
|
|
foreach (var p in parts)
|
|
{
|
|
if (!Guid.TryParse(p, out var g))
|
|
{
|
|
error = $"deviceIds contains an invalid GUID: '{p}'.";
|
|
return false;
|
|
}
|
|
parsed.Add(g);
|
|
}
|
|
ids = parsed;
|
|
return true;
|
|
}
|
|
}
|