videogen/apps/api/app/models/db/discount.py
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

140 lines
5.9 KiB
Python

"""Discount codes: percent/flat-off codes redeemable against a credit pack.
Two tables, both purely additive:
* ``DiscountCode`` — the catalog row a creator/owner creates for a campaign
(e.g. ``LAUNCH20`` -> 20% off). ``redemption_count`` is a denormalized
counter kept in sync with :func:`app.services.billing.discounts.redeem`'s
atomic, bounds-checked ``UPDATE`` so a code can never be redeemed more than
``max_redemptions`` times even under concurrent requests.
* ``DiscountRedemption`` — one row per successful redemption. The composite
``UNIQUE(discount_code_id, user_id)`` is the whole idempotency/anti-abuse
story: the SAME user can never redeem the SAME code twice (a webhook retry
for the same payment hits the constraint and is swallowed, exactly like the
``metered_usage.idempotency_key`` pattern), and "one use per customer" is
enforced by the database, not application code that could race.
A code's real price-off is only ever applied at the ACTIVE payment provider
(Dodo Payments) by forwarding the bare ``code`` string into Dodo's own
``discount_codes`` checkout parameter — Dodo resolves the authoritative
amount/eligibility server-side. This local catalog exists so the web app can
preview a price before checkout and render the ``/pricing`` promo banner
without a live provider call, and so redemptions are tracked after the fact.
Keep a code's ``percent_off``/``amount_off_cents`` here in sync with whatever
is configured in the Dodo dashboard for the same ``code`` — the same
"mirror the provider, don't query it live" convention
:mod:`app.services.billing.plans` already uses for plan prices.
"""
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import (
Boolean,
DateTime,
ForeignKey,
Integer,
String,
UniqueConstraint,
false,
text,
true,
)
from sqlalchemy.orm import Mapped, mapped_column
from app.models.db.base import Base
def _uuid() -> str:
return uuid.uuid4().hex
KIND_PERCENT: str = "percent"
KIND_FLAT: str = "flat"
KINDS: tuple[str, ...] = (KIND_PERCENT, KIND_FLAT)
class DiscountCode(Base):
"""A redeemable discount code (one campaign/code per row)."""
__tablename__ = "discount_codes"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_uuid)
# Stored exactly as created; Dodo codes are case-sensitive so comparisons
# here never lower()/upper() the value.
code: Mapped[str] = mapped_column(String(40), nullable=False, unique=True, index=True)
# percent | flat
kind: Mapped[str] = mapped_column(
String(10), default=KIND_PERCENT, server_default=text("'percent'"), nullable=False
)
# 1-100 for a percentage code; null for a flat code.
percent_off: Mapped[int | None] = mapped_column(Integer, nullable=True)
# Integer minor units (cents); null for a percentage code.
amount_off_cents: Mapped[int | None] = mapped_column(Integer, nullable=True)
currency: Mapped[str] = mapped_column(
String(10), default="usd", server_default=text("'usd'"), nullable=False
)
# Comma-separated plan keys this code applies to; '' means every
# purchasable plan.
scope_plan_keys: Mapped[str] = mapped_column(
String(200), default="", server_default=text("''"), nullable=False
)
# Global redemption ceiling; null means unlimited.
max_redemptions: Mapped[int | None] = mapped_column(Integer, nullable=True)
redemption_count: Mapped[int] = mapped_column(
Integer, default=0, server_default=text("0"), nullable=False
)
active: Mapped[bool] = mapped_column(
Boolean, default=True, server_default=true(), nullable=False
)
# Surfaced on the public /pricing banner when true (at most one code should
# be flagged at a time; the service picks the newest if several are).
is_public_banner: Mapped[bool] = mapped_column(
Boolean, default=False, server_default=false(), nullable=False
)
banner_text: Mapped[str] = mapped_column(
String(200), default="", server_default=text("''"), nullable=False
)
starts_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=text("(CURRENT_TIMESTAMP)"), nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=text("(CURRENT_TIMESTAMP)"), nullable=False
)
class DiscountRedemption(Base):
"""One successful redemption of a :class:`DiscountCode` by one user.
``UNIQUE(discount_code_id, user_id)`` is the anti-double-redemption guard
(see module docstring); ``external_ref`` carries the provider payment id
for audit only (not itself unique — the user+code pair already is).
"""
__tablename__ = "discount_redemptions"
__table_args__ = (
UniqueConstraint("discount_code_id", "user_id", name="uq_discount_redemption_user"),
)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_uuid)
discount_code_id: Mapped[str] = mapped_column(
ForeignKey("discount_codes.id"), index=True, nullable=False
)
user_id: Mapped[str] = mapped_column(ForeignKey("users.id"), index=True, nullable=False)
workspace_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
plan_key: Mapped[str] = mapped_column(String(40), nullable=False)
provider: Mapped[str] = mapped_column(String(20), nullable=False)
external_ref: Mapped[str] = mapped_column(
String(255), default="", server_default=text("''"), nullable=False
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=text("(CURRENT_TIMESTAMP)"), nullable=False
)
__all__ = ["KINDS", "KIND_FLAT", "KIND_PERCENT", "DiscountCode", "DiscountRedemption"]