 # Billing Lifecycle
 
 ## Purpose
 Detail how credits, plans, subscriptions, invoices, and payments flow through the system, and where deductions/additions are enforced.
 
 ## Code Locations (exact paths)
 - Models: `backend/igny8_core/business/billing/models.py` (`CreditTransaction`, `CreditUsageLog`, `CreditCostConfig`, `Invoice`, `Payment`, `CreditPackage`, `PaymentMethodConfig`, `AccountPaymentMethod`)
 - Services: `backend/igny8_core/business/billing/services/credit_service.py`, `services/invoice_service.py`, `services/payment_service.py`
 - Views/Endpoints: `backend/igny8_core/modules/billing/views.py`
 - Frontend billing pages: `frontend/src/pages/account/{AccountBillingPage.tsx,PlansAndBillingPage.tsx,PurchaseCreditsPage.tsx}`
 
 ## High-Level Responsibilities
 - Track credit balance, record usage, and enforce costs for AI/automation actions.
 - Manage plans/subscriptions, generate invoices, and record payments.
 - Expose account-scoped billing data (balance, usage, invoices, payments, packages, payment methods).
 
 ## Detailed Behavior
 - Credit balance: stored on `Account.credits`; `CreditService` adds/deducts via `CreditTransaction` and logs usage in `CreditUsageLog`.
 - Costs: read from `CreditCostConfig` or hardcoded `CREDIT_COSTS` fallbacks inside `credit_service.py`.
 - Deductions: called from AI/automation flows to ensure sufficient credits; `InsufficientCreditsError` thrown on shortage.
 - Plans/Subscriptions: `Plan` defines price, billing_cycle, included_credits, max sites/sectors/users; `Subscription` links account to plan. Plan selection handled via billing endpoints and frontend plan tabs.
 - Invoices: `InvoiceService` creates invoices for subscriptions and credit packages; generates unique invoice numbers and line items.
 - Payments: `PaymentService` records payments; manual payments stored with status (pending/processing/etc.); payment methods configured via `PaymentMethodConfig`/`AccountPaymentMethod`.
 - Packages: `CreditPackage` defines purchasable credit bundles; purchasing triggers invoice/payment flows.
 
 ## Data Structures / Models Involved (no code)
 - Billing: `CreditTransaction`, `CreditUsageLog`, `CreditCostConfig`, `Invoice`, `Payment`, `CreditPackage`, `PaymentMethodConfig`, `AccountPaymentMethod`.
 - Plan: `Plan`, `Subscription` (in `auth/models.py`).
 - Account linkage: `Account` holds `credits` and `plan`.
 
 ## Execution Flow
 - Balance/Usage read: billing endpoints return account-scoped balance and usage summaries.
 - AI/Automation call: service invokes `CreditService.deduct_credits_for_action` → creates `CreditTransaction` + `CreditUsageLog`.
 - Purchase credits: frontend calls billing endpoint → `CreditService.add_credits` + `InvoiceService` for package; payment recorded via `PaymentService` (manual/other).
 - Subscription change: endpoint updates `Subscription` + `Account.plan`, generates invoice as needed; payment recorded if required.
 - Invoice download: `modules/billing/views.py` exposes invoice retrieval; frontend uses `downloadInvoicePDF`.
 
 ## Cross-Module Interactions
 - Automation/writer AI calls depend on credit checks; insufficient balance blocks operations.
 - Account settings feed invoice billing details; payments/invoices are tied to account.
 
 ## State Transitions (if applicable)
 - Payment status: `pending` → `processing/pending_approval` → `succeeded/completed` or `failed/refunded/cancelled/void/uncollectible`.
 - Subscription status: `active`/`cancelled` (persisted in `Subscription`); plan reference on account updates accordingly.
 
 ## Error Handling
 - `InsufficientCreditsError` for low balance; surfaces to API as error response.
 - Payment/Invoice service raise validation errors (e.g., already paid invoice).
 
 ## Tenancy Rules
 - All billing queries filter by `request.user.account`; viewsets inherit from `AccountModelViewSet`.
 - Payment methods, invoices, payments, credit transactions are account-scoped; no cross-tenant access.
 
 ## Billing Rules (if applicable)
 - Costs derived from config constants or `CreditCostConfig`.
 - Included credits and limits come from `Plan`; extra purchases via `CreditPackage`.
 - Credits must be available before AI/automation runs proceed.
 
 ## Background Tasks / Schedulers (if applicable)
 - None dedicated; billing operations are request-driven. Automation tasks carry account context to deduct credits within Celery runs.
 
 ## Key Design Considerations
 - CreditService centralizes deductions to avoid scattered logic.
 - Manual payment flow avoids storing sensitive data; relies on transaction_reference and admin approval.
 
 ## How Developers Should Work With This Module
 - When adding new billable actions, route them through `CreditService` with a defined cost key.
 - To change pricing, update `CreditCostConfig` data or the `CREDIT_COSTS` fallback map.
 - Keep all billing endpoints inheriting `AccountModelViewSet` to maintain isolation.
