caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

309 lines
11 KiB
Python

"""Launch-offer / discount-code billing primitive.
Codes are percent-off or flat-off and redeemable against a purchasable
credit pack (``starter`` | ``pro``). The authoritative price-off is only ever
applied at the ACTIVE payment provider (Dodo Payments today) by forwarding
the bare ``code`` string into Dodo's own ``discount_codes`` checkout
parameter (see :mod:`app.services.billing.dodo_client`); this module's own
catalog exists so:
* the ``/pricing`` page can preview a discounted price and render the public
promo banner without a live provider call (:func:`active_banner`,
:func:`preview`), and
* a redemption is recorded once a purchase is actually fulfilled
(:func:`redeem`), enforcing "one use per customer" at the database level.
No network access happens here — every function is a plain DB read/write
behind the shared ``get_session`` session factory (imported lazily inside
each function, mirroring :mod:`app.services.billing.card_check`, so this
module stays import-safe even before the persistence layer exists).
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any
from loguru import logger
from sqlalchemy import or_, select, update
from sqlalchemy.exc import IntegrityError
KIND_PERCENT: str = "percent"
KIND_FLAT: str = "flat"
class DiscountError(ValueError):
"""The code does not exist, is inactive, expired, exhausted, or scoped out."""
@dataclass(frozen=True)
class DiscountCheck:
"""A validated, currently-redeemable code (no money math applied yet)."""
id: str
code: str
kind: str
percent_off: int | None
amount_off_cents: int | None
banner_text: str
def _now() -> datetime:
return datetime.now(timezone.utc)
def _scope_list(raw: str) -> tuple[str, ...]:
return tuple(part.strip() for part in (raw or "").split(",") if part.strip())
def _row_is_live(row: Any, *, now: datetime) -> bool:
if not row.active:
return False
if row.starts_at is not None and row.starts_at > now:
return False
if row.expires_at is not None and row.expires_at < now:
return False
if row.max_redemptions is not None and row.redemption_count >= row.max_redemptions:
return False
return True
def _open_session():
from app.models.db.base import get_session
return get_session()
def validate_code(
code: str,
plan_key: str,
*,
user_id: str | None = None,
session: Any = None,
) -> DiscountCheck:
"""Validate ``code`` against ``plan_key`` (and ``user_id`` when known).
Raises :class:`DiscountError` with a client-safe message on any failure
(unknown code, inactive, not-yet-started, expired, fully redeemed, wrong
plan scope, or already redeemed by this user). Never raises for any other
reason — a persistence-layer failure surfaces as ``DiscountError`` too, so
callers never need a second except clause.
"""
from app.models.db.discount import DiscountCode, DiscountRedemption
normalized = (code or "").strip()
if not normalized:
raise DiscountError("discount code is required")
plan_key = (plan_key or "").strip()
def _run(active_session: Any) -> DiscountCheck:
row = active_session.execute(
select(DiscountCode).where(DiscountCode.code == normalized)
).scalar_one_or_none()
if row is None:
raise DiscountError("discount code not found")
if not _row_is_live(row, now=_now()):
raise DiscountError("discount code is no longer active")
scope = _scope_list(row.scope_plan_keys)
if scope and plan_key and plan_key not in scope:
raise DiscountError(f"discount code is not valid for the {plan_key} plan")
if user_id:
already = active_session.execute(
select(DiscountRedemption.id).where(
DiscountRedemption.discount_code_id == row.id,
DiscountRedemption.user_id == user_id,
)
).first()
if already is not None:
raise DiscountError("you have already used this discount code")
return DiscountCheck(
id=row.id,
code=row.code,
kind=row.kind,
percent_off=row.percent_off,
amount_off_cents=row.amount_off_cents,
banner_text=row.banner_text or "",
)
if session is not None:
return _run(session)
try:
with _open_session() as active_session:
return _run(active_session)
except DiscountError:
raise
except Exception as exc: # noqa: BLE001 - persistence failure -> same client error
logger.error(f"discounts: validate_code({normalized!r}) failed: {exc}")
raise DiscountError("discount code is unavailable right now") from exc
def _apply(original_cents: int, check: DiscountCheck) -> tuple[int, int]:
"""Return ``(final_cents, savings_cents)`` for ``original_cents``."""
if check.kind == KIND_FLAT:
savings = min(int(check.amount_off_cents or 0), original_cents)
else:
savings = round(original_cents * max(0, min(100, int(check.percent_off or 0))) / 100)
final_cents = max(original_cents - savings, 0)
return final_cents, savings
def preview(code: str, plan_key: str, *, user_id: str | None = None) -> dict[str, Any]:
"""Validated price preview for the ``/pricing`` banner / checkout form.
Raises :class:`DiscountError` (never a bare exception) when the code
cannot be applied to ``plan_key`` right now.
"""
from app.services.billing.plans import get_plan
plan = get_plan(plan_key)
if plan is None or not plan.is_purchasable:
raise DiscountError(f"unknown plan {plan_key!r}")
check = validate_code(code, plan_key, user_id=user_id)
original_cents = round(plan.price_usd * 100)
final_cents, savings_cents = _apply(original_cents, check)
return {
"code": check.code,
"plan_key": plan.key,
"kind": check.kind,
"percent_off": check.percent_off,
"original_price_usd": round(original_cents / 100, 2),
"final_price_usd": round(final_cents / 100, 2),
"savings_usd": round(savings_cents / 100, 2),
"banner_text": check.banner_text,
}
def active_banner() -> dict[str, Any] | None:
"""The current public ``/pricing`` promo, or ``None`` when none is live.
Picks the most-recently-created code flagged ``is_public_banner`` that is
still live (active, within its date window, under its redemption cap).
Never raises — a persistence failure degrades to "no banner" rather than
breaking the pricing page.
"""
from app.models.db.discount import DiscountCode
try:
with _open_session() as session:
rows = session.execute(
select(DiscountCode)
.where(DiscountCode.is_public_banner.is_(True))
.order_by(DiscountCode.created_at.desc())
).scalars().all()
except Exception as exc: # noqa: BLE001 - degrade to "no banner"
logger.warning(f"discounts: active_banner lookup failed: {exc}")
return None
now = _now()
for row in rows:
if _row_is_live(row, now=now):
return {
"code": row.code,
"kind": row.kind,
"percent_off": row.percent_off,
"amount_off_cents": row.amount_off_cents,
"banner_text": row.banner_text or "",
"scope_plan_keys": list(_scope_list(row.scope_plan_keys)),
}
return None
def redeem(
*,
code: str,
user_id: str,
plan_key: str,
provider: str,
workspace_id: str | None = None,
external_ref: str = "",
) -> bool:
"""Record one redemption of ``code`` by ``user_id``. Returns ``True`` on success.
Idempotent and race-safe:
* the global ``max_redemptions`` cap is enforced by an atomic, bounds-
checked ``UPDATE ... WHERE redemption_count < max_redemptions`` (never a
read-then-write race), and
* "one use per customer" is enforced by the database's
``UNIQUE(discount_code_id, user_id)`` constraint — a retry (e.g. a
webhook replay for the same payment) hits the constraint and this
function returns ``True`` without inserting a second row or
double-incrementing the counter, exactly like ``metered_usage``'s
idempotency key.
Never raises: fulfilment (crediting the pack) must never be blocked by a
redemption-bookkeeping failure, so any persistence error is logged and
this returns ``False``.
"""
from app.models.db.discount import DiscountCode, DiscountRedemption
normalized = (code or "").strip()
user_id = (user_id or "").strip()
if not normalized or not user_id:
return False
try:
with _open_session() as session:
row = session.execute(
select(DiscountCode).where(DiscountCode.code == normalized)
).scalar_one_or_none()
if row is None:
return False
existing = session.execute(
select(DiscountRedemption.id).where(
DiscountRedemption.discount_code_id == row.id,
DiscountRedemption.user_id == user_id,
)
).first()
if existing is not None:
# Already redeemed by this user (e.g. a webhook replay) —
# idempotent no-op, not an error.
return True
result = session.execute(
update(DiscountCode)
.where(DiscountCode.id == row.id)
.where(
or_(
DiscountCode.max_redemptions.is_(None),
DiscountCode.redemption_count < DiscountCode.max_redemptions,
)
)
.values(redemption_count=DiscountCode.redemption_count + 1)
)
if result.rowcount == 0:
# The cap was hit by a concurrent redemption between the
# lookup above and this UPDATE; do not record a redemption
# that was never actually granted a slot.
session.rollback()
return False
session.add(
DiscountRedemption(
discount_code_id=row.id,
user_id=user_id,
workspace_id=workspace_id or None,
plan_key=plan_key,
provider=provider,
external_ref=external_ref,
)
)
session.commit()
return True
except IntegrityError:
# Lost a race against a concurrent redemption for the same user+code.
logger.info(f"discounts: redeem({normalized!r}, user={user_id}) raced; already recorded")
return True
except Exception as exc: # noqa: BLE001 - never block fulfilment
logger.error(f"discounts: redeem({normalized!r}, user={user_id}) failed: {exc}")
return False
__all__ = [
"DiscountCheck",
"DiscountError",
"KIND_FLAT",
"KIND_PERCENT",
"active_banner",
"preview",
"redeem",
"validate_code",
]