Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
205c695556 | ||
|
|
3db67e54f3 | ||
|
|
bbd8115058 | ||
|
|
ca336a3115 | ||
|
|
122824fd99 | ||
|
|
1191bcd521 | ||
|
|
aba53eabb5 | ||
|
|
fb6af42bbf | ||
|
|
6124d05ffd | ||
|
|
d10b36ed34 | ||
|
|
066a6fc2cf | ||
|
|
a70dd6ab4c | ||
|
|
cfb767dd4f | ||
|
|
18a4447aa2 | ||
|
|
dc53b27ad2 | ||
|
|
3e01f727c2 | ||
|
|
1070fc5dd0 | ||
|
|
0296f8d066 | ||
|
|
3d326ed428 | ||
|
|
97f0d6c3f1 | ||
|
|
237b695087 |
No files matched your search
@@ -29,11 +29,15 @@
|
|||||||
"credit_cycle_close": {
|
"credit_cycle_close": {
|
||||||
"schedule": "*/10 * * * *",
|
"schedule": "*/10 * * * *",
|
||||||
"command": "/app/code/credit_cycle_close.sh"
|
"command": "/app/code/credit_cycle_close.sh"
|
||||||
|
},
|
||||||
|
"loomio_inbound": {
|
||||||
|
"schedule": "*/2 * * * *",
|
||||||
|
"command": "/app/code/loomio_inbound.py"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"manifestVersion": 2,
|
"manifestVersion": 2,
|
||||||
"website": "https://inference.coop",
|
"website": "https://inference.coop",
|
||||||
"contactEmail": "info@inference.coop",
|
"contactEmail": "info@inference.coop",
|
||||||
"dockerImage": "registry.inference.coop/code/member-portal:20261127-0e53c33"
|
"dockerImage": "registry.inference.coop/code/member-portal:20261203-3db67e5"
|
||||||
}
|
}
|
||||||
+2
-1
@@ -12,7 +12,8 @@ COPY sweep.sh /app/code/sweep.sh
|
|||||||
COPY service_sync.sh /app/code/service_sync.sh
|
COPY service_sync.sh /app/code/service_sync.sh
|
||||||
COPY credit_cycle_close.sh /app/code/credit_cycle_close.sh
|
COPY credit_cycle_close.sh /app/code/credit_cycle_close.sh
|
||||||
COPY metrics_snapshot.py /app/code/metrics_snapshot.py
|
COPY metrics_snapshot.py /app/code/metrics_snapshot.py
|
||||||
RUN chmod +x /app/code/sweep.sh /app/code/service_sync.sh /app/code/credit_cycle_close.sh /app/code/metrics_snapshot.py
|
COPY loomio_inbound.py /app/code/loomio_inbound.py
|
||||||
|
RUN chmod +x /app/code/sweep.sh /app/code/service_sync.sh /app/code/credit_cycle_close.sh /app/code/metrics_snapshot.py /app/code/loomio_inbound.py
|
||||||
|
|
||||||
# Run as root (the base image default). Cloudron's sandboxing (read-only
|
# Run as root (the base image default). Cloudron's sandboxing (read-only
|
||||||
# rootfs, AppArmor, dropped capabilities) still applies to root inside the
|
# rootfs, AppArmor, dropped capabilities) still applies to root inside the
|
||||||
|
|||||||
@@ -180,7 +180,7 @@ points. Remaining work before production:
|
|||||||
|
|
||||||
## Scheduled tasks (scheduler addon)
|
## Scheduled tasks (scheduler addon)
|
||||||
|
|
||||||
Four jobs run inside the container via `CloudronManifest.json` → `addons.scheduler`:
|
Five jobs run inside the container via `CloudronManifest.json` → `addons.scheduler`:
|
||||||
|
|
||||||
- **membership_sweep** (`0 3,11,19 * * *` UTC — three times a day) — `sweep.sh`
|
- **membership_sweep** (`0 3,11,19 * * *` UTC — three times a day) — `sweep.sh`
|
||||||
calls the portal's own `/admin/sweep` (auth: the `X-Admin-Token` header with
|
calls the portal's own `/admin/sweep` (auth: the `X-Admin-Token` header with
|
||||||
@@ -316,7 +316,7 @@ Four jobs run inside the container via `CloudronManifest.json` → `addons.sched
|
|||||||
Methodology: [Energy and carbon metrics](docs/energy-metrics.md).
|
Methodology: [Energy and carbon metrics](docs/energy-metrics.md).
|
||||||
|
|
||||||
Verify after any manifest change: the deploy log must show
|
Verify after any manifest change: the deploy log must show
|
||||||
`setupAddons: ... scheduler ...` listing all four tasks, and each script must
|
`setupAddons: ... scheduler ...` listing all five tasks, and each script must
|
||||||
succeed when run manually inside the container.
|
succeed when run manually inside the container.
|
||||||
|
|
||||||
### Allowance renewal (payment-driven, join-day anchored)
|
### Allowance renewal (payment-driven, join-day anchored)
|
||||||
|
|||||||
+439
-23
@@ -1708,6 +1708,15 @@ def add_credits(email: str, delta: float, reason: str, reference: str | None = N
|
|||||||
"INSERT INTO credit_ledger (email, delta, reason, reference) VALUES (?, ?, ?, ?)",
|
"INSERT INTO credit_ledger (email, delta, reason, reference) VALUES (?, ?, ?, ?)",
|
||||||
(email, delta, reason, reference),
|
(email, delta, reason, reference),
|
||||||
)
|
)
|
||||||
|
# Keep `credits_drawn <= credit_balance`. An adjustment that lowers the pack
|
||||||
|
# below what was already drawn must not swallow FUTURE credits: a new pack
|
||||||
|
# adds headroom, while consumption beyond the reduced pack is simply
|
||||||
|
# unbacked. The ledger history itself is never rewritten.
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE members SET credits_drawn = MIN(COALESCE(credits_drawn, 0), "
|
||||||
|
"MAX(0, COALESCE(credit_balance, 0))) WHERE email = ?",
|
||||||
|
(email,),
|
||||||
|
)
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"SELECT credit_balance FROM members WHERE email = ?", (email,)
|
"SELECT credit_balance FROM members WHERE email = ?", (email,)
|
||||||
).fetchone()
|
).fetchone()
|
||||||
@@ -3729,6 +3738,42 @@ async def provision_guest_member(
|
|||||||
return user_id
|
return user_id
|
||||||
|
|
||||||
|
|
||||||
|
def record_guest_conversion_draw(email: str, spend: float) -> float:
|
||||||
|
"""Record guest usage consumed before conversion; only the unspent part carries.
|
||||||
|
|
||||||
|
A guest has no monthly cycle, so nothing ever drew their spend against the
|
||||||
|
$2 pack. Converting without this would hand back credits already used
|
||||||
|
(guest-access.md promises only the UNSPENT credit carries over). The draw
|
||||||
|
is capped by the row's current credit and deduped on a ledger reference.
|
||||||
|
Returns the amount recorded (0.0 when nothing owed or already recorded).
|
||||||
|
"""
|
||||||
|
purchased = get_credit_balance(email)
|
||||||
|
used = round(min(max(0.0, float(spend or 0.0)), purchased), 6)
|
||||||
|
if used <= 0:
|
||||||
|
return 0.0
|
||||||
|
ref = f"guest-convert-draw:{email}"
|
||||||
|
if credit_reference_exists(ref):
|
||||||
|
return 0.0
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO credit_ledger (email, delta, reason, reference) "
|
||||||
|
"VALUES (?, ?, ?, ?)",
|
||||||
|
(email, -used,
|
||||||
|
"guest credit used before conversion — only unspent credit carries over",
|
||||||
|
ref),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE members SET credits_drawn = COALESCE(credits_drawn, 0) + ? "
|
||||||
|
"WHERE email = ?",
|
||||||
|
(used, email),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return used
|
||||||
|
|
||||||
|
|
||||||
async def convert_guest_to_member(email: str, name: str, slug: str = "") -> str:
|
async def convert_guest_to_member(email: str, name: str, slug: str = "") -> str:
|
||||||
"""Convert a GUEST account into a full member (the automatic transition).
|
"""Convert a GUEST account into a full member (the automatic transition).
|
||||||
|
|
||||||
@@ -3775,6 +3820,24 @@ async def convert_guest_to_member(email: str, name: str, slug: str = "") -> str:
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
# Guest usage has already consumed part of the $2; only the UNSPENT credit
|
||||||
|
# may carry into membership (guest-access.md). record_guest_conversion_draw
|
||||||
|
# writes the consumed part as a draw so it cannot be spent twice.
|
||||||
|
try:
|
||||||
|
guest_spend = None
|
||||||
|
team_id = await litellm_team_id_for_email(email)
|
||||||
|
if team_id:
|
||||||
|
team = get_team_budget_from_db(team_id)
|
||||||
|
if team:
|
||||||
|
guest_spend = float(team.get("spend") or 0.0)
|
||||||
|
if guest_spend is not None:
|
||||||
|
used = record_guest_conversion_draw(email, guest_spend)
|
||||||
|
if used > 0:
|
||||||
|
logger.info("Guest convert: %.2f of guest credit already used for %s; "
|
||||||
|
"the rest carries over", used, email)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
logger.warning("Guest convert: guest-draw accounting failed for %s: %s", email, e)
|
||||||
|
|
||||||
# 3. Lift the LiteLLM cap to allowance + credits and pin the reset to
|
# 3. Lift the LiteLLM cap to allowance + credits and pin the reset to
|
||||||
# their anchor day, exactly as the webhook does for any member.
|
# their anchor day, exactly as the webhook does for any member.
|
||||||
await sync_team_budget_from_balance(email)
|
await sync_team_budget_from_balance(email)
|
||||||
@@ -4229,6 +4292,29 @@ async def litellm_update_team_budget(team_id: str, budget: float) -> None:
|
|||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
|
|
||||||
|
|
||||||
|
async def litellm_clear_team_budget(team_id: str) -> None:
|
||||||
|
"""Remove a team's spend cap (max_budget = NULL = unlimited).
|
||||||
|
|
||||||
|
Operator/infrastructure accounts are collective expenses, not members:
|
||||||
|
applying the $15/credits cap to them would cut off the co-op's own tooling
|
||||||
|
mid-task. Written straight to the team row because /team/update also
|
||||||
|
silently drops budget_reset_at (an uncapped team needs no reset).
|
||||||
|
"""
|
||||||
|
def _write() -> None:
|
||||||
|
conn = _pg_connect()
|
||||||
|
try:
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute(
|
||||||
|
'UPDATE "LiteLLM_TeamTable" SET max_budget = NULL WHERE team_id = %s',
|
||||||
|
(team_id,),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
await asyncio.get_event_loop().run_in_executor(None, _write)
|
||||||
|
|
||||||
|
|
||||||
async def litellm_pin_reset_date(team_id: str, reset_at: datetime) -> None:
|
async def litellm_pin_reset_date(team_id: str, reset_at: datetime) -> None:
|
||||||
"""Pin a team's allowance reset to an exact moment (next OC payment date).
|
"""Pin a team's allowance reset to an exact moment (next OC payment date).
|
||||||
|
|
||||||
@@ -4257,20 +4343,25 @@ def next_reset_from_now() -> datetime:
|
|||||||
return datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0) + timedelta(days=30)
|
return datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0) + timedelta(days=30)
|
||||||
|
|
||||||
|
|
||||||
async def sync_team_budget_from_balance(email: str) -> float:
|
async def sync_team_budget_from_balance(email: str) -> float | None:
|
||||||
"""Apply the member's effective budget to their LiteLLM team.
|
"""Apply the member's effective budget to their LiteLLM team.
|
||||||
|
|
||||||
Effective budget = monthly allowance + credits still available
|
Effective budget = monthly allowance + credits still available
|
||||||
(credits drawn only after the allowance is exhausted; credits consumed in
|
(credits drawn only after the allowance is exhausted; credits consumed in
|
||||||
CLOSED cycles are deducted by `close_credit_cycles`). Reads the member's
|
CLOSED cycles are deducted by `close_credit_cycles`). Reads the member's
|
||||||
live spend from LiteLLM to split this cycle's spend for display only.
|
live spend from LiteLLM to split this cycle's spend for display only.
|
||||||
Returns the applied budget.
|
Returns the applied budget; None for uncapped operator accounts, whose team
|
||||||
|
cap is cleared rather than computed.
|
||||||
"""
|
"""
|
||||||
balance = get_member_balance(email)
|
balance = get_member_balance(email)
|
||||||
credits = get_credit_balance(email)
|
credits = get_credit_balance(email)
|
||||||
drawn = get_credits_drawn(email)
|
drawn = get_credits_drawn(email)
|
||||||
team_id = await litellm_get_or_create_team(email, balance)
|
team_id = await litellm_get_or_create_team(email, balance)
|
||||||
|
|
||||||
|
if (email or "").strip().lower() in UNCAPPED_EMAILS:
|
||||||
|
await litellm_clear_team_budget(team_id)
|
||||||
|
return None
|
||||||
|
|
||||||
# Live spend this cycle (DB path preferred; LiteLLM computes the reset).
|
# Live spend this cycle (DB path preferred; LiteLLM computes the reset).
|
||||||
team = get_team_budget_from_db(team_id) or {}
|
team = get_team_budget_from_db(team_id) or {}
|
||||||
team_spend = team.get("spend")
|
team_spend = team.get("spend")
|
||||||
@@ -4325,21 +4416,105 @@ def cycle_spend_from_ledger(team_id: str, start: datetime, end: datetime) -> flo
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def apply_cycle_draw(email: str, cycle_key: str, spend: float, allowance: float) -> float:
|
def credit_available_at_start(email: str, when: datetime) -> float:
|
||||||
|
"""Credit balance the member already had when a cycle began.
|
||||||
|
|
||||||
|
The ledger is the full history (purchases positive, draws negative), so its
|
||||||
|
running sum is the spendable balance at any timestamp. A pack bought while
|
||||||
|
the previous cycle was open is available at the next boundary.
|
||||||
|
"""
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT COALESCE(SUM(delta), 0) FROM credit_ledger "
|
||||||
|
"WHERE email = ? AND created_at < ?",
|
||||||
|
(email, when.strftime("%Y-%m-%d %H:%M:%S")),
|
||||||
|
).fetchone()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return float(row[0] or 0.0)
|
||||||
|
|
||||||
|
|
||||||
|
def first_credit_available(email: str, start: datetime, end: datetime) -> datetime | None:
|
||||||
|
"""First moment inside [start, end) when the member's credit balance is > 0.
|
||||||
|
|
||||||
|
Returns `start` when credits were already available at the boundary, None
|
||||||
|
when the cycle never had credits, and the purchase timestamp when a pack
|
||||||
|
arrived mid-cycle.
|
||||||
|
"""
|
||||||
|
running = credit_available_at_start(email, start)
|
||||||
|
if running > 0:
|
||||||
|
return start
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT created_at, delta FROM credit_ledger "
|
||||||
|
"WHERE email = ? AND created_at >= ? AND created_at < ? "
|
||||||
|
"ORDER BY created_at, id",
|
||||||
|
(email, start.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
end.strftime("%Y-%m-%d %H:%M:%S")),
|
||||||
|
).fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
for created_at, delta in rows:
|
||||||
|
running += float(delta or 0.0)
|
||||||
|
if running > 0:
|
||||||
|
try:
|
||||||
|
return datetime.fromisoformat(created_at).replace(tzinfo=timezone.utc)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def credit_eligible_overage(email: str, team_id: str, cycle_start: datetime,
|
||||||
|
cycle_end: datetime, allowance: float,
|
||||||
|
total_spend: float | None = None) -> float | None:
|
||||||
|
"""The part of a cycle's overage that credits could actually have covered.
|
||||||
|
|
||||||
|
Spend before the pack existed is not credit spend. With credits available
|
||||||
|
from the boundary, the whole overage is eligible. Otherwise split the cycle
|
||||||
|
at the first grant: allowance is consumed first, then credits cover the
|
||||||
|
spend after that point. Returns None when SpendLogs cannot be read.
|
||||||
|
"""
|
||||||
|
if total_spend is None:
|
||||||
|
total_spend = cycle_spend_from_ledger(team_id, cycle_start, cycle_end)
|
||||||
|
if total_spend is None:
|
||||||
|
return None
|
||||||
|
available_from_start = credit_available_at_start(email, cycle_start)
|
||||||
|
if available_from_start > 0:
|
||||||
|
return round(max(0.0, total_spend - allowance), 6)
|
||||||
|
grant_at = first_credit_available(email, cycle_start, cycle_end)
|
||||||
|
if grant_at is None:
|
||||||
|
return 0.0
|
||||||
|
if grant_at <= cycle_start:
|
||||||
|
return round(max(0.0, total_spend - allowance), 6)
|
||||||
|
spend_before = cycle_spend_from_ledger(team_id, cycle_start, grant_at)
|
||||||
|
if spend_before is None:
|
||||||
|
return None
|
||||||
|
spend_after = max(0.0, total_spend - spend_before)
|
||||||
|
allowance_left = max(0.0, allowance - spend_before)
|
||||||
|
return round(max(0.0, spend_after - allowance_left), 6)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_cycle_draw(email: str, cycle_key: str, spend: float, allowance: float,
|
||||||
|
eligible: float | None = None) -> float:
|
||||||
"""Draw a closed cycle's credit overage from a member's pack (idempotent).
|
"""Draw a closed cycle's credit overage from a member's pack (idempotent).
|
||||||
|
|
||||||
The overage is `max(0, spend − allowance)`, capped by the credits still
|
The overage is `max(0, spend − allowance)` — or the caller's
|
||||||
available. Records a NEGATIVE ledger row and bumps `credits_drawn` in one
|
`credit-eligible` figure when credits arrived mid-cycle — capped by the
|
||||||
transaction; the reference `cycle-close:<email>:<cycle>` is the dedupe key,
|
credits still available. Records a NEGATIVE ledger row and bumps
|
||||||
so a repeat call for the same cycle applies nothing. Returns the amount
|
`credits_drawn` in one transaction; the reference
|
||||||
drawn (0.0 when nothing was owed or the draw already happened).
|
`cycle-close:<email>:<cycle>` is the dedupe key, so a repeat call for the
|
||||||
|
same cycle applies nothing. Returns the amount drawn (0.0 when nothing was
|
||||||
|
owed or the draw already happened).
|
||||||
"""
|
"""
|
||||||
ref = f"cycle-close:{email}:{cycle_key}"
|
ref = f"cycle-close:{email}:{cycle_key}"
|
||||||
if credit_reference_exists(ref):
|
if credit_reference_exists(ref):
|
||||||
return 0.0
|
return 0.0
|
||||||
purchased = get_credit_balance(email)
|
purchased = get_credit_balance(email)
|
||||||
available = max(0.0, purchased - get_credits_drawn(email))
|
available = max(0.0, purchased - get_credits_drawn(email))
|
||||||
draw = round(min(max(0.0, spend - allowance), available), 6)
|
overage = max(0.0, spend - allowance) if eligible is None else eligible
|
||||||
|
draw = round(min(max(0.0, overage), available), 6)
|
||||||
if draw <= 0:
|
if draw <= 0:
|
||||||
return 0.0
|
return 0.0
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
@@ -4349,7 +4524,8 @@ def apply_cycle_draw(email: str, cycle_key: str, spend: float, allowance: float)
|
|||||||
"VALUES (?, ?, ?, ?)",
|
"VALUES (?, ?, ?, ?)",
|
||||||
(email, -draw,
|
(email, -draw,
|
||||||
f"credits used in cycle {cycle_key} "
|
f"credits used in cycle {cycle_key} "
|
||||||
f"(${spend:.2f} spend, ${allowance:.2f} allowance)",
|
f"(${spend:.2f} spend, ${allowance:.2f} allowance, "
|
||||||
|
f"${overage:.2f} credit-eligible)",
|
||||||
ref),
|
ref),
|
||||||
)
|
)
|
||||||
conn.execute(
|
conn.execute(
|
||||||
@@ -4396,6 +4572,7 @@ async def close_credit_cycles() -> dict:
|
|||||||
skipped = 0
|
skipped = 0
|
||||||
errors: list[str] = []
|
errors: list[str] = []
|
||||||
details: list[dict] = []
|
details: list[dict] = []
|
||||||
|
deferred: list[dict] = []
|
||||||
|
|
||||||
for email, anchor_day, balance, credit_balance, credits_drawn in rows:
|
for email, anchor_day, balance, credit_balance, credits_drawn in rows:
|
||||||
if not anchor_day:
|
if not anchor_day:
|
||||||
@@ -4440,22 +4617,47 @@ async def close_credit_cycles() -> dict:
|
|||||||
break
|
break
|
||||||
|
|
||||||
available = max(0.0, purchased - get_credits_drawn(email))
|
available = max(0.0, purchased - get_credits_drawn(email))
|
||||||
overage = max(0.0, spend - allowance)
|
eligible = credit_eligible_overage(email, team_id, cycle_start,
|
||||||
draw = round(min(overage, available), 6)
|
cycle_end, allowance, spend)
|
||||||
|
if eligible is None:
|
||||||
|
errors.append(f"{email}/{cycle_key}: eligibility read failed")
|
||||||
|
break
|
||||||
|
draw = round(min(eligible, available), 6)
|
||||||
if draw > 0:
|
if draw > 0:
|
||||||
drawn = apply_cycle_draw(email, cycle_key, spend, allowance)
|
drawn = apply_cycle_draw(email, cycle_key, spend, allowance,
|
||||||
|
eligible=eligible)
|
||||||
if drawn > 0:
|
if drawn > 0:
|
||||||
closed += 1
|
closed += 1
|
||||||
drawn_total += drawn
|
drawn_total += drawn
|
||||||
details.append({"email": email, "cycle": cycle_key,
|
details.append({"email": email, "cycle": cycle_key,
|
||||||
"spend": round(spend, 2), "drawn": round(drawn, 2)})
|
"spend": round(spend, 2),
|
||||||
|
"eligible": round(eligible, 2),
|
||||||
|
"drawn": round(drawn, 2)})
|
||||||
|
cycle_end = cycle_start
|
||||||
|
|
||||||
|
# Re-sync the cap only when it will not put the member under their
|
||||||
|
# ALREADY-RECORDED spend. A clawback applied mid-cycle would otherwise
|
||||||
|
# leave max_budget < spend and LiteLLM refuses every call until the
|
||||||
|
# next reset — weeks for some anchors. The draw is still recorded now;
|
||||||
|
# the cap falls at the first tick after their spend resets.
|
||||||
|
if (email or "").strip().lower() in UNCAPPED_EMAILS:
|
||||||
|
continue
|
||||||
try:
|
try:
|
||||||
applied = await sync_team_budget_from_balance(email)
|
team = get_team_budget_from_db(team_id) or {}
|
||||||
|
spend_now = team.get("spend")
|
||||||
|
cur_cap = team.get("max_budget")
|
||||||
|
eff = compute_max_budget(allowance, purchased, spend_now,
|
||||||
|
get_credits_drawn(email))
|
||||||
|
if cur_cap is not None and abs(cur_cap - eff["max_budget"]) <= 1e-9:
|
||||||
|
continue
|
||||||
|
if spend_now is None or spend_now <= eff["max_budget"] + 1e-9:
|
||||||
|
await litellm_update_team_budget(team_id, eff["max_budget"])
|
||||||
|
details.append({"email": email, "cap_applied": eff["max_budget"]})
|
||||||
|
else:
|
||||||
|
deferred.append({"email": email, "cap": eff["max_budget"],
|
||||||
|
"spend_now": round(float(spend_now), 2)})
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
errors.append(f"{email}: cap sync failed: {str(exc)[:120]}")
|
errors.append(f"{email}: cap sync failed: {str(exc)[:120]}")
|
||||||
else:
|
|
||||||
details[-1]["team_budget"] = applied
|
|
||||||
cycle_end = cycle_start
|
|
||||||
|
|
||||||
if errors:
|
if errors:
|
||||||
logger.warning("close_credit_cycles: %d error(s): %s", len(errors), "; ".join(errors[:5]))
|
logger.warning("close_credit_cycles: %d error(s): %s", len(errors), "; ".join(errors[:5]))
|
||||||
@@ -4465,6 +4667,7 @@ async def close_credit_cycles() -> dict:
|
|||||||
"closed": closed,
|
"closed": closed,
|
||||||
"credits_drawn": round(drawn_total, 2),
|
"credits_drawn": round(drawn_total, 2),
|
||||||
"skipped": skipped,
|
"skipped": skipped,
|
||||||
|
"deferred": deferred,
|
||||||
"errors": errors,
|
"errors": errors,
|
||||||
"details": details,
|
"details": details,
|
||||||
}
|
}
|
||||||
@@ -5250,6 +5453,13 @@ async def _process_opencollective_webhook(request: Request, token: str):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("Webhook: org re-provision failed for %s: %s",
|
logger.warning("Webhook: org re-provision failed for %s: %s",
|
||||||
org_email, e)
|
org_email, e)
|
||||||
|
# Org rows are skipped by the allowance reconcile, so nothing
|
||||||
|
# else would give this member an anchor day; infer it now
|
||||||
|
# rather than waiting for the next sweep.
|
||||||
|
try:
|
||||||
|
await reconcile_org_anchors()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Webhook: org anchor pass failed: %s", e)
|
||||||
else:
|
else:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Webhook: Membership payment from ORGANIZATION %s (%s) — "
|
"Webhook: Membership payment from ORGANIZATION %s (%s) — "
|
||||||
@@ -6159,6 +6369,15 @@ OPERATOR_EMAILS = {
|
|||||||
if e.strip()
|
if e.strip()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Accounts that hold NO LiteLLM spend cap: the co-op's own infrastructure, whose
|
||||||
|
# usage is a collective expense and must not be cut off mid-task. Default: the
|
||||||
|
# operator accounts; UNCAPPED_EMAILS adds (or replaces) via env.
|
||||||
|
UNCAPPED_EMAILS = (
|
||||||
|
{e.strip().lower() for e in os.environ["UNCAPPED_EMAILS"].split(",") if e.strip()}
|
||||||
|
if os.environ.get("UNCAPPED_EMAILS")
|
||||||
|
else set(OPERATOR_EMAILS)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _membership_events_for_overview(conn: sqlite3.Connection) -> tuple[list[dict], dict[str, dict]]:
|
def _membership_events_for_overview(conn: sqlite3.Connection) -> tuple[list[dict], dict[str, dict]]:
|
||||||
"""Return (newest-first event log, latest deactivation per member email)."""
|
"""Return (newest-first event log, latest deactivation per member email)."""
|
||||||
@@ -6463,11 +6682,15 @@ async def admin_overview(request: Request):
|
|||||||
"operator_all_time_spend": round(operator_all_time, 2),
|
"operator_all_time_spend": round(operator_all_time, 2),
|
||||||
# The co-op's spend, the ONE definition both apps show (see
|
# The co-op's spend, the ONE definition both apps show (see
|
||||||
# coop_spend_totals). spend_all_time spans members AND the co-op's
|
# coop_spend_totals). spend_all_time spans members AND the co-op's
|
||||||
# own accounts; own_all_time_spend is the breakout.
|
# own accounts; own_all_time_spend is the breakout, and
|
||||||
|
# own_unattributed_spend names the part of it that joins to no team
|
||||||
|
# alias (gateway overhead — historically the master-key keepalive
|
||||||
|
# pings, kept as history rather than rewritten).
|
||||||
**{
|
**{
|
||||||
k: v
|
k: v
|
||||||
for k, v in _coop_spend_totals_safe().items()
|
for k, v in _coop_spend_totals_safe().items()
|
||||||
if k in ("spend_all_time", "own_all_time_spend")
|
if k in ("spend_all_time", "own_all_time_spend",
|
||||||
|
"own_unattributed_spend")
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -6723,6 +6946,11 @@ def coop_spend_totals() -> dict:
|
|||||||
as litellm_spend_by_day(), so the cards and the money chart agree.
|
as litellm_spend_by_day(), so the cards and the money chart agree.
|
||||||
own = the co-op's own use: every team that is not a member team, plus rows
|
own = the co-op's own use: every team that is not a member team, plus rows
|
||||||
with no team at all (nothing here is a member's usage).
|
with no team at all (nothing here is a member's usage).
|
||||||
|
unattributed = the part of own that joins to NO team alias (empty alias).
|
||||||
|
Named so it is auditable rather than a silent remainder: historically
|
||||||
|
the audio keepalive pings on the master key, ~$3.21 over 16,894 rows
|
||||||
|
before the key split on 2026-11-28. Never rewritten in LiteLLM's
|
||||||
|
tables — that table is the system of record and is read-only here.
|
||||||
"""
|
"""
|
||||||
if not litellm_db_ready():
|
if not litellm_db_ready():
|
||||||
raise RuntimeError("LiteLLM DB credentials not configured")
|
raise RuntimeError("LiteLLM DB credentials not configured")
|
||||||
@@ -6739,7 +6967,7 @@ def coop_spend_totals() -> dict:
|
|||||||
rows = cur.fetchall()
|
rows = cur.fetchall()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
member = own = 0.0
|
member = own = unattributed = 0.0
|
||||||
aliases = 0
|
aliases = 0
|
||||||
for alias, spend in rows:
|
for alias, spend in rows:
|
||||||
val = float(spend or 0.0)
|
val = float(spend or 0.0)
|
||||||
@@ -6748,10 +6976,13 @@ def coop_spend_totals() -> dict:
|
|||||||
member += val
|
member += val
|
||||||
else:
|
else:
|
||||||
own += val
|
own += val
|
||||||
|
if not str(alias or "").strip():
|
||||||
|
unattributed += val
|
||||||
return {
|
return {
|
||||||
"spend_all_time": round(member + own, 2),
|
"spend_all_time": round(member + own, 2),
|
||||||
"member_all_time_spend": round(member, 2),
|
"member_all_time_spend": round(member, 2),
|
||||||
"own_all_time_spend": round(own, 2),
|
"own_all_time_spend": round(own, 2),
|
||||||
|
"own_unattributed_spend": round(unattributed, 2),
|
||||||
"aliases": aliases,
|
"aliases": aliases,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6885,6 +7116,7 @@ async def _compute_money_payload() -> dict:
|
|||||||
# The member-owned vs co-op's-own split of that same all-time spend,
|
# The member-owned vs co-op's-own split of that same all-time spend,
|
||||||
# from the one shared definition.
|
# from the one shared definition.
|
||||||
"own_all_time_spend": (_coop_split := _coop_spend_totals_safe()).get("own_all_time_spend"),
|
"own_all_time_spend": (_coop_split := _coop_spend_totals_safe()).get("own_all_time_spend"),
|
||||||
|
"own_unattributed_spend": _coop_split.get("own_unattributed_spend"),
|
||||||
"member_all_time_spend": _coop_split.get("member_all_time_spend"),
|
"member_all_time_spend": _coop_split.get("member_all_time_spend"),
|
||||||
},
|
},
|
||||||
"sources": {
|
"sources": {
|
||||||
@@ -7617,13 +7849,20 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
|
|||||||
credits_drawn = get_credits_drawn(email)
|
credits_drawn = get_credits_drawn(email)
|
||||||
spend = 0.0
|
spend = 0.0
|
||||||
reset_at = None
|
reset_at = None
|
||||||
|
# Default: the member's own allowance + credits still available. An
|
||||||
|
# uncapped operator account has no team max_budget (NULL); keep this figure
|
||||||
|
# for the dashboard's arithmetic and say plainly that there is no cap.
|
||||||
|
balance = allowance + max(0.0, credits - credits_drawn)
|
||||||
|
uncapped = False
|
||||||
|
|
||||||
# Fast path: direct Postgres reads.
|
# Fast path: direct Postgres reads.
|
||||||
if litellm_db_ready():
|
if litellm_db_ready():
|
||||||
try:
|
try:
|
||||||
team = get_team_budget_from_db(team_id)
|
team = get_team_budget_from_db(team_id)
|
||||||
if team:
|
if team:
|
||||||
if team["max_budget"] is not None:
|
if team["max_budget"] is None:
|
||||||
|
uncapped = True
|
||||||
|
else:
|
||||||
balance = float(team["max_budget"])
|
balance = float(team["max_budget"])
|
||||||
spend = float(team["spend"] or 0.0)
|
spend = float(team["spend"] or 0.0)
|
||||||
reset_at = team["budget_reset_at"]
|
reset_at = team["budget_reset_at"]
|
||||||
@@ -7668,6 +7907,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
|
|||||||
return {
|
return {
|
||||||
"email": email,
|
"email": email,
|
||||||
"guest": is_guest_account(email),
|
"guest": is_guest_account(email),
|
||||||
|
"uncapped": uncapped,
|
||||||
"balance": balance,
|
"balance": balance,
|
||||||
"allowance": allowance,
|
"allowance": allowance,
|
||||||
"credits": credits,
|
"credits": credits,
|
||||||
@@ -7697,7 +7937,11 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
|
|||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
for t in r.json():
|
for t in r.json():
|
||||||
if t.get("team_id") == team_id:
|
if t.get("team_id") == team_id:
|
||||||
balance = float(t.get("max_budget") or balance)
|
mb = t.get("max_budget")
|
||||||
|
if mb is None:
|
||||||
|
uncapped = True
|
||||||
|
else:
|
||||||
|
balance = float(mb)
|
||||||
spend = float(t.get("spend") or 0.0)
|
spend = float(t.get("spend") or 0.0)
|
||||||
reset_at = t.get("budget_reset_at")
|
reset_at = t.get("budget_reset_at")
|
||||||
break
|
break
|
||||||
@@ -7751,6 +7995,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
|
|||||||
return {
|
return {
|
||||||
"email": email,
|
"email": email,
|
||||||
"guest": is_guest_account(email),
|
"guest": is_guest_account(email),
|
||||||
|
"uncapped": uncapped,
|
||||||
"balance": balance,
|
"balance": balance,
|
||||||
"allowance": allowance,
|
"allowance": allowance,
|
||||||
"credits": credits,
|
"credits": credits,
|
||||||
@@ -10644,6 +10889,159 @@ async def derive_member_sources() -> dict:
|
|||||||
return {"checked": len(stale), "flipped": flipped}
|
return {"checked": len(stale), "flipped": flipped}
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch_org_join_days() -> dict[str, datetime]:
|
||||||
|
"""org slug -> the date that ORGANIZATION joined the collective on OC.
|
||||||
|
|
||||||
|
Organizations never expose an email, so fetch_member_index() drops them and
|
||||||
|
the allowance reconcile skips org-backed rows. That is how an org member ends
|
||||||
|
up with no `anchor_day` — and a credit cycle that can never close.
|
||||||
|
"""
|
||||||
|
if not OC_PERSONAL_TOKEN:
|
||||||
|
raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch organization members")
|
||||||
|
out: dict[str, datetime] = {}
|
||||||
|
offset = 0
|
||||||
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||||
|
for _ in range(20): # same 100/page cap as the individual walk
|
||||||
|
query = (
|
||||||
|
'{ collective(slug: "%s") { members(limit: 100, offset: %d) { totalCount '
|
||||||
|
"nodes { role createdAt tier { name } account { slug type } } } } }"
|
||||||
|
% (OC_COLLECTIVE_SLUG, offset)
|
||||||
|
)
|
||||||
|
r = await _oc_graphql_post(
|
||||||
|
client, {"query": query}, {"Personal-Token": OC_PERSONAL_TOKEN},
|
||||||
|
)
|
||||||
|
if r.status_code != 200:
|
||||||
|
raise RuntimeError(f"OC organization fetch failed: HTTP {r.status_code}")
|
||||||
|
members = ((r.json().get("data") or {}).get("collective") or {}).get("members") or {}
|
||||||
|
total = members.get("totalCount") or 0
|
||||||
|
nodes = members.get("nodes") or []
|
||||||
|
for n in nodes:
|
||||||
|
acct = n.get("account") or {}
|
||||||
|
slug = (acct.get("slug") or "").strip().lower()
|
||||||
|
if not slug or (acct.get("type") or "").upper() != "ORGANIZATION":
|
||||||
|
continue
|
||||||
|
joined = _parse_oc_dt(n.get("createdAt"))
|
||||||
|
if joined and slug not in out:
|
||||||
|
out[slug] = joined # the join date never moves; first sight wins
|
||||||
|
offset += len(nodes)
|
||||||
|
if not nodes or offset >= total:
|
||||||
|
return out
|
||||||
|
raise RuntimeError("OC organization pagination exceeded 20 pages")
|
||||||
|
|
||||||
|
|
||||||
|
async def pin_member_reset_dates() -> dict:
|
||||||
|
"""Keep every active member's allowance reset on their join day.
|
||||||
|
|
||||||
|
LiteLLM's reset job special-cases budget_duration "30d" as "monthly on the
|
||||||
|
1st": after a reset it rewrites budget_reset_at to the first of the next
|
||||||
|
month, so the NEXT renewal would land on the calendar month instead of the
|
||||||
|
member's join day. The dues reconcile repins only members whose payment it
|
||||||
|
verified; manual and org-backed rows are skipped, so the drift can stick.
|
||||||
|
Pin every active non-guest row from its anchor day; write only when the
|
||||||
|
stored date differs, so this is cheap and idempotent.
|
||||||
|
"""
|
||||||
|
conn = get_db()
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT email, anchor_day FROM members WHERE active = 1 "
|
||||||
|
"AND account_type != 'guest' AND anchor_day IS NOT NULL"
|
||||||
|
).fetchall()
|
||||||
|
conn.close()
|
||||||
|
if not rows:
|
||||||
|
return {"checked": 0, "pinned": 0, "changes": []}
|
||||||
|
anchors = {email: _clamp_anchor_day(anchor) for email, anchor in rows}
|
||||||
|
|
||||||
|
try:
|
||||||
|
pg = _pg_connect()
|
||||||
|
try:
|
||||||
|
with pg.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
'SELECT team_alias, team_id, budget_reset_at '
|
||||||
|
'FROM "LiteLLM_TeamTable" WHERE team_alias LIKE %s',
|
||||||
|
("member:%",),
|
||||||
|
)
|
||||||
|
teams = cur.fetchall()
|
||||||
|
finally:
|
||||||
|
pg.close()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("pin_member_reset_dates: team read failed: %s", exc)
|
||||||
|
return {"checked": len(rows), "pinned": 0, "changes": [],
|
||||||
|
"error": str(exc)[:200]}
|
||||||
|
|
||||||
|
changes = []
|
||||||
|
for alias, team_id, reset_at in teams:
|
||||||
|
email = (alias or "")[7:]
|
||||||
|
anchor = anchors.get(email)
|
||||||
|
if not anchor:
|
||||||
|
continue
|
||||||
|
expected = next_reset_for_anchor_day(anchor)
|
||||||
|
if reset_at is not None and reset_at.date() == expected.date():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
await litellm_pin_reset_date(team_id, expected)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("pin_member_reset_dates: pin failed for %s: %s", email, exc)
|
||||||
|
continue
|
||||||
|
changes.append({"email": email, "anchor_day": anchor,
|
||||||
|
"from": str(reset_at)[:10] if reset_at else None,
|
||||||
|
"to": expected.date().isoformat()})
|
||||||
|
return {"checked": len(rows), "pinned": len(changes), "changes": changes}
|
||||||
|
|
||||||
|
|
||||||
|
async def reconcile_org_anchors() -> dict:
|
||||||
|
"""Give every org-backed member an anchor day from the ORG's OC join date.
|
||||||
|
|
||||||
|
The allowance reconcile SKIPS rows with `org_slug` (dues are paid by an
|
||||||
|
Organization, not by an individual order), so nothing ever set an anchor day
|
||||||
|
for them and `close_credit_cycles` skipped them forever — their credit packs
|
||||||
|
regenerated every month like everyone else's did before issue #12.
|
||||||
|
|
||||||
|
Anchor = day-of-month of the organization's OC membership `createdAt`,
|
||||||
|
clamped to 1..28; the team reset is pinned to its next occurrence. Idempotent:
|
||||||
|
only rows whose `anchor_day` is NULL are touched. An org with no membership
|
||||||
|
record on OC is REPORTED, never guessed — a wrong anchor moves a member's
|
||||||
|
billing boundary.
|
||||||
|
"""
|
||||||
|
conn = get_db()
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT email, org_slug FROM members "
|
||||||
|
"WHERE org_slug IS NOT NULL AND TRIM(org_slug) != '' AND anchor_day IS NULL"
|
||||||
|
).fetchall()
|
||||||
|
conn.close()
|
||||||
|
if not rows:
|
||||||
|
return {"checked": 0, "anchored": [], "unresolved": []}
|
||||||
|
|
||||||
|
try:
|
||||||
|
joins = await fetch_org_join_days()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("reconcile_org_anchors: org fetch failed: %s", exc)
|
||||||
|
return {"checked": len(rows), "anchored": [], "unresolved": [],
|
||||||
|
"error": str(exc)[:200]}
|
||||||
|
|
||||||
|
anchored: list[dict] = []
|
||||||
|
unresolved: list[dict] = []
|
||||||
|
for email, org_slug in rows:
|
||||||
|
joined = joins.get((org_slug or "").strip().lower())
|
||||||
|
if not joined:
|
||||||
|
unresolved.append({"email": email, "org_slug": org_slug})
|
||||||
|
continue
|
||||||
|
anchor = _clamp_anchor_day(joined.day)
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
conn.execute("UPDATE members SET anchor_day = ? WHERE email = ?", (anchor, email))
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
try:
|
||||||
|
team_id = await litellm_team_id_for_email(email)
|
||||||
|
if team_id:
|
||||||
|
await litellm_pin_reset_date(team_id, next_reset_for_anchor_day(anchor))
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.warning("reconcile_org_anchors: reset pin failed for %s: %s", email, exc)
|
||||||
|
anchored.append({"email": email, "org_slug": org_slug, "anchor_day": anchor,
|
||||||
|
"org_joined": joined.date().isoformat()})
|
||||||
|
return {"checked": len(rows), "anchored": anchored, "unresolved": unresolved}
|
||||||
|
|
||||||
|
|
||||||
FX_POLICY_EUR_USD = float(os.environ.get("FX_POLICY_EUR_USD", "1.0975") or 1.0975)
|
FX_POLICY_EUR_USD = float(os.environ.get("FX_POLICY_EUR_USD", "1.0975") or 1.0975)
|
||||||
FX_ALERT_PCT = float(os.environ.get("FX_ALERT_PCT", "2.0") or 2.0)
|
FX_ALERT_PCT = float(os.environ.get("FX_ALERT_PCT", "2.0") or 2.0)
|
||||||
|
|
||||||
@@ -10745,6 +11143,24 @@ async def admin_sweep(request: Request):
|
|||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
result["allowances"] = {"error": str(exc)[:200]}
|
result["allowances"] = {"error": str(exc)[:200]}
|
||||||
|
|
||||||
|
# Org-backed members get no anchor day from the allowance reconcile (it skips
|
||||||
|
# them); infer it from the organization's OC membership date so their credit
|
||||||
|
# cycles can close. Idempotent, and reports orgs with no OC record rather than
|
||||||
|
# guessing a boundary. Wrapped so it can never break reconciliation.
|
||||||
|
try:
|
||||||
|
result["org_anchors"] = await reconcile_org_anchors()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
result["org_anchors"] = {"error": str(exc)[:200]}
|
||||||
|
|
||||||
|
# LiteLLM rewrites budget_reset_at to the 1st of the next month whenever a
|
||||||
|
# "30d" team resets, so any row the dues reconcile skips (manual, org-backed)
|
||||||
|
# would drift off its join day. Pin every active member's reset from its
|
||||||
|
# anchor day; idempotent and writes only on a mismatch.
|
||||||
|
try:
|
||||||
|
result["reset_dates"] = await pin_member_reset_dates()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
result["reset_dates"] = {"error": str(exc)[:200]}
|
||||||
|
|
||||||
# Allowance-shortfall credits: OC's billing-day alignment truncates some paid
|
# Allowance-shortfall credits: OC's billing-day alignment truncates some paid
|
||||||
# cycles. Rides the same sweep so a new member is compensated automatically;
|
# cycles. Rides the same sweep so a new member is compensated automatically;
|
||||||
# credits are idempotent on the OC charge reference. Wrapped so it can never
|
# credits are idempotent on the OC charge reference. Wrapped so it can never
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Relay Loomio reply-by-email messages from Cloudron mail into Loomio.
|
||||||
|
|
||||||
|
Loomio's notification Reply-To addresses look like
|
||||||
|
d=<discussion>&u=<user>&k=<email_api_key>@forum-reply.inference.coop
|
||||||
|
Cloudron's Loomio package has no inbound mail receiver (upstream Haraka needs
|
||||||
|
port 25, which Cloudron cannot expose), so this job polls the catch-all mailbox
|
||||||
|
and hands each raw message to Loomio's ActionMailbox relay endpoint.
|
||||||
|
|
||||||
|
Runs from the Cloudron scheduler addon. Env comes from the portal app's launch
|
||||||
|
environment (same secrets the app process sees).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import imaplib
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from urllib.error import HTTPError
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
|
||||||
|
|
||||||
|
def required(name: str) -> str:
|
||||||
|
value = os.environ.get(name)
|
||||||
|
if not value:
|
||||||
|
raise SystemExit(f"loomio-inbound: {name} is not set")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
IMAP_HOST = os.environ.get("LOOMIO_INBOUND_IMAP_HOST", "my.inference.coop")
|
||||||
|
IMAP_PORT = int(os.environ.get("LOOMIO_INBOUND_IMAP_PORT", "993"))
|
||||||
|
IMAP_USER = required("LOOMIO_INBOUND_IMAP_USERNAME")
|
||||||
|
IMAP_PASSWORD = required("LOOMIO_INBOUND_IMAP_PASSWORD")
|
||||||
|
RELAY_URL = os.environ.get(
|
||||||
|
"LOOMIO_INBOUND_RELAY_URL",
|
||||||
|
"https://forum.inference.coop/rails/action_mailbox/relay/inbound_emails",
|
||||||
|
)
|
||||||
|
RELAY_PASSWORD = required("LOOMIO_INBOUND_RELAY_PASSWORD")
|
||||||
|
MAX_PER_RUN = int(os.environ.get("LOOMIO_INBOUND_MAX", "50"))
|
||||||
|
KEEP_DAYS = int(os.environ.get("LOOMIO_INBOUND_KEEP_DAYS", "30"))
|
||||||
|
|
||||||
|
|
||||||
|
def relay(raw: bytes) -> int:
|
||||||
|
auth = base64.b64encode(f"actionmailbox:{RELAY_PASSWORD}".encode()).decode()
|
||||||
|
req = Request(
|
||||||
|
RELAY_URL,
|
||||||
|
data=raw,
|
||||||
|
method="POST",
|
||||||
|
headers={
|
||||||
|
"Authorization": f"Basic {auth}",
|
||||||
|
"Content-Type": "message/rfc822",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
with urlopen(req, timeout=60) as resp:
|
||||||
|
return resp.status
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_raw(imap: imaplib.IMAP4_SSL, uid: str) -> bytes:
|
||||||
|
typ, data = imap.uid("FETCH", uid, "(BODY.PEEK[])")
|
||||||
|
if typ != "OK":
|
||||||
|
raise RuntimeError(f"FETCH failed: {typ}")
|
||||||
|
for item in data or []:
|
||||||
|
if isinstance(item, tuple) and len(item) >= 2 and isinstance(item[1], (bytes, bytearray)):
|
||||||
|
return bytes(item[1])
|
||||||
|
raise RuntimeError("FETCH returned no message body")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
imap = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT, ssl_context=ctx)
|
||||||
|
try:
|
||||||
|
imap.login(IMAP_USER, IMAP_PASSWORD)
|
||||||
|
typ, data = imap.select("INBOX")
|
||||||
|
if typ != "OK":
|
||||||
|
raise RuntimeError(f"SELECT INBOX failed: {typ}")
|
||||||
|
|
||||||
|
typ, data = imap.uid("SEARCH", "UNSEEN")
|
||||||
|
if typ != "OK":
|
||||||
|
raise RuntimeError(f"SEARCH UNSEEN failed: {typ}")
|
||||||
|
uids = (data[0].split() if data and data[0] else [])[:MAX_PER_RUN]
|
||||||
|
print(f"loomio-inbound: {len(uids)} unseen message(s)")
|
||||||
|
|
||||||
|
relayed = 0
|
||||||
|
for uid in uids:
|
||||||
|
try:
|
||||||
|
raw = fetch_raw(imap, uid.decode())
|
||||||
|
status = relay(raw)
|
||||||
|
imap.uid("STORE", uid.decode(), "+FLAGS", "(\\Seen)")
|
||||||
|
relayed += 1
|
||||||
|
print(f"loomio-inbound: uid {uid.decode()} relayed ({status}, {len(raw)} bytes)")
|
||||||
|
except HTTPError as exc:
|
||||||
|
print(
|
||||||
|
f"loomio-inbound: uid {uid.decode()} relay HTTP {exc.code}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
if exc.code in (401, 403):
|
||||||
|
return 1
|
||||||
|
except Exception as exc: # keep the message unseen for the next tick
|
||||||
|
print(
|
||||||
|
f"loomio-inbound: uid {uid.decode()} failed: "
|
||||||
|
f"{type(exc).__name__}: {exc}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
cutoff = (datetime.now(timezone.utc) - timedelta(days=KEEP_DAYS)).strftime("%d-%b-%Y")
|
||||||
|
typ, data = imap.uid("SEARCH", f"SEEN BEFORE {cutoff}")
|
||||||
|
old = data[0].split() if typ == "OK" and data and data[0] else []
|
||||||
|
for uid in old:
|
||||||
|
imap.uid("STORE", uid.decode(), "+FLAGS", "(\\Deleted)")
|
||||||
|
if old:
|
||||||
|
imap.expunge()
|
||||||
|
print(f"loomio-inbound: relayed={relayed} purged={len(old)}")
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"loomio-inbound: purge skipped: {type(exc).__name__}: {exc}", file=sys.stderr)
|
||||||
|
|
||||||
|
return 0
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
imap.logout()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -77,6 +77,10 @@ try:
|
|||||||
f"member side is the member: teams ($10.005 + $5.005 -> 15.01, got {t['member_all_time_spend']})")
|
f"member side is the member: teams ($10.005 + $5.005 -> 15.01, got {t['member_all_time_spend']})")
|
||||||
check(t["own_all_time_spend"] == 2.59,
|
check(t["own_all_time_spend"] == 2.59,
|
||||||
f"own side is everything else: agents, sandboxes, unattributed (got {t['own_all_time_spend']})")
|
f"own side is everything else: agents, sandboxes, unattributed (got {t['own_all_time_spend']})")
|
||||||
|
check(t["own_unattributed_spend"] == 1.07,
|
||||||
|
f"rows that join to no team alias are named, not left as a silent remainder (got {t['own_unattributed_spend']})")
|
||||||
|
check(t["own_unattributed_spend"] <= t["own_all_time_spend"],
|
||||||
|
"unattributed is a part of own, never added on top of the total")
|
||||||
check(t["spend_all_time"] == round(t["member_all_time_spend"] + t["own_all_time_spend"], 2),
|
check(t["spend_all_time"] == round(t["member_all_time_spend"] + t["own_all_time_spend"], 2),
|
||||||
"total == member + own, so no dollar is counted twice or dropped")
|
"total == member + own, so no dollar is counted twice or dropped")
|
||||||
check(t["spend_all_time"] == round(sum(r[1] for r in ROWS), 2),
|
check(t["spend_all_time"] == round(sum(r[1] for r in ROWS), 2),
|
||||||
|
|||||||
@@ -32,8 +32,8 @@ for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
|
|||||||
break
|
break
|
||||||
|
|
||||||
from app.main import ( # noqa: E402
|
from app.main import ( # noqa: E402
|
||||||
_prev_month, apply_cycle_draw, compute_max_budget, cycle_start_for_anchor_day,
|
_prev_month, add_credits, apply_cycle_draw, compute_max_budget,
|
||||||
get_credit_balance, get_credits_drawn, get_db,
|
cycle_start_for_anchor_day, get_credit_balance, get_credits_drawn, get_db,
|
||||||
)
|
)
|
||||||
|
|
||||||
failures = 0
|
failures = 0
|
||||||
@@ -147,6 +147,60 @@ check_near("no overage, no draw",
|
|||||||
apply_cycle_draw("under@example.com", "2026-10-01", spend=9.0, allowance=15.0), 0.0)
|
apply_cycle_draw("under@example.com", "2026-10-01", spend=9.0, allowance=15.0), 0.0)
|
||||||
check_near("balance untouched", get_credits_drawn("under@example.com"), 0.0)
|
check_near("balance untouched", get_credits_drawn("under@example.com"), 0.0)
|
||||||
|
|
||||||
|
# --- a clawback that would land under recorded spend is DEFERRED ------------
|
||||||
|
import asyncio # noqa: E402
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
now = m.datetime.now(m.timezone.utc)
|
||||||
|
anchor = now.day if now.day <= 28 else 28
|
||||||
|
conn = get_db()
|
||||||
|
m._ensure_allowance_tables(conn) # adds anchor_day
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance, anchor_day) "
|
||||||
|
"VALUES ('defer@example.com', '', 1, 'member', 15.0, 20.0, ?)", (anchor,))
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
||||||
|
"VALUES ('defer@example.com', 20.0, 'pack (test)', 'test-pack', '2026-10-01 00:00:00')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
state = {"spend": 40.0, "cap": 35.0}
|
||||||
|
applied = []
|
||||||
|
|
||||||
|
async def fake_team(email):
|
||||||
|
return "team:defer" if email == "defer@example.com" else None
|
||||||
|
|
||||||
|
async def fake_update(team_id, budget):
|
||||||
|
applied.append(budget)
|
||||||
|
state["cap"] = budget
|
||||||
|
|
||||||
|
m.litellm_team_id_for_email = fake_team
|
||||||
|
m.litellm_update_team_budget = fake_update
|
||||||
|
m.get_team_budget_from_db = lambda tid: {"spend": state["spend"], "max_budget": state["cap"],
|
||||||
|
"budget_reset_at": None}
|
||||||
|
m.cycle_spend_from_ledger = lambda tid, a, b: 40.0
|
||||||
|
m.CREDIT_CLOSE_FROM = "2026-01-01"
|
||||||
|
|
||||||
|
r1 = asyncio.run(m.close_credit_cycles())
|
||||||
|
check_near("draw recorded even while the cap is deferred", get_credits_drawn("defer@example.com"), 20.0)
|
||||||
|
check("cap NOT lowered under recorded spend",
|
||||||
|
any(d["email"] == "defer@example.com" for d in r1["deferred"]), True)
|
||||||
|
check("no cap push while spend > new cap", applied, [])
|
||||||
|
|
||||||
|
state["spend"] = 0.0 # what LiteLLM does at the member's reset
|
||||||
|
r2 = asyncio.run(m.close_credit_cycles())
|
||||||
|
check("cap applied once spend resets", applied, [15.0])
|
||||||
|
check("no second draw on the same cycle", r2["credits_drawn"], 0.0)
|
||||||
|
|
||||||
|
# --- lowering a pack below what was drawn must not swallow NEW credits ----
|
||||||
|
add_credits("small@example.com", -10.0, reason="admin correction (test)")
|
||||||
|
check_near("drawn follows the pack down when it is reduced", get_credits_drawn("small@example.com"), 0.0)
|
||||||
|
check_near("balance reduced to zero", get_credit_balance("small@example.com"), 0.0)
|
||||||
|
add_credits("small@example.com", 5.0, reason="new pack (test)")
|
||||||
|
check_near("a new pack is fully available after the correction",
|
||||||
|
compute_max_budget(15, get_credit_balance("small@example.com"), 0.0,
|
||||||
|
get_credits_drawn("small@example.com"))["credits_remaining"], 5.0)
|
||||||
|
|
||||||
print()
|
print()
|
||||||
if failures:
|
if failures:
|
||||||
print(f"{failures} FAILURE(S)")
|
print(f"{failures} FAILURE(S)")
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests: a cycle draw may only charge spend credits could cover.
|
||||||
|
|
||||||
|
A pack bought mid-cycle must not be charged for spend incurred before it
|
||||||
|
existed. Reproduces the consensus_polo100 case: $27.81 spent before the $10
|
||||||
|
pack arrived, then $0.62 after it; the eligible draw is $0.62, not $10.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="creditelig-test-"), "members.db")
|
||||||
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
|
||||||
|
|
||||||
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
||||||
|
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
|
||||||
|
sys.path.insert(0, _cand)
|
||||||
|
break
|
||||||
|
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
failures = 0
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, got, want):
|
||||||
|
global failures
|
||||||
|
ok = got == want
|
||||||
|
if not ok:
|
||||||
|
failures += 1
|
||||||
|
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
if not ok:
|
||||||
|
print(f" got {got!r}\n want {want!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def check_near(name, got, want):
|
||||||
|
global failures
|
||||||
|
ok = round(float(got), 6) == round(float(want), 6)
|
||||||
|
if not ok:
|
||||||
|
failures += 1
|
||||||
|
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
if not ok:
|
||||||
|
print(f" got {got!r}\n want {want!r}")
|
||||||
|
|
||||||
|
|
||||||
|
conn = m.get_db()
|
||||||
|
m._ensure_allowance_tables(conn) # adds anchor_day
|
||||||
|
for email, purchased, anchor in [
|
||||||
|
("midcycle@example.com", 10.0, 15),
|
||||||
|
("carried@example.com", 50.0, 15),
|
||||||
|
("none@example.com", 0.0, 15),
|
||||||
|
("partial@example.com", 20.0, 15)]:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, balance, "
|
||||||
|
"credit_balance, credits_drawn, anchor_day) VALUES (?, '', 1, 'member', 15.0, ?, 0, ?)",
|
||||||
|
(email, purchased, anchor))
|
||||||
|
|
||||||
|
# Pack bought inside the cycle, after the allowance had already been overspent.
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
||||||
|
"VALUES ('midcycle@example.com', 10.0, 'pack', 'pack-mid', '2026-11-12 13:05:26')")
|
||||||
|
# Pack held from before the cycle.
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
||||||
|
"VALUES ('carried@example.com', 50.0, 'pack', 'pack-carry', '2026-09-20 10:00:00')")
|
||||||
|
# Pack arrives when only part of the allowance has been used.
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
||||||
|
"VALUES ('partial@example.com', 20.0, 'pack', 'pack-part', '2026-10-20 12:00:00')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
CS = datetime(2026, 10, 15, tzinfo=timezone.utc)
|
||||||
|
CE = datetime(2026, 11, 15, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
# Spend windows for the mid-cycle member: 27.81376 before the pack, 0.624698 after.
|
||||||
|
def fake_spend(team_id, start, end):
|
||||||
|
if team_id == "t-mid":
|
||||||
|
if end.day == 12 and end.month == 11:
|
||||||
|
return 27.81376
|
||||||
|
if start == CS and end == CE:
|
||||||
|
return 28.438458
|
||||||
|
if team_id == "t-partial" and start == CS and end == datetime(2026, 10, 20, 12, tzinfo=timezone.utc):
|
||||||
|
return 5.0
|
||||||
|
return None
|
||||||
|
|
||||||
|
m.cycle_spend_from_ledger = fake_spend
|
||||||
|
|
||||||
|
# mid-cycle pack: only spend after the pack is eligible
|
||||||
|
got = m.credit_eligible_overage("midcycle@example.com", "t-mid", CS, CE, 15.0, 28.438458)
|
||||||
|
check_near("mid-cycle pack is not charged for earlier spend", got, 0.624698)
|
||||||
|
|
||||||
|
# pack carried in: whole overage is eligible
|
||||||
|
got = m.credit_eligible_overage("carried@example.com", "t-carry", CS, CE, 15.0, 28.438458)
|
||||||
|
check_near("credits at cycle start cover the whole overage", got, 13.438458)
|
||||||
|
|
||||||
|
# no credits: nothing eligible
|
||||||
|
got = m.credit_eligible_overage("none@example.com", "t-none", CS, CE, 15.0, 28.438458)
|
||||||
|
check_near("no credits means no eligible draw", got, 0.0)
|
||||||
|
|
||||||
|
# partial allowance left: overage above what remains is eligible
|
||||||
|
got = m.credit_eligible_overage("partial@example.com", "t-partial", CS, CE, 15.0, 20.0)
|
||||||
|
check_near("allowance is consumed before credits", got, 5.0)
|
||||||
|
|
||||||
|
# the eligible figure drives the draw, and the replay still draws nothing
|
||||||
|
drawn = m.apply_cycle_draw("midcycle@example.com", "2026-10-15", 28.438458, 15.0, eligible=0.624698)
|
||||||
|
check_near("draw uses the credit-eligible overage", drawn, 0.624698)
|
||||||
|
check_near("credits_drawn records only that amount", m.get_credits_drawn("midcycle@example.com"), 0.624698)
|
||||||
|
check_near("purchased total is unchanged", m.get_credit_balance("midcycle@example.com"), 10.0)
|
||||||
|
check_near("replay draws nothing",
|
||||||
|
m.apply_cycle_draw("midcycle@example.com", "2026-10-15", 28.438458, 15.0, eligible=0.624698), 0.0)
|
||||||
|
|
||||||
|
print()
|
||||||
|
if failures:
|
||||||
|
print(f"{failures} FAILURE(S)")
|
||||||
|
sys.exit(1)
|
||||||
|
print("all checks passed")
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests: guest conversion carries only UNSPENT credit.
|
||||||
|
|
||||||
|
Runnable:
|
||||||
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_guest_conversion_draw.py
|
||||||
|
* from the repo root, on a host that has the app's dependencies
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
A guest has no monthly cycle, so nothing ever drew their spend against the
|
||||||
|
$2 pack. Converting a guest kept the full $2 credit_balance, handing back
|
||||||
|
credits already used — while guest-access.md promises only the UNSPENT
|
||||||
|
credit carries over. record_guest_conversion_draw() records the consumed
|
||||||
|
part as a draw, deduped on a ledger reference.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="guestdraw-test-"), "members.db")
|
||||||
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
|
||||||
|
|
||||||
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
||||||
|
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
|
||||||
|
sys.path.insert(0, _cand)
|
||||||
|
break
|
||||||
|
|
||||||
|
from app.main import ( # noqa: E402
|
||||||
|
compute_max_budget, get_credit_balance, get_credits_drawn, get_db,
|
||||||
|
record_guest_conversion_draw,
|
||||||
|
)
|
||||||
|
|
||||||
|
failures = 0
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, got, want):
|
||||||
|
global failures
|
||||||
|
ok = got == want
|
||||||
|
if not ok:
|
||||||
|
failures += 1
|
||||||
|
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
if not ok:
|
||||||
|
print(f" got {got!r}\n want {want!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def check_near(name, got, want):
|
||||||
|
global failures
|
||||||
|
ok = round(float(got), 6) == round(float(want), 6)
|
||||||
|
if not ok:
|
||||||
|
failures += 1
|
||||||
|
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
if not ok:
|
||||||
|
print(f" got {got!r}\n want {want!r}")
|
||||||
|
|
||||||
|
|
||||||
|
conn = get_db()
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
|
||||||
|
"VALUES ('g1@example.com', '', 1, 'guest', 0.0, 2.0)")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
|
||||||
|
"VALUES ('g2@example.com', '', 1, 'guest', 0.0, 2.0)")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
used = record_guest_conversion_draw("g1@example.com", 1.9)
|
||||||
|
check_near("consumed guest spend is drawn", used, 1.9)
|
||||||
|
check_near("credits_drawn records it", get_credits_drawn("g1@example.com"), 1.9)
|
||||||
|
check_near("credit_balance stays the purchased total", get_credit_balance("g1@example.com"), 2.0)
|
||||||
|
check_near("only the unspent credit is available",
|
||||||
|
compute_max_budget(15, 2, 0.0, get_credits_drawn("g1@example.com"))["credits_remaining"], 0.1)
|
||||||
|
|
||||||
|
check_near("a replay draws nothing", record_guest_conversion_draw("g1@example.com", 1.9), 0.0)
|
||||||
|
check_near("credits_drawn unchanged by replay", get_credits_drawn("g1@example.com"), 1.9)
|
||||||
|
|
||||||
|
check_near("spend above the pack is capped", record_guest_conversion_draw("g2@example.com", 5.0), 2.0)
|
||||||
|
check_near("pack fully drawn", get_credits_drawn("g2@example.com"), 2.0)
|
||||||
|
check_near("no credit left", compute_max_budget(15, 2, 0.0, 2.0)["credits_remaining"], 0.0)
|
||||||
|
|
||||||
|
check_near("zero spend draws nothing", record_guest_conversion_draw("g1@example.com", 0.0), 0.0)
|
||||||
|
|
||||||
|
print()
|
||||||
|
if failures:
|
||||||
|
print(f"{failures} FAILURE(S)")
|
||||||
|
sys.exit(1)
|
||||||
|
print("all checks passed")
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests for org-backed anchor days.
|
||||||
|
|
||||||
|
Runnable:
|
||||||
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_org_anchors.py
|
||||||
|
* from the repo root, on a host that has the app's dependencies
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
The allowance reconcile SKIPS rows with `org_slug` (dues are paid by an OC
|
||||||
|
Organization, not an individual order), so org-backed members never got an
|
||||||
|
`anchor_day` — and close_credit_cycles skipped them forever, restoring their
|
||||||
|
credit packs every month. The fix infers the anchor from the ORGANIZATION's
|
||||||
|
OC membership createdAt. Covered:
|
||||||
|
- anchor = org join day, clamped to 28
|
||||||
|
- the team reset is pinned to the next occurrence
|
||||||
|
- idempotent: a second pass touches nothing
|
||||||
|
- an org with no OC membership record is reported, never guessed
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="organchor-test-"), "members.db")
|
||||||
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
|
||||||
|
|
||||||
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
||||||
|
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
|
||||||
|
sys.path.insert(0, _cand)
|
||||||
|
break
|
||||||
|
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
failures = 0
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, got, want):
|
||||||
|
global failures
|
||||||
|
ok = got == want
|
||||||
|
if not ok:
|
||||||
|
failures += 1
|
||||||
|
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
if not ok:
|
||||||
|
print(f" got {got!r}\n want {want!r}")
|
||||||
|
|
||||||
|
|
||||||
|
pins = []
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_org_joins():
|
||||||
|
return {
|
||||||
|
"cosmos": datetime(2026, 10, 15, 23, 52, tzinfo=timezone.utc),
|
||||||
|
"late": datetime(2026, 1, 31, 12, 0, tzinfo=timezone.utc),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_team_id(email):
|
||||||
|
return f"team:{email}"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_pin(team_id, reset_at):
|
||||||
|
pins.append((team_id, reset_at.isoformat()))
|
||||||
|
|
||||||
|
|
||||||
|
m.fetch_org_join_days = fake_org_joins
|
||||||
|
m.litellm_team_id_for_email = fake_team_id
|
||||||
|
m.litellm_pin_reset_date = fake_pin
|
||||||
|
|
||||||
|
conn = m.get_db()
|
||||||
|
m._ensure_allowance_tables(conn) # creates allowance_log and adds anchor_day
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, org_slug) "
|
||||||
|
"VALUES ('tech@cosmos.coop', '', 1, 'member', 'cosmos')")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, org_slug) "
|
||||||
|
"VALUES ('ops@late.org', '', 1, 'member', 'late')")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, org_slug) "
|
||||||
|
"VALUES ('x@unknown.org', '', 1, 'member', 'unknown-org')")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, org_slug, anchor_day) "
|
||||||
|
"VALUES ('already@set.org', '', 1, 'member', 'cosmos', 7)")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
first = asyncio.run(m.reconcile_org_anchors())
|
||||||
|
anchors = {r["email"]: r["anchor_day"] for r in first["anchored"]}
|
||||||
|
check("org join day 15 -> anchor 15", anchors.get("tech@cosmos.coop"), 15)
|
||||||
|
check("org join day 31 -> clamped to 28", anchors.get("ops@late.org"), 28)
|
||||||
|
check("an org with no OC record is reported, not guessed",
|
||||||
|
[u["email"] for u in first["unresolved"]], ["x@unknown.org"])
|
||||||
|
check("an already-anchored row is untouched", "already@set.org" not in anchors, True)
|
||||||
|
|
||||||
|
reset = dict((t, r) for t, r in pins)
|
||||||
|
check("reset pinned to the next occurrence of the anchor day (Dec 15)",
|
||||||
|
reset.get("team:tech@cosmos.coop", "")[:10], "2026-12-15")
|
||||||
|
|
||||||
|
second = asyncio.run(m.reconcile_org_anchors())
|
||||||
|
check("second pass leaves only the unresolved org to report", second["checked"], 1)
|
||||||
|
check("second pass writes no anchors", second["anchored"], [])
|
||||||
|
check("the unresolved org is reported again, not silently dropped",
|
||||||
|
[u["email"] for u in second["unresolved"]], ["x@unknown.org"])
|
||||||
|
|
||||||
|
row = m.get_db().execute(
|
||||||
|
"SELECT anchor_day FROM members WHERE email = 'tech@cosmos.coop'").fetchone()
|
||||||
|
check("anchor persisted", row[0], 15)
|
||||||
|
|
||||||
|
print()
|
||||||
|
if failures:
|
||||||
|
print(f"{failures} FAILURE(S)")
|
||||||
|
sys.exit(1)
|
||||||
|
print("all checks passed")
|
||||||
Reference in new issue
Block a user