Spaces:
Running

electrocheap / core.py
kugguk's picture
Add compressed billing imports, bulk CPU analysis and provider swap scenarios
d7dbd19 verified
Raw History Blame Contribute Delete
12.2 kB
"""Auditable quote comparison. Monetary inputs are tax-inclusive currency units."""
from datetime import date
import math
from urllib.parse import urlparse
from billing import normalize_bills
MARKETS = {"PT": "EUR", "DE": "EUR", "AU": "AUD"}
MAX_OFFERS = 500
REQUIRED = ["offer_id", "provider", "country", "region", "currency", "customer_type",
"tariff_type", "rate_per_kwh", "offpeak_rate_per_kwh", "daily_charge",
"annual_fees", "guaranteed_credit", "switching_cost", "tax_included",
"valid_from", "valid_to", "checked_at", "source_url", "evidence",
"conditions", "meter_type", "price_guaranteed_months"]
def number(value, name, minimum=0, maximum=1e9):
if isinstance(value, bool):
raise ValueError(f"{name} must be a number.")
try:
x = float(value)
except (TypeError, ValueError):
raise ValueError(f"{name} must be a finite number.") from None
if not math.isfinite(x) or not minimum <= x <= maximum:
raise ValueError(f"{name} must be between {minimum} and {maximum}.")
return x
def boolean(value, name):
if value is True or str(value).strip().lower() in {"true", "1"}:
return True
if value is False or str(value).strip().lower() in {"false", "0"}:
return False
raise ValueError(f"{name} must be true or false.")
def iso(value, name):
try:
return date.fromisoformat(str(value))
except ValueError:
raise ValueError(f"{name} must be YYYY-MM-DD.") from None
def validate_offer(row):
missing = [k for k in REQUIRED if k not in row]
if missing:
raise ValueError("Missing offer fields: " + ", ".join(missing))
r = dict(row)
for k in REQUIRED:
if isinstance(r[k], float) and not math.isfinite(r[k]):
raise ValueError(f"Missing or invalid {k}.")
for k in ["offer_id", "provider", "country", "region", "currency", "customer_type",
"tariff_type", "source_url", "evidence", "conditions", "meter_type"]:
r[k] = str(r[k]).strip()
if not r[k] or len(r[k]) > 2000:
raise ValueError(f"{k} must contain 1–2000 characters.")
if r["country"] not in MARKETS or r["currency"] != MARKETS[r["country"]]:
raise ValueError("Use PT/EUR, DE/EUR or AU/AUD; currencies are never converted.")
if r["tariff_type"] not in {"flat", "tou"}:
raise ValueError("Only flat and two-period time-of-use tariffs are supported.")
if r["customer_type"] not in {"consumer", "ngo", "business", "all"}:
raise ValueError("Invalid customer_type.")
if r["evidence"] not in {"submitted_quote", "illustrative"}:
raise ValueError("Evidence must be submitted_quote or illustrative; uploads are not independently verified.")
if r["meter_type"] not in {"standard", "smart", "any"}:
raise ValueError("meter_type must be standard, smart or any.")
for k in ["rate_per_kwh", "offpeak_rate_per_kwh", "daily_charge", "annual_fees",
"guaranteed_credit", "switching_cost", "price_guaranteed_months"]:
r[k] = number(r[k], k)
r["tax_included"] = boolean(r["tax_included"], "tax_included")
for k in ["valid_from", "valid_to", "checked_at"]:
r[k] = iso(r[k], k).isoformat()
if r["valid_to"] < r["valid_from"]:
raise ValueError("valid_to precedes valid_from.")
if r.get("contracted_power_kva") not in {None,""}:
r["contracted_power_kva"] = number(r["contracted_power_kva"], "contracted_power_kva", .1, 1000)
url = urlparse(r["source_url"])
if url.scheme != "https" or not url.netloc:
raise ValueError("source_url must be an HTTPS evidence link.")
return r
def annual_cost(r, kwh, peak_share):
rate = r["rate_per_kwh"]
if r["tariff_type"] == "tou":
rate = peak_share * rate + (1 - peak_share) * r["offpeak_rate_per_kwh"]
recurring = kwh * rate + 365 * r["daily_charge"] + r["annual_fees"]
return recurring + r["switching_cost"] - r["guaranteed_credit"], recurring
def consumer_compare(payload):
"""Compare supplied quotes for one profile; no contracting or switching."""
if not isinstance(payload, dict):
raise ValueError("Supply a JSON object.")
country = payload.get("country", "PT")
if country not in MARKETS:
raise ValueError("country must be PT, DE or AU.")
region = str(payload.get("region", "")).strip()
if not region:
raise ValueError("An eligibility region/grid code is required.")
as_of = iso(payload.get("as_of", date.today().isoformat()), "as_of")
bill_summary = None
if "billing_months" in payload:
bill_summary = normalize_bills(payload["billing_months"], MARKETS[country], as_of)
for field in ["annual_kwh", "current_annual_bill", "peak_share"]:
if field in payload and field in bill_summary and not math.isclose(number(payload[field], field), bill_summary[field], rel_tol=1e-6, abs_tol=.01):
raise ValueError(f"{field} conflicts with the supplied monthly bills; omit the annual override.")
payload = {**payload, **bill_summary}
kwh = number(payload.get("annual_kwh"), "annual_kwh", 1, 1e7)
current = number(payload.get("current_annual_bill"), "current_annual_bill", 0, 1e8)
peak = number(payload.get("peak_share", .5), "peak_share", 0, 1)
audience = payload.get("customer_type", "consumer")
if audience not in {"consumer", "ngo", "business"}:
raise ValueError("Invalid profile customer_type.")
meter = payload.get("meter_type", "standard")
if meter not in {"standard", "smart"}:
raise ValueError("Profile meter_type must be standard or smart.")
offers = payload.get("offers", [])
if not isinstance(offers, list) or len(offers) > MAX_OFFERS:
raise ValueError(f"Supply a list of at most {MAX_OFFERS} quotes.")
allow_demo = boolean(payload.get("allow_illustrative", False), "allow_illustrative")
accepted = payload.get("accepted_conditions", [])
if not isinstance(accepted, list) or any(not isinstance(x, str) for x in accepted):
raise ValueError("accepted_conditions must be a list of offer IDs.")
ranked, excluded, seen = [], [], set()
for raw in offers:
if not isinstance(raw, dict):
excluded.append({"offer_id": "unknown", "reason": "Quote must be an object."}); continue
offer_id = str(raw.get("offer_id", "unknown"))[:200]
try:
r = validate_offer(raw)
if r["offer_id"] in seen:
raise ValueError("Duplicate offer_id in input.")
seen.add(r["offer_id"])
if r["country"] != country or r["region"] not in {region, "ALL"}:
raise ValueError("Outside the selected market/eligibility region.")
if r["customer_type"] not in {audience, "all"}:
raise ValueError("Customer type is ineligible; NGO sites require NGO/all quotes.")
if r["meter_type"] not in {meter, "any"}:
raise ValueError("Meter is ineligible.")
if payload.get("contracted_power_kva") not in {None,""}:
power = number(payload["contracted_power_kva"], "contracted_power_kva", .1, 1000)
if r.get("contracted_power_kva") in {None,""} or not math.isclose(power,r["contracted_power_kva"],abs_tol=.001):
raise ValueError("Quote must explicitly match the contracted kVA power.")
if r["tariff_type"] == "tou" and meter != "smart":
raise ValueError("Time-of-use estimation requires a smart-meter profile.")
if not r["tax_included"]:
raise ValueError("A complete tax-inclusive quote is required.")
if not iso(r["valid_from"], "valid_from") <= as_of <= iso(r["valid_to"], "valid_to"):
raise ValueError("Quote is not open for enrolment at the selected date.")
age = (as_of - iso(r["checked_at"], "checked_at")).days
if age < 0 or age > 14:
raise ValueError("Quote checked_at is in the future or more than 14 days old.")
if r["evidence"] == "illustrative" and not allow_demo:
raise ValueError("Illustrative quotes are disabled.")
if r["conditions"].lower() != "none" and r["offer_id"] not in accepted:
raise ValueError("Quote conditions need explicit acknowledgement by offer ID.")
first, recurring = annual_cost(r, kwh, peak)
low, _ = annual_cost(r, kwh * .8, peak)
high, _ = annual_cost(r, kwh * 1.2, peak)
ranked.append({"offer_id": r["offer_id"], "provider": r["provider"],
"currency": r["currency"], "first_year_cost": round(first, 2),
"recurring_annual_cost": round(recurring, 2),
"estimated_saving": round(current - first, 2),
"cost_at_80pct_usage": round(low, 2), "cost_at_120pct_usage": round(high, 2),
"price_basis": "12-month guarantee stated in quote" if r["price_guaranteed_months"] >= 12 else "constant-price scenario; rate may change",
"evidence": r["evidence"], "checked_at": r["checked_at"],
"source_url": r["source_url"], "conditions": r["conditions"]})
except (ValueError, TypeError) as e:
excluded.append({"offer_id": offer_id, "reason": str(e)})
ranked.sort(key=lambda x: (x["first_year_cost"], x["offer_id"]))
return {"status": "quoted_comparison" if ranked else "no_eligible_quotes",
"country": country, "region": region, "currency": MARKETS[country],
"as_of": as_of.isoformat(), "annual_kwh": kwh, "current_annual_bill": current,
"billing_summary": bill_summary,
"profile_source": str(payload.get("profile_source", "latest_12_complete_monthly_bills" if bill_summary else "annual_user_input"))[:200],
"ranked_offers": ranked, "excluded_offers": excluded,
"recommended_action": "Review the lowest eligible quote" if ranked and ranked[0]["estimated_saving"] > 0 else "Keep current contract under this scenario",
"method": "365-day tax-inclusive estimate. Rates assumed constant; includes all supplied annual fees, guaranteed credit and switching cost. No automatic switching.",
"limits": "Eligibility and completeness are assertions in supplied quotes, not independently verified. Usage scenarios are not confidence intervals. Demand/capacity charges, tiered tariffs, controlled load, export credits and dynamic-indexed contracts must be reduced to a complete scoped quote before comparison."}
def ngo_compare(payload):
"""Compare up to 100 deidentified household or NGO-site profiles independently."""
if not isinstance(payload, dict):
raise ValueError("Supply a JSON object.")
profiles = payload.get("profiles", [])
if not isinstance(profiles, list) or not 1 <= len(profiles) <= 100:
raise ValueError("Supply 1–100 profiles with anonymous profile_id values.")
offers = payload.get("offers", [])
results, totals, seen = [], {}, set()
for p in profiles:
if not isinstance(p, dict):
raise ValueError("Each profile must be an object.")
pid = str(p.get("profile_id", "")).strip()
if not pid or pid in seen or len(pid) > 100:
raise ValueError("Each profile_id must be unique and contain 1–100 characters.")
seen.add(pid)
r = consumer_compare({**payload, **p, "offers": offers})
best = r["ranked_offers"][0] if r["ranked_offers"] else None
saving = max(0, best["estimated_saving"]) if best else 0
results.append({"profile_id": pid, "comparison": r, "saving_if_beneficial": saving})
currency = r["currency"]
totals[currency] = round(totals.get(currency, 0) + saving, 2)
return {"status": "portfolio_scenario", "profiles": results, "estimated_savings_by_currency": totals,
"limits": "Sum of beneficial individual quote scenarios, not a negotiated group discount or realized savings. No cross-currency totals; household and NGO-site eligibility are evaluated separately."}