sightbox/backend/billing/trial_check.py

96 lines
4.3 KiB
Python

"""
trial_check.py — route: POST /internal/check-trial/<tenant_slug>.
Independent of Stripe entirely: compares "now" against this tenant's own
trial_start_date + trial_days (tenants.json) and, once that window has
elapsed, locks out through the exact same billing.disable_users() a real
invoice.payment_failed would use — so whichever trigger caused the
lockout, a real payment succeeding afterward restores everyone through
the same reenable_users() snapshot, unconditionally.
Meant to be called once a day by a native Frappe Scheduled Job (see
provision_client.py) — not by Stripe, not by a browser. Not reverse-proxied
to the public internet in production, the same as every other route here
except /webhook/stripe/<tenant_slug> — see INSTALLATION_PLAYBOOK.md's
billing stage. No signature to verify here: this route takes no input
besides the tenant_slug already embedded in its own URL, and every
transition it can trigger is the same idempotent, reversible lockout
disable_users() already guards.
Inbound: POST /internal/check-trial/<tenant_slug>
Response shape: {"status": "locked" | "already_locked" | "not_due" |
"no_trial_configured", "trace_id": "..."}
or {"error": "unknown tenant", "trace_id": "..."} (404)
"already_locked" covers every repeat call after the
first (Stripe-independent daily scheduler ticks keep
calling this after the trial has expired, right up
until payment succeeds) — disable_users() finds nothing
newly eligible and safely no-ops.
"""
import logging
import sentry_sdk
from flask import Blueprint, current_app, g, jsonify
from .billing import PartialFailureError, SnapshotFetchError, disable_users
from .state_store import StateStore
from .tenants import trial_has_expired
logger = logging.getLogger("trial_check")
trial_check_bp = Blueprint("trial_check", __name__)
@trial_check_bp.route("/internal/check-trial/<tenant_slug>", methods=["POST"])
def check_trial(tenant_slug):
"""
Locks this tenant out if its independent trial has expired.
Data flow:
tenant_slug (str) — URL segment identifying which client
returns (Flask response) — see module docstring for shapes
Steps:
1. Reject with 404 if tenant_slug matches no configured tenant
2. No-op with "no_trial_configured"/"not_due" if this tenant has no
trial configured, or its trial hasn't elapsed yet
3. Otherwise lock out via the exact same disable_users() a real
invoice.payment_failed would use
"""
trace_id = g.trace_id
registry = current_app.config["TENANT_REGISTRY"]
# Step 1: an unknown tenant is rejected outright
tenant = registry.get(tenant_slug)
if tenant is None:
logger.warning("trace_id=%s rejected: unknown tenant %s", trace_id, tenant_slug)
return jsonify({"error": "unknown tenant", "trace_id": trace_id}), 404
# Step 2: nothing to do unless a trial is configured and has actually elapsed
if tenant.trial_start_date is None or tenant.trial_days is None:
return jsonify({"status": "no_trial_configured", "trace_id": trace_id}), 200
if not trial_has_expired(tenant):
return jsonify({"status": "not_due", "trace_id": trace_id}), 200
# Step 3: lock out — disable_users() itself is the no-op-if-already-locked guard
frappe_client = registry.frappe_client_for(tenant_slug)
state_store = StateStore(tenant_slug=tenant_slug, db_path=current_app.config["STATE_STORE_PATH"])
try:
result = disable_users(frappe_client, state_store, trace_id)
except SnapshotFetchError as exc:
logger.error("trace_id=%s tenant=%s trial-lock stopped: %s", trace_id, tenant_slug, exc)
sentry_sdk.capture_exception(exc)
return jsonify({"error": "trial-lock failed", "trace_id": trace_id}), 500
except PartialFailureError as exc:
logger.error(
"trace_id=%s tenant=%s trial-lock partially failed: succeeded=%s failed=%s",
trace_id, tenant_slug, exc.succeeded, exc.failed,
)
sentry_sdk.capture_exception(exc)
return jsonify({"error": "trial-lock partially failed", "trace_id": trace_id}), 502
status = "locked" if result["locked"] else "already_locked"
return jsonify({"status": status, "trace_id": trace_id}), 200