Files
cantabile-ha-addons/src/edge/cantabile_edge/costs.py
T

597 lines
32 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The household's own energy costs on the box (docs/methods.md A12; the
owner, 2026-11-05: a tenant/inhabitant-facing "My energy costs" view on the
box's own Home Assistant dashboard; the console is staff-only).
Only the household's own figures: its meter, the prices of its own tariff
bundle and its own plan. Never the building operator's margin, other flats
or building totals (the box has none of them: the bundle carries only this
site's prices).
What is kept (<state dir>/costs.db, SQLite; survives restarts):
slots per quarter-hour and carrier (electricity, gas, heat): the metered
kWh (from the agent's own 1-minute windows: a counter's delta,
else a power's mean), what they cost at the price that applied
(the tariff bundle in force at the minute), the kWh without a
price, the same kWh at the own supplier's price, the kWh, cost and
own-supplier cost of slots priced by a building's or community's
offer (Mieterstrom, GGV, §42c), and the plan's estimate for the
slot (optimizer.step_costs: with and without the plan, the same
prices) as saved (mode auto, a billed price) or would-have-saved
(shadow, advisory, or an unbilled tenant price). 400 days.
months the same sums per local month (the site's time zone): the
monthly accumulators, plus the fixed charges per month the bundle
said (when it carries them).
prices per quarter-hour the import price, the own supplier's and whether
the offer priced it, as the bundle said (today's past hours after
the bundle has moved on). 3 days.
Nothing here is ever sent anywhere: it is shown in HA only (announce.py,
dashboards.py). Missing data is never a 0: each figure is None with the
reason in report()["gaps"] (the dashboard's alarm box)."""
from __future__ import annotations
import html
import logging
import math
import os
import sqlite3
import threading
import time
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from . import names
from .devprofiles import part_of
log = logging.getLogger(__name__)
SLOT_S = 900
KEEP_DAYS = 400 # slots: this month and last, and a year back for a later view
KEEP_PRICE_DAYS = 3
CARRIERS = ("electricity", "gas", "heat", "oil")
# the meters the costs are read from: carrier, kind (a part, grid.1.import_energy, counts as its quantity)
ASSETS = {"grid.import_energy": ("electricity", "counter"), "grid.import_power": ("electricity", "gauge"),
"grid.power": ("electricity", "gauge"), # signed (import +): its positive part
"gas.energy": ("gas", "counter"), "heat.energy": ("heat", "counter"),
# a boiler's own gas counter (simulated boilers map it; before 2026-11-08 not booked)
"boiler.gas_energy": ("gas", "counter"),
# heating oil (methods.md E15): kWh (Hi) where the device reports energy, else its oil meter's
# litres × the Parameters row de.heizoel_kwh_per_l (the tariff bundle's params)
"oil.energy": ("oil", "counter"), "oil.volume": ("oil", "litres"),
"boiler.oil_energy": ("oil", "counter"), "boiler.oil_volume": ("oil", "litres")}
OIL_KWH_PER_L = "de.heizoel_kwh_per_l"
PREFER = ("grid.import_energy", "grid.import_power", "grid.power") # electricity: the counter first
# gas and oil: the house's meter before the boiler's own (one of them, never both: the same fuel)
PREFER_FUEL = ("gas.energy", "boiler.gas_energy", "oil.energy", "oil.volume", "boiler.oil_energy", "boiler.oil_volume")
PARAM_FORECAST = "costs.forecast_days" # the Parameters page (fleet), in the tariff bundle's params
FORECAST_DAYS = (1, 62) # the parameter's valid range
REPORT_EVERY_S = 60 # HA's figures made again at most this often (announce.py)
COLS = ("kwh", "cost_eur", "unpriced_kwh", "own_eur", "offer_kwh", "offer_eur", "offer_own_eur",
"plan_eur", "base_eur", "saved_eur", "would_eur", "plan_slots", "minutes")
def quantity(asset: str) -> str:
p = part_of(asset)
return p[0] if p else asset
def wanted(asset: str) -> bool:
return quantity(asset) in ASSETS
def meters_of(mapping) -> dict[str, bool]:
"""Per carrier whether the mapping has a meter for it."""
out = {c: False for c in CARRIERS}
for a in mapping.assets:
q = quantity(a.asset)
if q in ASSETS:
out[ASSETS[q][0]] = True
return out
def _finite(v) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
def amounts(records: list[dict], span_s: float, oil_kwh_per_l: float | None = None) -> dict[str, float | None]:
"""A closed window's kWh per carrier from the cost aggregator's records
(telemetry.Aggregator): the counters' deltas (Wh) where the carrier has
a counter that has a reading, else its power's mean (W) over the
window; None: no meter value for the carrier in this window. Parts
(two meters) add up."""
by: dict[str, dict[str, list]] = {}
for r in records:
q = quantity(r.get("asset", ""))
if q not in ASSETS:
continue
carrier, kind = ASSETS[q]
if kind == "counter":
v = r.get("delta") if r.get("last") is not None else None
v = v / 1000.0 if _finite(v) else None
elif kind == "litres":
# litres of oil: kWh only with the conversion row (none: no value, never litres as kWh)
v = r.get("delta") if r.get("last") is not None else None
v = v * oil_kwh_per_l if _finite(v) and _finite(oil_kwh_per_l) and oil_kwh_per_l > 0 else None
else:
m = r.get("mean")
v = (max(m, 0.0) if q == "grid.power" else m) * span_s / 3600.0 / 1000.0 if _finite(m) else None
by.setdefault(carrier, {}).setdefault(q, []).append(v)
out = {}
for carrier, qs in by.items():
order = [q for q in PREFER if q in qs] if carrier == "electricity" else \
[q for q in PREFER_FUEL if q in qs] + [q for q in qs if q not in PREFER_FUEL]
got = None
for q in order:
vals = qs[q]
if vals and all(v is not None for v in vals):
got = sum(vals)
break
out[carrier] = got
return out
class Ledger:
"""The household's costs. bundles: the agent's tariff bundle reader
(bundles.Bundles); mode: the control mode now (None: no planner on this
box); tz: the site's time zone now (HA's)."""
def __init__(self, state_dir: str, bundles, mode=lambda: None, tz=lambda: "UTC", clock=time.time):
self.bundles, self.mode, self.tz, self.clock = bundles, mode, tz, clock
self.lock = threading.Lock()
self.path = os.path.join(state_dir, "costs.db")
self.db = sqlite3.connect(self.path, isolation_level=None, check_same_thread=False)
self.db.execute("PRAGMA journal_mode=WAL")
self.db.execute("PRAGMA synchronous=NORMAL")
cols = ", ".join(f"{c} REAL NOT NULL DEFAULT 0" for c in COLS)
self.db.execute(f"CREATE TABLE IF NOT EXISTS slots (slot INTEGER NOT NULL, carrier TEXT NOT NULL, {cols}, "
"billed INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (slot, carrier)) WITHOUT ROWID")
self.db.execute(f"CREATE TABLE IF NOT EXISTS months (month TEXT NOT NULL, carrier TEXT NOT NULL, {cols}, "
"fixed_eur REAL, fixed_incomplete INTEGER NOT NULL DEFAULT 0, unbilled_kwh REAL NOT NULL DEFAULT 0, "
"PRIMARY KEY (month, carrier)) WITHOUT ROWID")
self.db.execute("CREATE TABLE IF NOT EXISTS prices (slot INTEGER PRIMARY KEY, price_ct REAL, own_ct REAL, "
"offer INTEGER NOT NULL DEFAULT 0) WITHOUT ROWID")
self.pending: dict[int, dict] = {} # slot -> the latest plan's estimate for it (step 0)
self._booked = 0 # the last slot whose plan estimate is booked
self.outlook: dict | None = None # the last plan's heat outlook: carrier, eur, input_kwh, hours
def close(self):
with self.lock:
self.db.close()
# -- time -------------------------------------------------------------------
def zone(self) -> ZoneInfo:
try:
return ZoneInfo(self.tz() or "UTC")
except Exception: # an unknown zone: UTC, said in the report
return ZoneInfo("UTC")
def month_of(self, ts: float) -> str:
return datetime.fromtimestamp(ts, timezone.utc).astimezone(self.zone()).strftime("%Y-%m")
def month_bounds(self, ts: float) -> tuple[int, int]:
d = datetime.fromtimestamp(ts, timezone.utc).astimezone(self.zone())
a = d.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
b = (a + timedelta(days=32)).replace(day=1)
# a new datetime at midnight in the zone (DST: the offset of that day)
a = datetime(a.year, a.month, 1, tzinfo=self.zone())
b = datetime(b.year, b.month, 1, tzinfo=self.zone())
return int(a.timestamp()), int(b.timestamp())
# -- writing ----------------------------------------------------------------
def _add(self, slot: int, carrier: str, vals: dict, billed: bool | None = None, month_extra: dict | None = None):
keys = [k for k in COLS if k in vals]
month = self.month_of(slot)
if keys:
sets = ", ".join(f"{k} = {k} + excluded.{k}" for k in keys)
q = ", ".join("?" for _ in keys)
self.db.execute(f"INSERT INTO slots (slot, carrier, {', '.join(keys)}{', billed' if billed is not None else ''}) "
f"VALUES (?, ?, {q}{', ?' if billed is not None else ''}) ON CONFLICT (slot, carrier) DO UPDATE SET "
f"{sets}{', billed = excluded.billed' if billed is not None else ''}",
[slot, carrier] + [vals[k] for k in keys] + ([int(billed)] if billed is not None else []))
self.db.execute(f"INSERT INTO months (month, carrier, {', '.join(keys)}) VALUES (?, ?, {q}) "
f"ON CONFLICT (month, carrier) DO UPDATE SET {sets}", [month, carrier] + [vals[k] for k in keys])
for k, v in (month_extra or {}).items():
self.db.execute("INSERT INTO months (month, carrier) VALUES (?, ?) ON CONFLICT DO NOTHING", (month, carrier))
if k == "unbilled_kwh":
self.db.execute("UPDATE months SET unbilled_kwh = unbilled_kwh + ? WHERE month = ? AND carrier = ?",
(v, month, carrier))
else:
self.db.execute(f"UPDATE months SET {k} = ? WHERE month = ? AND carrier = ?", (v, month, carrier))
def add_window(self, start: float, end: float, records: list[dict]) -> dict:
"""A closed window of the cost aggregator: its kWh per carrier at the
prices in force at its start, into its slot and month; the plan's
estimate of slots that ended. Returns the kWh booked per carrier."""
span = max(0.0, end - start)
slot = int(start // SLOT_S * SLOT_S)
try:
kwh_l = float(self.bundles.box_params(self.clock()).get(OIL_KWH_PER_L))
except (TypeError, ValueError, AttributeError):
kwh_l = None
got = amounts(records, span, kwh_l)
sp = self.bundles.slot_prices(start, self.clock())
fixed = self.bundles.fixed_charges(start)
with self.lock:
self.db.execute("BEGIN")
try:
self._book_plans(slot)
el = (sp or {}).get("electricity") or {}
if el:
self.db.execute("INSERT OR REPLACE INTO prices (slot, price_ct, own_ct, offer) VALUES (?, ?, ?, ?)",
(slot, el.get("price"), el.get("own"), int(bool(el.get("offer")))))
for carrier, kwh in got.items():
if kwh is None or kwh < 0:
continue
p = (sp or {}).get(carrier) or {}
price, own = p.get("price"), p.get("own")
v = {"kwh": kwh, "minutes": span / 60.0}
if price is None:
v["unpriced_kwh"] = kwh
else:
v["cost_eur"] = kwh * price / 100.0
if own is not None:
v["own_eur"] = kwh * own / 100.0
if p.get("offer") and price is not None and own is not None:
v.update(offer_kwh=kwh, offer_eur=kwh * price / 100.0, offer_own_eur=kwh * own / 100.0)
extra = {}
f = (fixed or {}).get(carrier)
if f is not None:
extra.update(fixed_eur=f["eur_month"], fixed_incomplete=int(bool(f.get("incomplete"))))
if p.get("offer") and not p.get("billed"):
extra["unbilled_kwh"] = kwh
self._add(slot, carrier, v, None if not p else bool(p.get("billed", True)), extra)
self.db.execute("COMMIT")
except Exception:
self.db.execute("ROLLBACK")
raise
return got
def take_plan(self, plan: dict):
"""A new plan: its estimate for the quarter-hour under way (step 0,
optimizer.step_costs), booked when the quarter-hour ends; a later
plan in the same quarter-hour replaces it."""
se, start, step = plan.get("steps_eur"), plan.get("start"), plan.get("step_s") or SLOT_S
# the heat no room model plans: its expected bill over the plan's horizon (methods A2.16, A12)
ho = plan.get("heat_outlook")
self.outlook = {k: ho.get(k) for k in ("carrier", "eur", "input_kwh")} | {
"hours": round((plan.get("steps") or 0) * step / 3600.0)} if isinstance(ho, dict) else None
if not isinstance(se, dict) or not _finite(start):
return
now = self.clock()
k = int((now - start) // step)
if k < 0:
return
slot = int(start + k * step)
est = {}
for carrier, d in se.items():
try:
est[carrier] = (float(d["plan"][k]), float(d["base"][k]))
except (KeyError, IndexError, TypeError, ValueError):
continue
if est:
self.pending[slot] = {"est": est, "mode": self.mode() or ""}
def _book_plans(self, now_slot: int):
for slot in sorted(s for s in self.pending if s < now_slot):
p = self.pending.pop(slot)
if slot <= self._booked:
continue
sp = self.bundles.slot_prices(slot, self.clock()) or {}
for carrier, (plan_eur, base_eur) in p["est"].items():
saving = base_eur - plan_eur
billed = carrier != "electricity" or not (sp.get("electricity") or {}).get("offer") or \
bool((sp.get("electricity") or {}).get("billed"))
acted = p["mode"] == "auto" and billed
self._add(slot, carrier, {"plan_eur": plan_eur, "base_eur": base_eur,
"saved_eur" if acted else "would_eur": saving, "plan_slots": 1})
self._booked = slot
def prune(self, now: float | None = None):
now = self.clock() if now is None else now
with self.lock:
self.db.execute("DELETE FROM slots WHERE slot < ?", (int(now) - KEEP_DAYS * 86400,))
self.db.execute("DELETE FROM prices WHERE slot < ?", (int(now) - KEEP_PRICE_DAYS * 86400,))
# -- reading ----------------------------------------------------------------
def month_row(self, month: str, carrier: str) -> dict | None:
with self.lock:
cur = self.db.execute(f"SELECT {', '.join(COLS)}, fixed_eur, fixed_incomplete, unbilled_kwh FROM months "
"WHERE month = ? AND carrier = ?", (month, carrier))
row = cur.fetchone()
if row is None:
return None
return dict(zip(COLS + ("fixed_eur", "fixed_incomplete", "unbilled_kwh"), row))
def window(self, carrier: str, since: int, until: int) -> dict:
with self.lock:
row = self.db.execute("SELECT count(*), sum(cost_eur), sum(unpriced_kwh), sum(minutes) FROM slots "
"WHERE carrier = ? AND slot >= ? AND slot < ? AND minutes > 0",
(carrier, since, until)).fetchone()
return {"slots": row[0] or 0, "cost_eur": row[1] or 0.0, "unpriced_kwh": row[2] or 0.0, "minutes": row[3] or 0.0}
def stored_prices(self, since: int, until: int) -> dict[int, tuple]:
with self.lock:
rows = self.db.execute("SELECT slot, price_ct, own_ct, offer FROM prices WHERE slot >= ? AND slot < ?",
(since, until)).fetchall()
return {int(s): (p, o, bool(f)) for s, p, o, f in rows}
def carriers(self, now: float) -> list[str]:
"""The carriers this home has: electricity always; gas and heat with
a meter value kept or a price in the bundle."""
out = ["electricity"]
with self.lock:
kept = {c for (c,) in self.db.execute("SELECT DISTINCT carrier FROM months")}
sp = self.bundles.slot_prices(now, now) or {}
for c in ("gas", "heat", "oil"):
if c in kept or (sp.get(c) or {}).get("price") is not None:
out.append(c)
return out
# -- the report HA shows ------------------------------------------------------------
def _eur(v: float | None, lang: str) -> str:
return "–" if v is None else f"{names.number(v, lang, 2)} €"
def _ct(v: float | None, lang: str) -> str:
return "–" if v is None else names.number(v, lang, 1)
def report(ledger: Ledger, now: float | None, lang: str, meters: dict[str, bool], has_plan: bool) -> dict:
"""What the dashboard shows, in HA's language (names.py): per section
its figures and markdown, and the gaps (missing data: a figure is None
and why). meters: per carrier whether the mapping has a meter for it.
A section that fails is a gap of its own; the others stay."""
now = ledger.clock() if now is None else now
out = {"gaps": [], "made": int(now)}
def gap(section: str, why: str):
out["gaps"].append({"section": section, "why": why})
for key, fn in (("prices", lambda: prices_section(ledger, now, lang, gap)),
("costs", lambda: costs_section(ledger, now, lang, meters, gap)),
("savings", lambda: savings_section(ledger, now, lang, has_plan, gap))):
try:
out[key] = fn()
except Exception as e: # one section's failure never takes the others with it
log.warning("costs: the %s section: %s", key, e)
out[key] = None
gap(key, names.name("cg_failed", lang, str(e)[:120]))
out["md_gaps"] = "\n".join(f"- **{names.name('cs_' + g['section'], lang)}**: {g['why']}" for g in out["gaps"])
return out
def prices_section(ledger: Ledger, now: float, lang: str, gap) -> dict:
"""Today and tomorrow per hour (local): the price (mean of its
quarter-hours), where it came from (the building's or community's offer,
or the own supplier) and, where an offer exists, the own supplier's
price beside it."""
zone = ledger.zone()
b = ledger.bundles
tenant = b.tenant_now(now)
d0 = datetime.fromtimestamp(now, timezone.utc).astimezone(zone).replace(hour=0, minute=0, second=0, microsecond=0)
d0 = datetime(d0.year, d0.month, d0.day, tzinfo=zone)
days = []
stored = ledger.stored_prices(int(d0.timestamp()), int(d0.timestamp()) + 2 * 86400 + 7200)
for di, key in ((0, "today"), (1, "tomorrow")):
day = (d0 + timedelta(days=di))
day = datetime(day.year, day.month, day.day, tzinfo=zone)
nxt = day + timedelta(days=1)
nxt = datetime(nxt.year, nxt.month, nxt.day, tzinfo=zone)
hours = []
t = int(day.timestamp())
while t < int(nxt.timestamp()):
qs = []
for q in range(4):
s = t + q * SLOT_S
sp = (b.slot_prices(s, now) or {}).get("electricity")
if sp and sp.get("price") is not None:
qs.append((sp["price"], sp.get("own"), bool(sp.get("offer"))))
elif s in stored and stored[s][0] is not None:
qs.append(stored[s])
local = datetime.fromtimestamp(t, timezone.utc).astimezone(zone)
if qs:
own = [o for _, o, _ in qs if o is not None]
hours.append({"h": local.strftime("%H"), "t": t, "ct": round(sum(p for p, _, _ in qs) / len(qs), 2),
"own": round(sum(own) / len(own), 2) if len(own) == len(qs) else None,
"offer": sum(1 for *_, f in qs if f), "of": len(qs)})
else:
hours.append({"h": local.strftime("%H"), "t": t, "ct": None, "own": None, "offer": 0, "of": 0})
t += 3600
days.append({"key": key, "date": day.strftime("%Y-%m-%d"), "hours": hours})
any_offer = tenant is not None or any(h["offer"] for d in days for h in d["hours"])
who = names.name("cs_offer_of", lang, tenant_label(tenant)) if tenant else names.name("cs_offer", lang)
for d in days:
priced = [h for h in d["hours"] if h["ct"] is not None]
label = names.name("cs_" + d["key"], lang)
if not priced:
d["md"] = f"**{label}**: {names.name('cg_no_prices_day', lang)}"
if d["key"] == "today":
gap("prices", names.name("cg_no_prices_today", lang))
continue
lo, hi = min(h["ct"] for h in priced), max(h["ct"] for h in priced)
n_off = sum(1 for h in priced if h["offer"])
head = f"<b>{label}</b>: {_ct(lo, lang)}–{_ct(hi, lang)} ct/kWh" # HTML: a summary is no markdown
if any_offer:
head += " · " + html.escape(names.name("cs_hours_offer", lang, n_off, who))
rows = []
hdr = f"| {names.name('cs_hour', lang)} | ct/kWh | {names.name('cs_from', lang)} |"
sep = "|---|---:|---|"
if any_offer:
hdr += f" {names.name('cs_own', lang)} |"
sep += "---:|"
for h in d["hours"]:
src = "–" if h["ct"] is None else (names.name("cs_src_offer", lang) if h["offer"] == h["of"] and h["of"]
else names.name("cs_src_part", lang) if h["offer"]
else names.name("cs_src_own", lang))
row = f"| {h['h']} | {_ct(h['ct'], lang)} | {src} |"
if any_offer:
row += f" {_ct(h['own'], lang) if h['offer'] else ''} |"
rows.append(row)
d["md"] = (f"<details><summary>{head}</summary>\n\n{hdr}\n{sep}\n" + "\n".join(rows) + "\n\n</details>")
# now: the price, its source and the own supplier's beside it
sp = (b.slot_prices(now, now) or {}).get("electricity") or {}
now_md = ""
if sp.get("price") is not None:
now_md = f"{names.name('price_now', lang)} **{_ct(sp['price'], lang)} ct/kWh**"
if sp.get("offer"):
now_md += " · " + who
if sp.get("own") is not None:
now_md += f" · {names.name('cs_own_now', lang)} {_ct(sp['own'], lang)} ct/kWh"
else:
now_md += " · " + names.name("cs_src_own_long", lang)
if tenant and not tenant.get("billed"):
now_md += f" \n<small>{names.name('cs_offer_shadow', lang)}</small>"
else:
gap("prices", names.name("cg_no_price_now", lang))
if tenant and not tenant.get("own_known"):
gap("prices", names.name("cg_no_own_curve", lang))
return {"now_md": now_md, "days": days, "tenant": tenant, "offer": any_offer}
def tenant_label(t: dict | None) -> str:
if not t:
return ""
model = {"mieterstrom": "Mieterstrom", "ggv": "GGV", "sharing": "§42c"}.get(t.get("model"), t.get("model") or "")
return f"{t.get('name') or t.get('plant') or ''} ({model})".strip()
def costs_section(ledger: Ledger, now: float, lang: str, meters: dict[str, bool], gap) -> dict:
"""Per carrier: this month so far, the forecast to its end, last month;
each with the fixed charges where the bundle carries them."""
month = ledger.month_of(now)
a, b = ledger.month_bounds(now)
last = ledger.month_of(a - 1)
params = ledger.bundles.box_params(now)
days = params.get(PARAM_FORECAST)
if not _finite(days) or not FORECAST_DAYS[0] <= days <= FORECAST_DAYS[1]:
days = None
gap("costs", names.name("cg_no_forecast_param", lang, PARAM_FORECAST))
fixed_now = ledger.bundles.fixed_charges(now)
if fixed_now is None:
gap("costs", names.name("cg_no_fixed", lang))
out = {"month": month, "last_month": last, "carriers": {}}
rows = []
for c in ledger.carriers(now):
cur, prev = ledger.month_row(month, c), ledger.month_row(last, c)
r = {"so_far": None, "forecast": None, "last": None, "kwh": None, "fixed_month": None, "why": []}
fx = (fixed_now or {}).get(c)
if fx is not None:
r["fixed_month"] = round(fx["eur_month"], 2)
if not meters.get(c) and not (cur and cur["kwh"]):
r["why"].append(names.name("cg_no_meter_" + c, lang))
gap("costs", names.name("cg_no_meter_" + c, lang))
elif cur is None or not cur["minutes"]:
r["why"].append(names.name("cg_no_meter_data", lang))
else:
elapsed = max(0.0, min(1.0, (now - a) / (b - a)))
fixed_so_far = fx["eur_month"] * elapsed if fx else 0.0
r["kwh"] = round(cur["kwh"], 2)
r["so_far"] = round(cur["cost_eur"] + fixed_so_far, 2)
if cur["unpriced_kwh"] > 0.0005:
r["why"].append(names.name("cg_unpriced", lang, names.number(cur["unpriced_kwh"], lang, 1)))
gap("costs", names.name("cg_unpriced_of", lang, names.name("carrier_" + c, lang),
names.number(cur["unpriced_kwh"], lang, 1)))
if days is not None:
w = ledger.window(c, int(now - days * 86400), int(now))
if w["minutes"] >= 60:
per_min = w["cost_eur"] / w["minutes"]
rest = max(0.0, (b - now) / 60.0)
r["forecast"] = round(cur["cost_eur"] + per_min * rest + (fx["eur_month"] if fx else 0.0), 2)
r["forecast_basis_h"] = round(w["minutes"] / 60.0, 1)
else:
r["why"].append(names.name("cg_forecast_short", lang))
if prev is not None and prev["minutes"]:
pf = prev.get("fixed_eur")
r["last"] = round(prev["cost_eur"] + (pf or 0.0), 2)
r["last_kwh"] = round(prev["kwh"], 2)
if cur and cur.get("unbilled_kwh", 0) > 0.0005:
r["own_eur"] = round(cur["own_eur"], 2)
r["note"] = names.name("cs_unbilled_note", lang, _eur(cur["own_eur"], lang))
r["incomplete"] = bool(cur and (cur["unpriced_kwh"] > 0.0005 or cur.get("fixed_incomplete")))
out["carriers"][c] = r
star = "*" if r["incomplete"] else ""
rows.append(f"| {names.name('carrier_' + c, lang)} | {_eur(r['so_far'], lang)}{star} | "
f"{_eur(r['forecast'], lang)} | {_eur(r['last'], lang)} |")
hdr = (f"| | {names.name('cs_so_far', lang)} | {names.name('cs_forecast', lang)} | "
f"{names.name('cs_last_month', lang)} |\n|---|---:|---:|---:|\n")
notes = []
if fixed_now is not None:
notes.append(names.name("cs_fixed_in", lang))
else:
notes.append(names.name("cs_fixed_out", lang))
if any(r["incomplete"] for r in out["carriers"].values()):
notes.append(names.name("cs_incomplete", lang))
notes += [r["note"] for r in out["carriers"].values() if r.get("note")]
if days is not None:
notes.append(names.name("cs_forecast_how", lang, int(days)))
ho = getattr(ledger, "outlook", None)
if ho and _finite(ho.get("eur")):
# the heat no room model plans: what the last plan expects it to cost (methods A2.16)
out["heat_outlook"] = ho
notes.append(names.name("cs_heat_outlook", lang, names.name("carrier_" + str(ho.get("carrier")), lang),
ho.get("hours"), _eur(ho["eur"], lang), names.number(ho.get("input_kwh") or 0.0, lang, 1)))
out["md"] = hdr + "\n".join(rows) + "\n\n<small>" + " ".join(notes) + "</small>"
return out
def savings_section(ledger: Ledger, now: float, lang: str, has_plan: bool, gap) -> dict:
"""Per carrier, this month and last: (a) where the household buys: the
building's or community's offer against its own supplier for the same
kWh (electricity only: there is no tenant gas or heat); (b) the plan's
actions: with against without the plan, the same prices (its estimate).
Shadow (control mode shadow or advisory, or a tenant price not billed):
"would have saved", never money saved."""
month = ledger.month_of(now)
a, _ = ledger.month_bounds(now)
last = ledger.month_of(a - 1)
tenant = ledger.bundles.tenant_now(now)
out = {"carriers": {}}
lines = []
for c in ledger.carriers(now):
cur, prev = ledger.month_row(month, c) or {}, ledger.month_row(last, c) or {}
r = {}
if c == "electricity":
if cur.get("offer_kwh") or prev.get("offer_kwh") or tenant:
billed = not cur.get("unbilled_kwh") and bool(cur.get("offer_kwh"))
r["offer"] = {"month": round(cur.get("offer_own_eur", 0) - cur.get("offer_eur", 0), 2) if cur.get("offer_kwh") else None,
"last": round(prev.get("offer_own_eur", 0) - prev.get("offer_eur", 0), 2) if prev.get("offer_kwh") else None,
"kwh": round(cur.get("offer_kwh", 0), 2), "billed": billed}
key = "cs_offer_saved" if billed else "cs_offer_would"
if r["offer"]["month"] is None:
lines.append(f"- {names.name('cs_offer_none_yet', lang, tenant_label(tenant))}")
else:
lines.append(f"- {names.name(key, lang, _eur(r['offer']['month'], lang), names.number(r['offer']['kwh'], lang, 1))}"
+ (f" · {names.name('cs_last_month', lang)} {_eur(r['offer']['last'], lang)}"
if r["offer"]["last"] is not None else ""))
else:
lines.append(f"- {names.name('cs_offer_no', lang)}")
p_cur = (cur.get("saved_eur", 0), cur.get("would_eur", 0), cur.get("plan_slots", 0))
p_prev = (prev.get("saved_eur", 0), prev.get("would_eur", 0), prev.get("plan_slots", 0))
if p_cur[2] or p_prev[2]:
r["plan"] = {"saved": round(p_cur[0], 2) if p_cur[2] else None, "would": round(p_cur[1], 2) if p_cur[2] else None,
"hours": round(p_cur[2] / 4.0, 1),
"last_saved": round(p_prev[0], 2) if p_prev[2] else None,
"last_would": round(p_prev[1], 2) if p_prev[2] else None}
parts = []
if p_cur[2] and abs(p_cur[0]) >= 0.005:
parts.append(names.name("cs_plan_saved", lang, _eur(p_cur[0], lang)))
if p_cur[2] and (abs(p_cur[1]) >= 0.005 or not parts):
parts.append(names.name("cs_plan_would", lang, _eur(p_cur[1], lang)))
if not p_cur[2]:
parts.append(names.name("cs_plan_none_month", lang))
tail = ""
if p_prev[2]:
tail = f" · {names.name('cs_last_month', lang)} {_eur(p_prev[0] + p_prev[1], lang)}"
lines.append(f"- {names.name('cs_plan_of', lang, names.name('carrier_' + c, lang))}: " + ", ".join(parts) + tail)
elif c == "electricity" or has_plan:
why = names.name("cg_no_plan" if not has_plan else "cg_no_plan_yet", lang)
lines.append(f"- {names.name('cs_plan_of', lang, names.name('carrier_' + c, lang))}: {why}")
if c == "electricity":
gap("savings", why)
out["carriers"][c] = r
out["md"] = "\n".join(lines) + "\n\n<small>" + names.name("cs_savings_how", lang) + "</small>"
return out