Skip to content

feat(api): historical vs flat-rate savings — /api/savings/daily - #279

Merged
frahlg merged 1 commit into
masterfrom
278-historical-savings-vs-flat
May 18, 2026
Merged

frahlg merged 1 commit into
masterfrom
278-historical-savings-vs-flat

Conversation

@frahlg

@frahlg frahlg commented May 18, 2026

Copy link
Copy Markdown
Member

Summary

  • New state.DailyCostBreakdown(sinceMs, untilMs, zone, exportPricing) integrates grid traffic across all three history tiers and joins it to the prices table for slot-weighted import cost + export revenue, plus the unweighted slot-mean prices the flat-rate baseline needs. Mirrors mpc.ComputeBaselines so a finished day's historical answer matches what the live plan badge said when that day was the plan.
  • New GET /api/savings/daily?days=N returns per-day import/export Wh, actual cost, flat cost, saved öre, and a totals block. Same immutable-past-day cache pattern as handleEnergyDaily. Empty days when cfg.Price.Zone is unset.
  • Slot lookup uses the midpoint of (prev_ts, ts_ms] so a sample on a slot boundary isn't off-by-one toward either side. Export pricing mirrors mpc.SlotExportPriceOre exactly: FlatOreKwh > 0 overrides; otherwise max(spot + bonus − fee, 0).

Test plan

  • go test ./internal/state/ -run TestDailyCostBreakdown — 4 cases: slot-weighted vs flat with timing win, export clamped at zero on negative spot, flat-export override path, empty range.
  • go test ./internal/api/ -run TestHandleSavings — 4 cases: nil state, unconfigured zone, end-to-end with seeded prices+history, days clamping.
  • make test — all packages green.
  • make e2e — full-stack green.

Closes #278.

Field testers asked whether they can see how much the system has saved
historically — the plan view's "vs flat avg price" badge already does this
forward-looking via mpc.ComputeBaselines, but disappears as time passes.

state.DailyCostBreakdown joins history_{hot,warm,cold} with the prices
table (kept indefinitely, no rolloff) and returns slot-weighted import
cost, export revenue, and the unweighted slot-mean prices the flat-rate
baseline needs. Price for each integration step is the slot whose
[slot_ts_ms, slot_ts_ms+len) window contains the midpoint of the
interval — using the midpoint instead of either edge keeps the result
stable across slot boundaries (no off-by-one based on which side a
sample lands on). Export pricing mirrors mpc.SlotExportPriceOre exactly
(flat override → spot+bonus−fee clamped at zero) so a finished day's
historical answer matches what the live plan badge said when that day
was the plan.

/api/savings/daily wraps it with the same immutable-past-day cache
pattern handleEnergyDaily uses. Lives in its own api_savings.go per
internal/api/CLAUDE.md's "one file per feature cluster" rule. Returns
empty days when cfg.Price.Zone is unset — no zone means no baseline to
compare against.

Closes #278.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d17c330d5c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread go/internal/state/cost.go
END
), 0)
FROM prices
WHERE zone = ? AND slot_ts_ms BETWEEN ? AND ?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use half-open slot range for flat-price averages

The flat-rate baseline query currently uses slot_ts_ms BETWEEN ? AND ?, which includes a slot that starts exactly at untilMs. For the API’s daily path, untilMs for past days is next midnight, so this pulls in the first slot of the following day and biases AvgImportOreKwh / AvgExportOreKwh, which then skews flat_cost_ore and saved_ore on otherwise complete days. This happens with normal hourly price data because there is always a slot at day boundaries; the range should be treated as half-open (>= sinceMs and < untilMs) to match the integration window.

Useful? React with 👍 / 👎.

@frahlg
frahlg merged commit 7b3e20a into master May 18, 2026
1 check passed
@frahlg
frahlg deleted the 278-historical-savings-vs-flat branch May 18, 2026 13:55
frahlg added a commit that referenced this pull request May 18, 2026
Mounts above the controls row on the main dashboard. Self-contained
web component: own Week/Month toggle (same pill shape ftw-history-card
uses, single shared accent), own fetch loop against /api/savings/daily,
own paint cycle. No external JS wiring.

Headline is a mono tabular SEK total with sign + percentage, color
flipped per sign via a CSS custom property so re-paint on each poll
tick doesn't restyle the world. Sparkline is inline SVG — diverging
bars on a hairline zero baseline (green above, red below), the same
gestalt the plan view's "vs flat avg price" badge uses but extended
along the time axis.

Three terminal states:
  - empty       : /api/savings/daily returned []  (no price.zone)
  - awaiting    : every day comes back resolution=no_prices
                  (zone set, price provider hasn't filled yet)
  - ready       : at least one day has real prices → render normally

The "awaiting" state matters on a fresh dev system — the API otherwise
returns 7 zeroed days, and a flat sparkline at zero would look like a
silent failure rather than the legitimate "no data yet" it is.

Closes #280. Depends on #279 (server-side endpoint).
frahlg added a commit that referenced this pull request May 18, 2026
Mounts above the controls row on the main dashboard. Self-contained
web component: own Week/Month toggle (same pill shape ftw-history-card
uses, single shared accent), own fetch loop against /api/savings/daily,
own paint cycle. No external JS wiring.

Headline is a mono tabular SEK total with sign + percentage, color
flipped per sign via a CSS custom property so re-paint on each poll
tick doesn't restyle the world. Sparkline is inline SVG — diverging
bars on a hairline zero baseline (green above, red below), the same
gestalt the plan view's "vs flat avg price" badge uses but extended
along the time axis.

Three terminal states:
  - empty       : /api/savings/daily returned []  (no price.zone)
  - awaiting    : every day comes back resolution=no_prices
                  (zone set, price provider hasn't filled yet)
  - ready       : at least one day has real prices → render normally

The "awaiting" state matters on a fresh dev system — the API otherwise
returns 7 zeroed days, and a flat sparkline at zero would look like a
silent failure rather than the legitimate "no data yet" it is.

Closes #280. Depends on #279 (server-side endpoint).
frahlg added a commit that referenced this pull request Nov 25, 2026
Move the pin to srcfl/device-drivers@28c771fd (#279). zaptec_cloud 0.3.0
uses host.set_command_timeout_s and driver_release from this PR. The pin
also carries the easee_cloud fixes merged since e7b94b11 (#183, #227, #194,
#236, #200), whose Core side (#2050, #2062) is already on master.

Tell the stopped instance's default apart from a replacement's startup
default in TestOtherStopsKeepTheSafeDefault (review finding).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
frahlg added a commit that referenced this pull request Nov 25, 2026
…val (#2079)

* fix(drivers): give slow cloud drivers time, hand devices back on removal

A Zaptec Cloud command that took longer than 5 s failed, and the safe
default then paused the charger at 0 A. A driver can now ask for up to
30 s per call with host.set_command_timeout_s; the control tick still waits
only its short deadline and the call finishes in the driver's queue.

Removing or disabling a driver calls its optional driver_release instead of
driver_default_mode, so a charger goes back to the owner's own current
rather than staying at FTW's 0 A. Restarts, shutdown and stale readings
keep the safe default.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(drivers): bundle zaptec_cloud 0.3.0 and easee_cloud 1.5.0

Move the pin to srcfl/device-drivers@28c771fd (#279). zaptec_cloud 0.3.0
uses host.set_command_timeout_s and driver_release from this PR. The pin
also carries the easee_cloud fixes merged since e7b94b11 (#183, #227, #194,
#236, #200), whose Core side (#2050, #2062) is already on master.

Tell the stopped instance's default apart from a replacement's startup
default in TestOtherStopsKeepTheSafeDefault (review finding).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Historical savings: vs flat-rate, computed per day from prices + history

1 participant