diff --git a/app/main.py b/app/main.py index 7e8dba6..8485a07 100644 --- a/app/main.py +++ b/app/main.py @@ -9453,6 +9453,74 @@ async def derive_member_sources() -> dict: return {"checked": len(stale), "flipped": flipped} +FX_POLICY_EUR_USD = float(os.environ.get("FX_POLICY_EUR_USD", "1.16") or 1.16) +FX_ALERT_PCT = float(os.environ.get("FX_ALERT_PCT", "2.0") or 2.0) + + +def _fx_verdict(rate: float, policy: float = FX_POLICY_EUR_USD, + threshold: float = FX_ALERT_PCT) -> dict: + """Compare a live EUR/USD rate to the pricing policy. Pure, so it is testable.""" + drift = ((rate - policy) / policy * 100.0) if policy else 0.0 + return {"rate": round(float(rate), 4), "policy": policy, + "drift_pct": round(drift, 2), "alert": abs(drift) >= threshold} + + +async def fx_spot_check(send: bool = True) -> dict: + """Daily spot check of EUR/USD against the pricing FX (1.16). Alerts, never reprices. + + Source: ECB daily reference rate. An alert is sent to info@ only when the drift + first crosses FX_ALERT_PCT; staying over the line does not mail every day. When + the rate returns inside the band the marker resets, so a later breach is news. + """ + try: + async with httpx.AsyncClient(timeout=20.0) as client: + r = await client.get("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml") + r.raise_for_status() + m = re.search(r'currency=["\']USD["\']\s+rate=["\']([0-9.]+)["\']', r.text) + if not m: + return {"error": "USD rate not found in ECB feed"} + rate = float(m.group(1)) + except Exception as exc: # noqa: BLE001 + return {"error": f"ECB fetch failed: {str(exc)[:120]}"} + + verdict = _fx_verdict(rate) + verdict["checked_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds") + + conn = get_db() + try: + prev_row = conn.execute("SELECT value FROM portal_state WHERE key = 'fx_alert'").fetchone() + prev = json.loads(prev_row[0]) if prev_row and prev_row[0] else {} + finally: + conn.close() + + newly_alerting = verdict["alert"] and not prev.get("alerted") + verdict["alerted_before"] = bool(prev.get("alerted")) + verdict["notified"] = False + if newly_alerting and send: + direction = "above" if verdict["drift_pct"] > 0 else "below" + verdict["notified"] = bool(send_email( + ADMIN_INVITER_EMAIL, + f"EUR/USD {verdict['drift_pct']:+.1f}% {direction} the pricing FX", + f"The ECB rate is {verdict['rate']} USD per EUR; our pricing policy is " + f"{verdict['policy']}. Drift: {verdict['drift_pct']:+.1f}%.\n\n" + "No prices were changed automatically. Decide whether to re-convert " + "GreenPT/Regolo EUR list prices at the new rate (scripts/check_eur_fx.py " + "in code/litellm guards the conversion).\n")) + + conn = get_db() + try: + conn.execute( + "INSERT INTO portal_state (key, value) VALUES ('fx_alert', ?) " + "ON CONFLICT(key) DO UPDATE SET value = excluded.value", + (json.dumps({"alerted": bool(verdict["alert"]), "rate": verdict["rate"], + "drift_pct": verdict["drift_pct"], + "at": verdict["checked_at"]}),)) + conn.commit() + finally: + conn.close() + return verdict + + @app.post("/admin/sweep") @limiter.limit("20/minute") async def admin_sweep(request: Request): @@ -9511,6 +9579,13 @@ async def admin_sweep(request: Request): except Exception as exc: # noqa: BLE001 result["member_sources"] = {"error": str(exc)[:200]} + # FX spot check: compare the ECB EUR/USD rate to the pricing policy. Alerts + # info@ on a new breach; never reprices anything by itself. + try: + result["fx_spot_check"] = await fx_spot_check(send=True) + except Exception as exc: # noqa: BLE001 + result["fx_spot_check"] = {"error": str(exc)[:200]} + # Paid Open Collective contributors with no portal row — the net for members # the sweep cannot see (hidden email, org account). Emails info@ only when it # finds something, and only when the set changes. Was a daily script on the diff --git a/tests/test_fx_verdict.py b/tests/test_fx_verdict.py new file mode 100644 index 0000000..4182d06 --- /dev/null +++ b/tests/test_fx_verdict.py @@ -0,0 +1,8 @@ +import os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import app.main as m +v=m._fx_verdict(1.16); assert v["alert"] is False, v +v=m._fx_verdict(1.20); assert v["alert"] is True and v["drift_pct"] > 0, v +v=m._fx_verdict(1.10); assert v["alert"] is True and v["drift_pct"] < 0, v +v=m._fx_verdict(1.157); assert v["alert"] is False, v # 0.26% drift +print("FX VERDICT OK: thresholds and signs behave")