From 01856fa12ca985da6fe810c279c99e34578f5633 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 18:14:10 +0000 Subject: [PATCH] fix(billing): Plan Despacho emite licencia real y se renueva cada mes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Antes, una compra con metadata tier=despacho_* devolvía 422 (DTO y CHECK de SQLite no conocían el tier): el cliente pagaba y no recibía licencia. - Tiers despacho_* en DTOs, CLI, schemas.sql y migración (reconstruye la tabla licenses en BD existentes conservando datos). - Despacho cuenta como suscripción: invoice.payment_succeeded rellena créditos y customer.subscription.deleted la detiene. - Sin metadata: suscripción EUR de 49/99/149 € se infiere como Despacho. - tests/tier1_features/test_despacho_plan.py (5 tests). Suite 239/239. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01R4cLjd2oEZwwjivgXu6rxX --- CLAUDE.md | 2 +- app/application/dtos/billing_dtos.py | 2 +- app/application/dtos/license_dtos.py | 2 +- app/application/services/billing_service.py | 11 +- app/cli.py | 2 +- app/infrastructure/database/migrations.py | 8 +- app/infrastructure/database/schemas.sql | 2 +- tests/tier1_features/test_despacho_plan.py | 115 ++++++++++++++++++++ 8 files changed, 134 insertions(+), 10 deletions(-) create mode 100644 tests/tier1_features/test_despacho_plan.py diff --git a/CLAUDE.md b/CLAUDE.md index a809b23..29fdbe1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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`. diff --git a/app/application/dtos/billing_dtos.py b/app/application/dtos/billing_dtos.py index f20ea78..ddbd818 100644 --- a/app/application/dtos/billing_dtos.py +++ b/app/application/dtos/billing_dtos.py @@ -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") diff --git a/app/application/dtos/license_dtos.py b/app/application/dtos/license_dtos.py index 757ee50..8b6c5c2 100644 --- a/app/application/dtos/license_dtos.py +++ b/app/application/dtos/license_dtos.py @@ -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]+$") diff --git a/app/application/services/billing_service.py b/app/application/services/billing_service.py index bf65026..fb613b8 100644 --- a/app/application/services/billing_service.py +++ b/app/application/services/billing_service.py @@ -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"} @@ -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. @@ -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.""" diff --git a/app/cli.py b/app/cli.py index 7ea20bc..6d20ac5 100644 --- a/app/cli.py +++ b/app/cli.py @@ -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( diff --git a/app/infrastructure/database/migrations.py b/app/infrastructure/database/migrations.py index 32fa26b..a17662b 100644 --- a/app/infrastructure/database/migrations.py +++ b/app/infrastructure/database/migrations.py @@ -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. @@ -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, diff --git a/app/infrastructure/database/schemas.sql b/app/infrastructure/database/schemas.sql index dd4af2e..5dfc8c4 100644 --- a/app/infrastructure/database/schemas.sql +++ b/app/infrastructure/database/schemas.sql @@ -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, diff --git a/tests/tier1_features/test_despacho_plan.py b/tests/tier1_features/test_despacho_plan.py new file mode 100644 index 0000000..e20ffd3 --- /dev/null +++ b/tests/tier1_features/test_despacho_plan.py @@ -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()