import pytest from infrasynth.billing.models import ( BillingPlan, PaymentGateway, ) from infrasynth.billing.services import BillingService from infrasynth.shared.enums import InvoiceStatus, 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 plan(gateway): return BillingPlan.objects.create( slug="pro", name="Pro", price_amount="49.00", price_currency="USD", interval="monthly", gateway=gateway, external_id="price_123", ) class TestCreateCheckoutSession: def test_returns_session_and_gateway(self, user, plan): result, gateway = BillingService().create_checkout_session( "pro", 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_inactive_plan_raises(self, user, plan): plan.is_active = False plan.save(update_fields=["is_active"]) with pytest.raises(BillingPlan.DoesNotExist): BillingService().create_checkout_session("pro", user) def test_no_gateway_raises(self, user, 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("pro", user) def test_gateway_failure_propagates(self, user, 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("pro", user) class TestCreateSubscription: def test_creates_active_subscription(self, user, plan, gateway): subscription = BillingService().create_subscription(plan, user, gateway, external_id="sub_1") assert subscription.user_id == user.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 def test_trial_subscription(self, user, plan, gateway): plan.trial_days = 14 plan.save(update_fields=["trial_days"]) subscription = BillingService().create_subscription(plan, user, gateway) assert subscription.status == SubscriptionStatus.TRIALING assert subscription.trial_end is not None def test_emits_subscription_created_signal(self, user, 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, user, gateway) assert sent assert sent[0]["user"] == user assert sent[0]["plan_slug"] == "pro" assert sent[0]["gateway"] == "fake" subscription_created.disconnect(receiver) class TestCancelSubscription: def test_cancels_local_and_gateway(self, user, plan, gateway): subscription = BillingService().create_subscription(plan, user, 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, user, plan, gateway): from infrasynth.billing.signals import subscription_cancelled subscription = BillingService().create_subscription(plan, user, 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, user, plan, gateway): subscription = BillingService().create_subscription(plan, user, 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, user, plan): subscription = BillingService().create_subscription(plan, user, None, external_id="") assert BillingService().sync_subscription(subscription) == {} class TestGenerateInvoice: def test_creates_invoice_and_pdf(self, user, plan, gateway, media_root): subscription = BillingService().create_subscription(plan, user, gateway, external_id="sub_1") invoice = BillingService().generate_invoice(subscription) invoice.refresh_from_db() assert invoice.status == InvoiceStatus.OPEN assert invoice.amount == 49 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.user_id == user.id def test_invoice_numbers_are_sequential(self, user, plan, gateway): service = BillingService() subscription = service.create_subscription(plan, user, 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, user, plan, gateway, settings): settings.INFRASYNTH_BILLING = { **settings.INFRASYNTH_BILLING, "TAX_PERCENTAGE": 19, "TAX_NAME": "IVA", } subscription = BillingService().create_subscription(plan, user, gateway) invoice = BillingService().generate_invoice(subscription) from decimal import Decimal assert invoice.tax_amount == Decimal("9.31") assert invoice.tax_name == "IVA" def test_custom_line_items(self, user, plan, gateway): subscription = BillingService().create_subscription(plan, user, gateway) invoice = BillingService().generate_invoice( subscription, amount=99, line_items=[{"description": "Extra", "amount": 99.0, "quantity": 1}], ) assert invoice.amount == 99 assert invoice.line_items[0]["description"] == "Extra" def test_emits_invoice_generated_signal(self, user, plan, gateway): from infrasynth.billing.signals import invoice_generated subscription = BillingService().create_subscription(plan, user, 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"] == 49.0 invoice_generated.disconnect(receiver)