============================= Endpoints de Facturación ============================= El módulo de facturación expone endpoints bajo ``/billing/api/`` diseñados para integrarse fácilmente con sistemas **ERP/CRM**. Todos los campos económicos (``tax_id``, ``subtotal``, ``tax_amount``, ``total``, ``currency``, ``line_items``) siguen un formato estándar parseable por cualquier sistema externo. .. contents:: En esta página :local: :depth: 2 Facturas — ``/billing/api/invoices/`` ====================================== El endpoint principal para consultar y gestionar facturas. Cada factura incluye datos fiscales completos e inmutables (snapshot al momento de generación). .. list-table:: Métodos :header-rows: 1 :widths: 15 50 35 * - Método - Endpoint - Descripción * - ``GET`` - ``/billing/api/invoices/`` - Listar facturas (paginado) * - ``POST`` - ``/billing/api/invoices/`` - Crear factura (admin) * - ``GET`` - ``/billing/api/invoices/{id}/`` - Detalle de factura con líneas * - ``PUT`` - ``/billing/api/invoices/{id}/`` - Actualizar factura (solo borrador) * - ``DELETE`` - ``/billing/api/invoices/{id}/`` - Anular factura * - ``POST`` - ``/billing/api/invoices/{id}/mark_paid/`` - Marcar como pagada (admin) * - ``POST`` - ``/billing/api/invoices/{id}/create_stripe_checkout/`` - Crear sesión de pago Stripe * - ``POST`` - ``/billing/api/invoices/{id}/create_paypal_order/`` - Crear orden de pago PayPal Filtros disponibles -------------------- - ``?status=pending`` — Filtrar por estado (draft, pending, paid, overdue, cancelled, refunded) - ``?tenant=1`` — Filtrar por ID de tenant - ``?date_from=2026-01-01`` — Facturas desde una fecha - ``?date_to=2026-01-31`` — Facturas hasta una fecha **Ejemplo — Listar facturas pendientes:** .. code-block:: bash curl -X GET "https://panel.example.com/billing/api/invoices/?status=pending" \ -H "Authorization: Bearer $TOKEN" **Respuesta (lista):** .. code-block:: json { "count": 3, "next": null, "previous": null, "results": [ { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "number": "INV-2026-0015", "tenant": 1, "status": "pending", "issue_date": "2026-02-01", "due_date": "2026-02-15", "subtotal": "49.90", "tax_rate": "21.00", "tax_amount": "10.48", "total": "60.38", "currency": "EUR" } ] } **Respuesta (detalle con line_items):** .. code-block:: json { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "number": "INV-2026-0015", "tenant": 1, "status": "pending", "issue_date": "2026-02-01", "due_date": "2026-02-15", "paid_date": null, "period_start": "2026-01-01", "period_end": "2026-01-31", "subtotal": "49.90", "tax_rate": "21.00", "tax_amount": "10.48", "total": "60.38", "currency": "EUR", "billing_name": "Empresa Ejemplo S.L.", "billing_tax_id": "B12345678", "billing_address": "Calle Mayor 1, 08001 Barcelona, ES", "notes": "", "items": [ { "id": 1, "description": "Hosting Plan M - Enero 2026", "quantity": "1.0000", "unit_price": "29.9500", "total": "29.95", "resource_type": "hosting_site", "resource_id": 1, "period_start": "2026-01-01", "period_end": "2026-01-31" }, { "id": 2, "description": "Base de datos adicional", "quantity": "1.0000", "unit_price": "9.9500", "total": "9.95", "resource_type": "addon", "resource_id": null, "period_start": "2026-01-01", "period_end": "2026-01-31" }, { "id": 3, "description": "VPS Basic - 720 horas", "quantity": "720.0000", "unit_price": "0.0139", "total": "10.00", "resource_type": "vps", "resource_id": 5, "period_start": "2026-01-01", "period_end": "2026-01-31" } ], "payments": [], "stripe_invoice_id": "", "paypal_invoice_id": "", "created_at": "2026-02-01T00:05:00Z", "updated_at": "2026-02-01T00:05:00Z" } .. note:: Los campos ``billing_name``, ``billing_tax_id`` y ``billing_address`` son snapshots inmutables tomados del perfil de facturación al momento de generar la factura. Esto garantiza que la factura sea legalmente válida incluso si el cliente cambia sus datos fiscales posteriormente. Suscripciones — ``/billing/api/subscriptions/`` ================================================= Gestión de suscripciones activas que enlazan tenants con planes de precios. .. list-table:: Métodos :header-rows: 1 :widths: 15 55 30 * - Método - Endpoint - Descripción * - ``GET`` - ``/billing/api/subscriptions/`` - Listar suscripciones * - ``POST`` - ``/billing/api/subscriptions/`` - Crear suscripción * - ``GET`` - ``/billing/api/subscriptions/{id}/`` - Detalle de suscripción * - ``POST`` - ``/billing/api/subscriptions/{id}/cancel/`` - Cancelar suscripción * - ``POST`` - ``/billing/api/subscriptions/{id}/pause/`` - Pausar suscripción * - ``POST`` - ``/billing/api/subscriptions/{id}/resume/`` - Reanudar suscripción **Respuesta de suscripción:** .. code-block:: json { "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "tenant": 1, "plan": 2, "status": "active", "custom_price": null, "resource_type": "hosting_site", "resource_id": 1, "resource_name": "example.com - Plan M", "started_at": "2026-01-01T00:00:00Z", "current_period_start": "2026-02-01T00:00:00Z", "current_period_end": "2026-02-28T23:59:59Z", "cancelled_at": null, "stripe_subscription_id": "", "paypal_subscription_id": "" } Registros de Uso — ``/billing/api/usage/`` ============================================ Endpoint de solo lectura para consultar registros de consumo (VPS por horas, almacenamiento adicional, etc.). .. list-table:: Métodos :header-rows: 1 :widths: 15 50 35 * - Método - Endpoint - Descripción * - ``GET`` - ``/billing/api/usage/`` - Listar registros de uso * - ``GET`` - ``/billing/api/usage/{id}/`` - Detalle de un registro **Respuesta:** .. code-block:: json { "id": 100, "subscription": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "resource_type": "vm", "resource_id": 5, "resource_name": "vps-basic-01", "period_start": "2026-02-01T00:00:00Z", "period_end": "2026-02-01T01:00:00Z", "quantity": "1.0000", "unit": "hours", "unit_price": "0.0139", "total": "0.0139", "invoiced": false } Planes de Precios — ``/billing/api/plans/`` ============================================= Catálogo de planes de precios configurables. Lectura para todos los autenticados, escritura solo para administradores. .. list-table:: Métodos :header-rows: 1 :widths: 15 50 35 * - Método - Endpoint - Descripción * - ``GET`` - ``/billing/api/plans/`` - Listar planes activos * - ``GET`` - ``/billing/api/plans/{slug}/`` - Detalle de un plan (por slug) * - ``POST`` - ``/billing/api/plans/`` - Crear plan (admin) * - ``PUT`` - ``/billing/api/plans/{slug}/`` - Actualizar plan (admin) * - ``DELETE`` - ``/billing/api/plans/{slug}/`` - Desactivar plan (admin) **Respuesta de plan:** .. code-block:: json { "id": 2, "name": "Hosting Plan M", "slug": "hosting-plan-m", "description": "Hosting compartido con 10 sitios, 5 BBDDs, 10GB", "resource_type": "hosting", "billing_period": "monthly", "price": "29.9500", "setup_fee": "0.00", "currency": "EUR", "hosting_package": 2, "tax_rate": "21.00", "is_active": true } Pagos — ``/billing/api/payments/`` ==================================== Registro de pagos recibidos (Stripe, PayPal, transferencia, manual). Solo lectura. .. list-table:: Métodos :header-rows: 1 :widths: 15 50 35 * - Método - Endpoint - Descripción * - ``GET`` - ``/billing/api/payments/`` - Listar pagos * - ``GET`` - ``/billing/api/payments/{id}/`` - Detalle de un pago **Respuesta de pago:** .. code-block:: json { "id": "c8d9e0f1-2345-6789-abcd-ef0123456789", "invoice": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "tenant": 1, "amount": "60.38", "currency": "EUR", "gateway": "stripe", "status": "completed", "gateway_payment_id": "pi_3Abc123Def456Ghi", "paid_at": "2026-02-05T15:30:00Z", "notes": "" } Integración ERP/CRM ==================== El formato JSON de las facturas está diseñado para importación directa en sistemas ERP y CRM. Campos clave para la integración: .. list-table:: Campos para ERP :header-rows: 1 :widths: 25 75 * - Campo - Uso en ERP * - ``number`` - Número de factura único (INV-YYYY-NNNN) * - ``billing_tax_id`` - NIF/CIF/VAT del cliente * - ``billing_name`` - Razón social del cliente * - ``billing_address`` - Dirección fiscal completa * - ``subtotal`` - Base imponible * - ``tax_rate`` - Porcentaje de IVA aplicado * - ``tax_amount`` - Cuota de IVA * - ``total`` - Total factura (subtotal + IVA) * - ``currency`` - Moneda ISO 4217 (EUR, USD, etc.) * - ``items[]`` - Líneas de factura con desglose