import pytest from infrasynth.billing.models import App, PaymentGateway, Plan from infrasynth.billing.services import BillingService from infrasynth.shared.enums import InvoiceStatus, MonetizationModel, SubscriptionStatus pytestmark = pytest.mark.django_db @pytest.fixture def gateway(): return PaymentGateway.objects.create( slug="fake", display_name="Fake", gateway_class="tests.helpers.FakeGateway", is_active=True, ) @pytest.fixture def app(): return App.objects.create(slug="messenger", name="Messenger", monetization=MonetizationModel.SUBSCRIPTION) @pytest.fixture def plan(app, gateway): return Plan.objects.create( app=app, slug="pro", name="Pro", price_amount=4900, price_currency="USD", interval="monthly", gateway=gateway, external_id="price_123", ) class TestCreateCheckoutSession: def test_returns_session_and_gateway(self, user, tenant, plan): result, gateway = BillingService().create_checkout_session( plan, tenant, user, success_url="https://x/success", cancel_url="https://x/cancel" ) assert result.session_id == "cs_fake_123" assert result.checkout_url == "https://checkout.example.com/cs_fake_123" assert result.client_secret == "secret_123" assert gateway.slug == "fake" def test_no_gateway_raises(self, tenant, plan, gateway): plan.gateway = None plan.save(update_fields=["gateway"]) gateway.is_active = False gateway.save(update_fields=["is_active"]) with pytest.raises(ValueError, match="No active payment gateway"): BillingService().create_checkout_session(plan, tenant) def test_gateway_failure_propagates(self, tenant, plan): plan.gateway.config = {"create_should_fail": True} plan.gateway.save(update_fields=["config"]) with pytest.raises(ValueError, match="Fake gateway failure"): BillingService().create_checkout_session(plan, tenant) class TestCreateSubscription: def test_creates_active_subscription(self, tenant, plan, gateway): subscription = BillingService().create_subscription(plan, tenant, gateway, external_id="sub_1") assert subscription.tenant_id == tenant.id assert subscription.plan_id == plan.id assert subscription.gateway_id == gateway.slug assert subscription.external_id == "sub_1" assert subscription.status == SubscriptionStatus.ACTIVE assert subscription.current_period_start is not None assert subscription.current_period_end is not None assert subscription.entitlement_id is not None def test_creates_entitlement(self, tenant, plan, gateway): subscription = BillingService().create_subscription(plan, tenant, gateway) entitlement = subscription.entitlement assert entitlement.app_id == plan.app_id assert entitlement.status == "active" def test_trial_subscription(self, tenant, plan, gateway): plan.trial_days = 14 plan.save(update_fields=["trial_days"]) subscription = BillingService().create_subscription(plan, tenant, gateway) assert subscription.status == SubscriptionStatus.TRIALING assert subscription.trial_end is not None assert subscription.entitlement.status == "trialing" def test_emits_subscription_created_signal(self, tenant, plan, gateway): from infrasynth.billing.signals import subscription_created sent = [] receiver = lambda **kw: sent.append(kw) # noqa: E731 subscription_created.connect(receiver, weak=False) BillingService().create_subscription(plan, tenant, gateway) assert sent assert sent[0]["tenant_id"] == str(tenant.pk) assert sent[0]["plan_slug"] == "pro" assert sent[0]["app_slug"] == "messenger" assert sent[0]["gateway"] == "fake" subscription_created.disconnect(receiver) class TestCancelSubscription: def test_cancels_local_and_gateway(self, tenant, plan, gateway): subscription = BillingService().create_subscription(plan, tenant, gateway, external_id="sub_1") assert BillingService().cancel_subscription(subscription) is True subscription.refresh_from_db() assert subscription.status == SubscriptionStatus.CANCELLED assert subscription.cancelled_at is not None assert subscription.cancel_at_period_end is False def test_emits_cancelled_signal(self, tenant, plan, gateway): from infrasynth.billing.signals import subscription_cancelled subscription = BillingService().create_subscription(plan, tenant, gateway) sent = [] receiver = lambda **kw: sent.append(kw) # noqa: E731 subscription_cancelled.connect(receiver, weak=False) BillingService().cancel_subscription(subscription) assert sent assert sent[0]["reason"] == "user_requested" assert sent[0]["plan_slug"] == "pro" subscription_cancelled.disconnect(receiver) class TestSyncSubscription: def test_syncs_fields_from_gateway(self, tenant, plan, gateway): subscription = BillingService().create_subscription(plan, tenant, gateway, external_id="sub_1") data = BillingService().sync_subscription(subscription) assert data["status"] == "active" subscription.refresh_from_db() assert subscription.status == SubscriptionStatus.ACTIVE assert subscription.metadata.get("synced") is True def test_without_gateway_returns_empty(self, tenant, plan): subscription = BillingService().create_subscription(plan, tenant, None, external_id="") assert BillingService().sync_subscription(subscription) == {} class TestGenerateInvoice: def test_creates_invoice_and_pdf(self, tenant, plan, gateway, media_root): subscription = BillingService().create_subscription(plan, tenant, gateway, external_id="sub_1") invoice = BillingService().generate_invoice(subscription) invoice.refresh_from_db() assert invoice.status == InvoiceStatus.OPEN assert invoice.amount == 4900 assert invoice.currency == "USD" assert invoice.invoice_number.startswith("INV-") assert invoice.due_date is not None assert invoice.subscription_id == subscription.id assert invoice.tenant_id == tenant.id def test_invoice_numbers_are_sequential(self, tenant, plan, gateway): service = BillingService() subscription = service.create_subscription(plan, tenant, gateway) first = service.generate_invoice(subscription) second = service.generate_invoice(subscription) assert first.invoice_number != second.invoice_number assert first.invoice_number < second.invoice_number def test_tax_applied(self, tenant, plan, gateway, settings): settings.INFRASYNTH_BILLING = { **settings.INFRASYNTH_BILLING, "TAX_PERCENTAGE": 19, "TAX_NAME": "IVA", } subscription = BillingService().create_subscription(plan, tenant, gateway) invoice = BillingService().generate_invoice(subscription) assert invoice.tax_amount == 931 # 19% of 4900 minor units assert invoice.tax_name == "IVA" def test_custom_line_items(self, tenant, plan, gateway): subscription = BillingService().create_subscription(plan, tenant, gateway) invoice = BillingService().generate_invoice( subscription, amount=9900, line_items=[{"description": "Extra", "amount": 9900, "quantity": 1}], ) assert invoice.amount == 9900 assert invoice.line_items[0]["description"] == "Extra" def test_emits_invoice_generated_signal(self, tenant, plan, gateway): from infrasynth.billing.signals import invoice_generated subscription = BillingService().create_subscription(plan, tenant, gateway) sent = [] receiver = lambda **kw: sent.append(kw) # noqa: E731 invoice_generated.connect(receiver, weak=False) invoice = BillingService().generate_invoice(subscription) assert sent assert sent[0]["invoice_id"] == invoice.id assert sent[0]["amount"] == 4900 assert sent[0]["tenant_id"] == str(tenant.pk) invoice_generated.disconnect(receiver) class TestProcessWebhookEvent: def test_paid_event_reinstates_entitlement(self, tenant, plan, gateway): from infrasynth.billing.models import PaymentTransaction from infrasynth.shared.enums import EntitlementStatus subscription = BillingService().create_subscription(plan, tenant, gateway, external_id="sub_1") entitlement = subscription.entitlement entitlement.status = EntitlementStatus.PAST_DUE entitlement.save(update_fields=["status"]) tenant.status = "suspended" tenant.save(update_fields=["status"]) result = BillingService().process_webhook_event( gateway, "invoice.paid", { "metadata": {"tenant_id": str(tenant.pk)}, "amount": 4900, "currency": "usd", "id": "evt_1", }, event_id="evt_1", ) assert result["action"] == "reinstated" entitlement.refresh_from_db() tenant.refresh_from_db() assert entitlement.status == EntitlementStatus.ACTIVE assert tenant.status == "active" assert PaymentTransaction.objects.filter(tenant=tenant).count() == 1 def test_duplicate_event_is_idempotent(self, tenant, plan, gateway): from infrasynth.billing.models import PaymentTransaction BillingService().create_subscription(plan, tenant, gateway, external_id="sub_1") payload = {"metadata": {"tenant_id": str(tenant.pk)}, "amount": 100, "id": "evt_dup"} first = BillingService().process_webhook_event(gateway, "invoice.paid", payload, event_id="evt_dup") second = BillingService().process_webhook_event(gateway, "invoice.paid", payload, event_id="evt_dup") assert first["status"] == "processed" assert second["status"] == "duplicate" assert PaymentTransaction.objects.filter(tenant=tenant).count() == 1 def test_failed_event_marks_past_due(self, tenant, plan, gateway): from infrasynth.shared.enums import EntitlementStatus subscription = BillingService().create_subscription(plan, tenant, gateway, external_id="sub_1") BillingService().process_webhook_event( gateway, "invoice.payment_failed", {"metadata": {"tenant_id": str(tenant.pk)}, "amount": 4900, "id": "evt_fail"}, event_id="evt_fail", ) subscription.entitlement.refresh_from_db() assert subscription.entitlement.status == EntitlementStatus.PAST_DUE