Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,4 @@ Estándar: producción militar, determinismo matemático (SHA-256), seguridad LS
2. **No-Fault Quota Deduction**:
- Nunca cobrar doble ni perder créditos por reintentos de red.
3. **Verificación Obligatoria**:
- `python run_tests.py` debe pasar al 100 % (234/234) antes de cualquier `fly deploy`.
- `python run_tests.py` debe pasar al 100 % (239/239) antes de cualquier `fly deploy`.
2 changes: 1 addition & 1 deletion app/application/dtos/billing_dtos.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from pydantic import BaseModel, Field, field_validator, model_validator


VALID_TIERS = ("community", "indie", "agency", "pro", "studio", "lifetime")
VALID_TIERS = ("community", "indie", "agency", "pro", "studio", "lifetime", "despacho_basico", "despacho_pro", "despacho_empresa")
VALID_PROVIDERS = ("stripe", "lemonsqueezy")


Expand Down
2 changes: 1 addition & 1 deletion app/application/dtos/license_dtos.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from app.domain.entities.license import normalize_domain_host

_VALID_TIERS = ("community", "indie", "agency", "pro", "studio", "lifetime")
_VALID_TIERS = ("community", "indie", "agency", "pro", "studio", "lifetime", "despacho_basico", "despacho_pro", "despacho_empresa")
_VALID_ALGOS = ("ed25519", "hmac-sha256", "hmac")
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")

Expand Down
11 changes: 10 additions & 1 deletion app/application/services/billing_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ def _resolve_tier(raw: Optional[str]) -> Optional[Tier]:
"despacho_empresa": 14900,
}
# Prices of Payment Links sold before the 2026-11 price change: still recognised if metadata is missing.
_DESPACHO_EUR_AMOUNTS_CENTS: dict[int, str] = {4900: "despacho_basico", 9900: "despacho_pro", 14900: "despacho_empresa"}
_LEGACY_TIER_AMOUNTS_CENTS: dict[int, str] = {14900: "indie", 34900: "agency", 19900: "lifetime", 4900: "despacho_basico", 9900: "despacho_pro"}


Expand Down Expand Up @@ -441,6 +442,14 @@ def _extract_webhook_context(
by_price.update({cents: name for name, cents in _TIER_UNIT_AMOUNTS_CENTS.items() if cents})
if isinstance(subtotal, int) and currency == "usd" and subtotal in by_price:
tier_raw = by_price[subtotal]
elif (
isinstance(subtotal, int)
and currency == "eur"
and data_obj.get("mode") == "subscription"
and subtotal in _DESPACHO_EUR_AMOUNTS_CENTS
):
# Plan Despacho: suscripción mensual en EUR (49/99/149 €/mes). Pagos únicos en EUR no se infieren.
tier_raw = _DESPACHO_EUR_AMOUNTS_CENTS[subtotal]
return event_id, raw_event_type, customer_email, _resolve_tier(tier_raw), tier_raw

# Stripe object reference prefixes used to link a payment back to its license.
Expand Down Expand Up @@ -525,7 +534,7 @@ def _resolve_payment_licenses(self, data_obj: dict[str, Any]) -> tuple[list[Any]
return found, "email"
return [], "none"

_RECURRING_TIERS = (Tier.PRO, Tier.STUDIO)
_RECURRING_TIERS = (Tier.PRO, Tier.STUDIO, Tier.DESPACHO_BASICO, Tier.DESPACHO_PRO, Tier.DESPACHO_EMPRESA)

def _promotable_free_license(self, customer: Any) -> Optional[Any]:
"""A free Community license that was never billed: the only kind a purchase may upgrade in place."""
Expand Down
2 changes: 1 addition & 1 deletion app/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def cli() -> None:
"--tier",
"-t",
default="pro",
type=click.Choice(["community", "indie", "agency", "pro", "studio", "lifetime"], case_sensitive=False),
type=click.Choice(["community", "indie", "agency", "pro", "studio", "lifetime", "despacho_basico", "despacho_pro", "despacho_empresa"], case_sensitive=False),
help="Entitlement tier.",
)
@click.option(
Expand Down
8 changes: 4 additions & 4 deletions app/infrastructure/database/migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@ def run_migrations(conn: sqlite3.Connection, schema_path: Optional[Path] = None)
if "metadata_json" not in lic_cols:
conn.execute("ALTER TABLE licenses ADD COLUMN metadata_json TEXT NOT NULL DEFAULT '{}';")

# 3c. Ensure licenses table CHECK constraint supports indie and agency tiers
# 3c. Ensure licenses table CHECK constraint supports every Tier (indie, agency, despacho_*)
cur = conn.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='licenses'")
row = cur.fetchone()
if row and row[0] and "'indie'" not in row[0]:
logger.info("Migrating licenses table schema to include 'indie' and 'agency' tiers...")
if row and row[0] and "'despacho_empresa'" not in row[0]:
logger.info("Migrating licenses table schema to the expanded tier list (indie/agency/despacho_*)...")
# Table rebuild: FKs off (must be set outside a transaction) so DROP TABLE does not
# cascade-delete activations/quotas/usage_events; all DDL in one transaction so a crash
# leaves the old table intact.
Expand All @@ -93,7 +93,7 @@ def run_migrations(conn: sqlite3.Connection, schema_path: Optional[Path] = None)
id TEXT PRIMARY KEY,
customer_id TEXT NOT NULL REFERENCES customers(id) ON DELETE CASCADE,
license_key TEXT UNIQUE NOT NULL,
tier TEXT NOT NULL CHECK(tier IN ('community', 'indie', 'agency', 'pro', 'studio', 'lifetime')),
tier TEXT NOT NULL CHECK(tier IN ('community', 'indie', 'agency', 'pro', 'studio', 'lifetime', 'despacho_basico', 'despacho_pro', 'despacho_empresa')),
status TEXT NOT NULL CHECK(status IN ('active', 'suspended', 'expired', 'revoked', 'grace_period')),
max_seats INTEGER NOT NULL DEFAULT 1,
current_activations INTEGER NOT NULL DEFAULT 0,
Expand Down
2 changes: 1 addition & 1 deletion app/infrastructure/database/schemas.sql
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ CREATE TABLE IF NOT EXISTS licenses (
id TEXT PRIMARY KEY,
customer_id TEXT NOT NULL REFERENCES customers(id) ON DELETE CASCADE,
license_key TEXT UNIQUE NOT NULL,
tier TEXT NOT NULL CHECK(tier IN ('community', 'indie', 'agency', 'pro', 'studio', 'lifetime')),
tier TEXT NOT NULL CHECK(tier IN ('community', 'indie', 'agency', 'pro', 'studio', 'lifetime', 'despacho_basico', 'despacho_pro', 'despacho_empresa')),
status TEXT NOT NULL CHECK(status IN ('active', 'suspended', 'expired', 'revoked', 'grace_period')),
max_seats INTEGER NOT NULL DEFAULT 1,
current_activations INTEGER NOT NULL DEFAULT 0,
Expand Down
115 changes: 115 additions & 0 deletions tests/tier1_features/test_despacho_plan.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""Tier 1: Plan Despacho (49/99/149 €/mes) se emite con su tier, créditos y renovación mensual."""

from __future__ import annotations

import json
import unittest
import uuid

from tests.conftest import (
BaseKeyFlintTestCase,
TEST_STRIPE_WEBHOOK_SECRET,
generate_stripe_signature,
)


class TestDespachoPlan(BaseKeyFlintTestCase):

def _post(self, event_type: str, obj: dict):
raw = json.dumps({
"id": f"evt_{uuid.uuid4().hex}",
"type": event_type,
"data": {"object": obj},
}).encode("utf-8")
headers = {
"Stripe-Signature": generate_stripe_signature(raw, TEST_STRIPE_WEBHOOK_SECRET),
"Content-Type": "application/json",
}
return self.client.post("/api/v1/webhooks/stripe", content=raw, headers=headers)

def _buy(self, metadata: dict, amount_total: int | None = None):
email = f"despacho_{uuid.uuid4().hex[:6]}@gestoria.es"
obj = {
"id": f"cs_{uuid.uuid4().hex[:12]}",
"customer_email": email,
"customer": f"cus_{uuid.uuid4().hex[:10]}",
"metadata": metadata,
"payment_status": "paid",
"mode": "subscription",
"subscription": f"sub_{uuid.uuid4().hex[:10]}",
}
if amount_total is not None:
obj["amount_subtotal"] = amount_total
obj["currency"] = "eur"
res = self._post("checkout.session.completed", obj)
self.assertEqual(res.status_code, 200, res.text)
return res.json()["data"], obj

def _status(self, key: str) -> dict:
res = self.client.get(f"/api/v1/billing/status?license_key={key}")
self.assertEqual(res.status_code, 200, res.text)
return res.json()["data"]

def test_each_despacho_tier_issues_paid_license(self):
self.require_app()
for tier, credits in (("despacho_basico", 2500), ("despacho_pro", 6000), ("despacho_empresa", 15000)):
with self.subTest(tier=tier):
data, _ = self._buy({"tier": tier, "source": "mcp-hub"})
self.assertIn("license_key", data, data)
st = self._status(data["license_key"])
self.assertEqual(st["tier"], tier, st)
self.assertEqual(st["status"], "active", st)
self.assertEqual(st["credit_balance"], credits, st)

def test_despacho_never_falls_back_to_community(self):
self.require_app()
data, _ = self._buy({"tier": "Despacho Pro"})
st = self._status(data["license_key"])
self.assertNotEqual(st["tier"], "community", st)
self.assertEqual(st["tier"], "despacho_pro", st)

def test_despacho_by_amount_without_metadata(self):
self.require_app()
data, _ = self._buy({}, amount_total=9900)
st = self._status(data["license_key"])
self.assertEqual(st["tier"], "despacho_pro", st)

def test_monthly_renewal_refills_and_cancel_stops(self):
self.require_app()
data, obj = self._buy({"tier": "despacho_basico"})
key = data["license_key"]
cons = self.deduct_quota_api(key, 100)
self.assertIn(cons.status_code, (200, 201), cons.text)
self.assertEqual(self._status(key)["credit_balance"], 2400)
inv = {"id": f"in_{uuid.uuid4().hex[:10]}", "subscription": obj["subscription"],
"customer": obj["customer"], "customer_email": obj["customer_email"]}
res = self._post("invoice.payment_succeeded", inv)
self.assertEqual(res.status_code, 200, res.text)
self.assertEqual(self._status(key)["credit_balance"], 2500)
res = self._post("customer.subscription.deleted", {"id": obj["subscription"], "customer": obj["customer"],
"customer_email": obj["customer_email"]})
self.assertEqual(res.status_code, 200, res.text)
self.assertNotEqual(self._status(key)["status"], "active")

def test_migration_widens_tier_check_on_existing_db(self):
import pathlib
import sqlite3

from app.infrastructure.database.migrations import run_migrations

schema = pathlib.Path("app/infrastructure/database/schemas.sql").read_text()
old = schema.replace(", 'despacho_basico', 'despacho_pro', 'despacho_empresa'", "")
conn = sqlite3.connect(":memory:", isolation_level=None)
conn.row_factory = sqlite3.Row
conn.executescript(old)
conn.execute("INSERT INTO customers(id, email) VALUES ('c1', 'a@b.es')")
conn.execute("INSERT INTO licenses(id, customer_id, license_key, tier, status, signature) "
"VALUES ('l1', 'c1', 'K1', 'pro', 'active', 's')")
run_migrations(conn)
conn.execute("INSERT INTO licenses(id, customer_id, license_key, tier, status, signature) "
"VALUES ('l2', 'c1', 'K2', 'despacho_pro', 'active', 's')")
self.assertEqual(conn.execute("SELECT COUNT(*) FROM licenses").fetchone()[0], 2)


if __name__ == "__main__":
unittest.main()
Loading