Files
gabrielvidalandClaude Opus 5.5 49e027eafd feat(usage): when the Claude plan renews, and whether a smaller plan would hold
Anthropic's API gives no next-charge date, only subscriptionCreatedAt
(already read by the sidecar into /accounts → plan). usage/billing.py takes
the monthly renewal on that day and time — an estimate — and peaks each
seven_day window of this cycle and the previous one.

- /api/usage/limits → billing on Claude accounts in the totals (not the
  work seat, Orus's bill)
- Plan usage: a Billing cycle panel — next charge, the weeks' peaks against
  where the Pro / Max 5× caps sit on this plan's scale
- Home strip: a "Renews" tile (hold to bench it), French strings included
- Plan usage is now lazy (the root chunk had crept past the PWA 2 MiB cap)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 03:02:36 +01:00

108 lines
4.4 KiB
Python

"""When a paid Claude plan is billed next, and how this billing cycle's weeks
went — for deciding whether a smaller plan would hold.
Anthropic's API gives no next-charge date. The login's cached profile does
carry when the subscription started (``.claude.json`` → ``oauthAccount`` →
``subscriptionCreatedAt``, read by the sidecar into ``/accounts`` → ``plan``),
and a monthly Stripe subscription renews on that day of the month at that
time — on the month's last day when it is shorter. So the date is an
**estimate**: an upgrade that reset the billing day, or an annual plan, would
move it. claude.ai → Settings → Billing has the authoritative one.
Each week of this cycle and the one before is one ``seven_day`` window instance, its peak % the
highest reading it reached. Shown only for the accounts Gabriel pays for (not
excluded from the totals): the work seat's billing is Orus's.
"""
from __future__ import annotations
import calendar
import datetime as dt
import time
# Two readings belong to the same week when their reset times are this close
# (the reported reset jitters by up to an hour or so).
SAME_WEEK_S = 2 * 86400
def _parse(ts) -> float | None:
if not ts:
return None
try:
return dt.datetime.fromisoformat(str(ts).replace("Z", "+00:00")).timestamp()
except ValueError:
return None
def _monthly(anchor: dt.datetime, year: int, month: int) -> dt.datetime:
"""The anchor's day/time in ``year``-``month`` (clamped to its last day)."""
last = calendar.monthrange(year, month)[1]
return anchor.replace(year=year, month=month, day=min(anchor.day, last))
def period(started_at: float, now: float | None = None) -> tuple[float, float]:
"""``(last renewal, next renewal)`` of a monthly plan started at
``started_at`` — both epoch seconds, ``last <= now < next``."""
now = now if now is not None else time.time()
a = dt.datetime.fromtimestamp(started_at, dt.timezone.utc)
n = dt.datetime.fromtimestamp(now, dt.timezone.utc)
if n < a:
return started_at, _monthly(a, *_add(a.year, a.month, 1)).timestamp()
y, m = n.year, n.month
cur = _monthly(a, y, m)
if cur > n:
y, m = _add(y, m, -1)
cur = _monthly(a, y, m)
nxt = _monthly(a, *_add(y, m, 1))
return cur.timestamp(), nxt.timestamp()
def _add(y: int, m: int, k: int) -> tuple[int, int]:
i = y * 12 + (m - 1) + k
return i // 12, i % 12 + 1
def week_peaks(points: list[tuple], since: float, now: float | None = None) -> list[dict]:
"""One row per week instance whose window ends after ``since``:
``{resetsAt, peak, current}`` (``current`` = still open), oldest first.
``points`` are ``(t, pct, resets_at)`` of the ``seven_day`` window."""
now = now if now is not None else time.time()
weeks: list[dict] = []
for _t, pct, r in sorted(points):
if r is None:
continue
r = float(r)
w = weeks[-1] if weeks else None
if w is None or abs(r - w["resetsAt"]) > SAME_WEEK_S:
weeks.append({"resetsAt": r, "peak": float(pct)})
else:
w["peak"] = max(w["peak"], float(pct))
w["resetsAt"] = max(w["resetsAt"], r)
return [{**w, "current": w["resetsAt"] > now} for w in weeks if w["resetsAt"] > since]
def started_at(row: dict | None, segment: dict | None) -> float | None:
"""The subscription's start: the login's live profile, else the one the
plan tracker stored with the plan segment."""
for src in ((row or {}).get("plan") or {}, (segment or {}).get("data") or {}):
t = _parse(src.get("subscriptionCreatedAt"))
if t:
return t
return None
def billing(store, account: str, row: dict | None, segment: dict | None,
now: float | None = None) -> dict | None:
"""The account's billing cycle, or None when the start isn't known."""
now = now if now is not None else time.time()
start = started_at(row, segment)
if start is None:
return None
last, nxt = period(start, now)
# The cycle before too: a cycle a few days old holds one week.
prev = period(start, last - 1)[0] if last > start else last
series = store.series(account, prev - 8 * 86400).get("seven_day", [])
weeks = [{**w, "inCycle": w["resetsAt"] > last} for w in week_peaks(series, prev, now)]
return {"subscriptionStartedAt": start, "periodStart": last, "previousPeriodStart": prev,
"nextBillingAt": nxt, "estimated": True, "weeks": weeks}