194 lines
8.9 KiB
Python
194 lines
8.9 KiB
Python
"""
|
|
billing.py — the actual lock-out/restore logic for access control, whether
|
|
triggered by a real Stripe invoice.payment_failed/succeeded or by the
|
|
independent trial-expiry check. Implements the three-step rollback plan
|
|
documented in CLAUDE.md's Enterprise Standards Compliance section, adapted
|
|
to a Role swap instead of the User.enabled flag: a locked-out User keeps
|
|
enabled=1 (can still log in) but holds only frappe_client.LOCKOUT_ROLE
|
|
with default_workspace cleared, which has no Desk access and redirects
|
|
straight to the billing page — see FrappeClient.get_user_lock_state's
|
|
docstring for exactly how that works, including why default_workspace has
|
|
to move in lockstep with the Role (a real bug caught live: a User's own
|
|
default_workspace silently overrides LOCKOUT_ROLE's redirect otherwise).
|
|
No Flask/HTTP objects imported here by design — stripe_webhook.py owns
|
|
the request/response, this module owns the business logic and is
|
|
testable without a running Flask app.
|
|
"""
|
|
|
|
import logging
|
|
|
|
logger = logging.getLogger("billing")
|
|
|
|
|
|
class BillingError(Exception):
|
|
"""Base class for billing-operation failures."""
|
|
|
|
|
|
class SnapshotFetchError(BillingError):
|
|
"""
|
|
Raised when Step 2 (fetch + store the currently-enabled Users) fails.
|
|
|
|
Per the rollback plan: if this happens, stop — no User has been touched,
|
|
so there is nothing to roll back, only nothing to proceed with.
|
|
"""
|
|
|
|
|
|
class PartialFailureError(BillingError):
|
|
"""
|
|
Raised when Step 3 (or its re-enable mirror) partially fails — some
|
|
usernames succeeded, some didn't.
|
|
|
|
Data carried:
|
|
succeeded (list[str]) — usernames the operation completed for
|
|
failed (list[str]) — usernames the operation failed for
|
|
"""
|
|
|
|
def __init__(self, message, succeeded, failed):
|
|
super().__init__(message)
|
|
self.succeeded = succeeded
|
|
self.failed = failed
|
|
|
|
|
|
def disable_users(frappe_client, state_store, trace_id):
|
|
"""
|
|
Handles a lockout trigger (invoice.payment_failed, or the independent
|
|
trial-expiry check): locks every currently-unlocked, eligible User
|
|
(Role -> LOCKOUT_ROLE, default_workspace cleared), after durably
|
|
storing each one's real Roles + default_workspace so they can be
|
|
restored exactly.
|
|
|
|
Data flow:
|
|
frappe_client (FrappeClient) — Frappe REST API wrapper
|
|
state_store (StateStore) — persistent snapshot + audit log
|
|
trace_id (str) — this request's trace id, for log correlation
|
|
returns (dict) — {"locked": [...], "failed": [...]}
|
|
|
|
Steps:
|
|
1. Fetch every newly-eligible User's current lock state (excludes
|
|
Administrator, this client's own service account, and anyone
|
|
already locked out — see FrappeClient.list_lockable_users). If
|
|
none, stop — a no-op, deliberately without touching the snapshot
|
|
at all (see the note below on why this matters)
|
|
2. Merge that {username: {"roles", "default_workspace"}} map into
|
|
whatever snapshot already exists (rather than replacing it
|
|
outright) and store the result before locking anyone out — if
|
|
this fails, stop immediately; raise SnapshotFetchError, nothing
|
|
has changed yet
|
|
3. Lock each newly-eligible User (FrappeClient.lock_user), continuing
|
|
through the full list even if one call fails (each User's lock is
|
|
independent), then raise PartialFailureError if any failed so the
|
|
caller returns a non-2xx and Stripe retries the event
|
|
|
|
Why Step 1 stops cold on an empty result, and Step 2 merges instead of
|
|
replacing: this function runs more than once per lockout in practice —
|
|
Stripe retries invoice.payment_failed on a non-2xx, and the independent
|
|
trial-expiry check re-runs daily until payment succeeds. On any of
|
|
those repeat runs, everyone already locked is excluded from
|
|
list_lockable_users() by design, so a naive "replace the snapshot with
|
|
whatever came back" would overwrite a real, still-needed restore point
|
|
with an empty (or partial, if a new User became eligible meanwhile)
|
|
one — destroying the only record of what to restore, before payment
|
|
ever arrives to trigger reenable_users().
|
|
"""
|
|
# Step 1: fetch — a failure here is Step 2's failure per the rollback plan, nothing is stored yet
|
|
try:
|
|
newly_lockable = frappe_client.list_lockable_users()
|
|
except Exception as exc:
|
|
state_store.log_action(trace_id, "snapshot_fetch", "failure")
|
|
logger.error("trace_id=%s snapshot fetch failed: %s", trace_id, exc)
|
|
raise SnapshotFetchError("Failed to fetch lockable Users") from exc
|
|
|
|
if not newly_lockable:
|
|
logger.info("trace_id=%s disable: no newly-eligible users to lock, nothing to do", trace_id)
|
|
return {"locked": [], "failed": []}
|
|
|
|
# Step 2: merge into the existing snapshot (if any) before touching any User —
|
|
# this is the confirmed restore point, and must never drop already-stored entries
|
|
try:
|
|
merged_snapshot = {**state_store.get_snapshot(), **newly_lockable}
|
|
state_store.save_snapshot(merged_snapshot)
|
|
except Exception as exc:
|
|
state_store.log_action(trace_id, "snapshot_save", "failure")
|
|
logger.error("trace_id=%s snapshot save failed: %s", trace_id, exc)
|
|
raise SnapshotFetchError("Failed to store the lockable-Users snapshot") from exc
|
|
|
|
state_store.log_action(trace_id, "snapshot_save", "success")
|
|
logger.info("trace_id=%s snapshot saved: %d newly-locked user(s)", trace_id, len(newly_lockable))
|
|
|
|
# Step 3: lock out every newly-eligible User — best-effort across the whole list, not stop-at-first-failure
|
|
locked, failed = [], []
|
|
for username in newly_lockable:
|
|
try:
|
|
frappe_client.lock_user(username)
|
|
except Exception as exc:
|
|
failed.append(username)
|
|
state_store.log_action(trace_id, "user_locked", "failure", username=username)
|
|
logger.error("trace_id=%s failed to lock out %s: %s", trace_id, username, exc)
|
|
else:
|
|
locked.append(username)
|
|
state_store.log_action(trace_id, "user_locked", "success", username=username)
|
|
|
|
if failed:
|
|
raise PartialFailureError(
|
|
f"Locked out {len(locked)}/{len(newly_lockable)} users; {len(failed)} failed",
|
|
succeeded=locked,
|
|
failed=failed,
|
|
)
|
|
|
|
return {"locked": locked, "failed": failed}
|
|
|
|
|
|
def reenable_users(frappe_client, state_store, trace_id):
|
|
"""
|
|
Handles invoice.payment_succeeded (a real charge, or a trial-start $0
|
|
invoice): restores exactly the stored snapshot from the last
|
|
disable_users() call — never "every locked-out user found now", since
|
|
the stored Roles + default_workspace are the only record of what each
|
|
one actually had before lockout.
|
|
|
|
Data flow:
|
|
frappe_client (FrappeClient) — Frappe REST API wrapper
|
|
state_store (StateStore) — persistent snapshot + audit log
|
|
trace_id (str) — this request's trace id, for log correlation
|
|
returns (dict) — {"reenabled": [...], "failed": [...]}
|
|
|
|
Steps:
|
|
1. Read back the stored snapshot — an empty snapshot is a valid no-op
|
|
(nothing was locked out, or a previous restore already cleared it)
|
|
2. Restore each User's real Roles + default_workspace from the
|
|
snapshot, continuing through the full list even if one call
|
|
fails, mirroring disable_users' Step 3
|
|
3. Clear the snapshot only once every User in it has been
|
|
successfully restored — a partial failure leaves the snapshot in
|
|
place so a retried event picks up exactly where this one left off
|
|
"""
|
|
# Step 1: read the restore point saved during the matching disable_users() call
|
|
snapshot = state_store.get_snapshot()
|
|
if not snapshot:
|
|
logger.info("trace_id=%s re-enable: no stored snapshot, nothing to do", trace_id)
|
|
return {"reenabled": [], "failed": []}
|
|
|
|
# Step 2: restore every User's real Roles + default_workspace from the snapshot — best-effort
|
|
reenabled, failed = [], []
|
|
for username, state in snapshot.items():
|
|
try:
|
|
frappe_client.restore_user(username, state["roles"], state["default_workspace"])
|
|
except Exception as exc:
|
|
failed.append(username)
|
|
state_store.log_action(trace_id, "user_reenabled", "failure", username=username)
|
|
logger.error("trace_id=%s failed to restore %s: %s", trace_id, username, exc)
|
|
else:
|
|
reenabled.append(username)
|
|
state_store.log_action(trace_id, "user_reenabled", "success", username=username)
|
|
|
|
if failed:
|
|
raise PartialFailureError(
|
|
f"Restored {len(reenabled)}/{len(snapshot)} users; {len(failed)} failed",
|
|
succeeded=reenabled,
|
|
failed=failed,
|
|
)
|
|
|
|
# Step 3: every stored user is confirmed restored, safe to clear the restore point
|
|
state_store.clear_snapshot()
|
|
return {"reenabled": reenabled, "failed": failed}
|