docs re-org

This commit is contained in:
IGNY8 VPS (Salman)
2025-12-09 13:26:35 +00:00
parent 4d13a57068
commit 6a4f95c35a
231 changed files with 11353 additions and 31152 deletions

View File

@@ -0,0 +1,98 @@
# Billing Module Reference
## Purpose
Explain how billing is implemented: invoices, payments, credit packages, credit history/usage, payment methods, and limits, as exposed by billing services and API viewsets.
## Code Locations (exact paths)
- Models: `backend/igny8_core/business/billing/models.py`
- Services: `backend/igny8_core/business/billing/services/credit_service.py`, `invoice_service.py`, `payment_service.py`
- API (business billing): `backend/igny8_core/business/billing/views.py`, `backend/igny8_core/business/billing/urls.py`
- API (core billing endpoints): `backend/igny8_core/modules/billing/views.py`, `backend/igny8_core/modules/billing/urls.py`
- Plan metadata (included credits/limits): `backend/igny8_core/auth/models.py` (`Plan`, `Account`)
## High-Level Responsibilities
- Maintain credit ledger, usage logs, configurable per-operation costs, invoices, payments, credit packages, country-level payment method configs, and account-scoped payment methods.
- Expose endpoints for invoices/payments/credit packages/transactions, credit balance/usage/limits, and admin billing operations.
- Deduct or add credits atomically while recording both transactions and usage logs.
- Provide manual and (placeholder) Stripe/PayPal payment flows.
## Detailed Behavior
- Invoices (`InvoiceViewSet`):
- `list`/`retrieve`: fetch account-scoped invoices; include totals, line items, billing period, dates.
- `download_pdf`: returns PDF bytes from `InvoiceService.generate_pdf` (currently placeholder text payload).
- Payments (`PaymentViewSet`):
- `list`: account-scoped payments with amounts, methods, status, invoice linkage, timestamps.
- `available_methods`: delegates to `PaymentService.get_available_payment_methods` (country/config-driven; returns methods plus metadata).
- `create_manual_payment`: creates a manual payment for an invoice (bank/local wallet); requires invoice_id, method, reference; rejects already-paid invoices; returns pending-approval status.
- Account payment methods (`AccountPaymentMethodViewSet`):
- CRUD for account-level payment metadata (non-sensitive). `perform_create`/`perform_update` enforce one default by resetting others when `is_default` true or none exists.
- `set_default` toggles default within the account.
- Credit packages (`CreditPackageViewSet`):
- `list`: active packages with credits/price/discount/featured/sort order.
- `purchase`: creates invoice via `InvoiceService.create_credit_package_invoice`; returns next action depending on requested payment method (`stripe`/`paypal` placeholders, manual fallback returns invoice info).
- Credit transactions (`CreditTransactionViewSet` in business billing views; also registered under `credits/transactions` in URLs): lists credit ledger entries per account.
- Core billing endpoints (`modules/billing/views.py`):
- `CreditBalanceViewSet.list`: returns current credits, plan monthly credits, credits used this month.
- `CreditUsageViewSet`: paginated credit usage logs with filters (operation_type, date range); `summary` aggregates by operation/model and totals (credits, USD); `limits` returns plan/account limits and usage (users/sites/etc.) based on `Plan` fields.
- Routing (`business/billing/urls.py`):
- Routers for invoices, payments, credit packages, transactions, payment methods, and canonical credit endpoints (balance/usage/transactions). Legacy available-methods endpoint exposed at `/payment-methods/available/`.
## Data Structures / Models Involved (no code)
- `CreditTransaction`: ledger with type, amount (positive/negative), balance_after, metadata.
- `CreditUsageLog`: per-AI-operation usage with operation_type, credits_used, cost_usd, model_used, tokens, related object references, metadata.
- `CreditCostConfig`: per-operation cost config with unit, display metadata, active flag, audit of previous cost.
- `Invoice`: invoice_number, status, amounts (subtotal/tax/total), currency, billing_period, line_items JSON, subscription link, payment metadata, timestamps.
- `Payment`: status lifecycle, method (stripe/paypal/bank/local wallet/manual), provider references, manual notes/approval, failure reason, metadata.
- `CreditPackage`, `PaymentMethodConfig` (country/method availability + instructions/bank/local wallet data), `AccountPaymentMethod` (account-scoped payment metadata).
- Plan/account credits and limits: `Plan.included_credits`, `Plan.max_users/sites/industries/author_profiles`, `Account.credits`.
## Execution Flow
- Credits:
- Operations call `CreditService.get_credit_cost``check_credits`/`deduct_credits` or `deduct_credits_for_operation` → updates `Account.credits`, writes `CreditTransaction` and `CreditUsageLog`.
- Costs resolved from `CreditCostConfig` when active; otherwise constants. Units support per request, per 100/200 words, per item/image/idea.
- Invoicing/Payments:
- Credit package purchase → invoice creation → next-action response (manual vs pending Stripe/PayPal integration).
- Manual payment submission → `PaymentService.create_manual_payment` persists pending approval.
- Credit balance/usage:
- Balance endpoint computes plan credits and month-to-date usage (from `CreditUsageLog`).
- Usage endpoint filters logs; summary aggregates by operation/model and totals; limits endpoint computes plan-based limits and usage (users/sites/etc.) per account.
## Cross-Module Interactions
- AI/automation/planner/writer flows trigger credit checks/deductions through `CreditService`; usage logs can be filtered by operation_type (clustering, idea_generation, content_generation, image_generation, optimization, reparse).
- Plan limits surfaced in billing limits endpoint affect account/user/site management elsewhere.
- Invoice/payment metadata may be used by frontend billing UI; manual payments require admin follow-up.
## State Transitions
- Credits mutate `Account.credits`; ledger captures each change; usage logs accumulate per operation.
- Invoices move through statuses (`draft/pending/paid/void/uncollectible`); payments through (`pending/pending_approval/processing/succeeded/completed/failed/refunded/cancelled`).
- Credit packages and payment methods have active/default flags; cost configs can be toggled active/inactive.
## Error Handling
- Insufficient credits raise `InsufficientCreditsError`; API returns 402 when caught (e.g., content generation, credit deduct flows).
- Manual payment rejects missing fields or already-paid invoices.
- Usage/balance endpoints return empty data when account/plan missing instead of hard errors.
- Validation errors on site/sector/account scoping propagate from base viewsets and model constraints.
## Tenancy Rules
- Account scoping enforced via `AccountModelViewSet` or explicit account filtering in viewsets; all billing data is per-account.
- Payment methods, invoices, payments, transactions, usage logs, and balances are filtered to `request.user.account` (or `request.account` from middleware).
- Plan data comes from the accounts associated plan; no cross-tenant visibility.
## Billing Rules
- Credit costs configurable via `CreditCostConfig`; fallback constants apply when no config.
- Credit deductions and ledger entries are atomic; usage logs record the same operation with optional model/token metadata.
- Balance endpoint includes plan monthly credits; limits endpoint reports plan/user/site limits but does not enforce them here.
## Background Tasks / Schedulers
- None specific to billing in this module; Stripe/PayPal integrations are placeholders. Any future webhooks should persist to these models and adjust credits/invoices/payments accordingly.
## Key Design Considerations
- Credit handling is centralized in `CreditService` to keep ledger and usage logs consistent.
- Usage/balance endpoints are read-mostly, with graceful handling when plan/account data is missing.
- Manual payments support bank/local wallet flows without storing sensitive data; account payment methods store display metadata only.
## How Developers Should Work With This Module
- Use `CreditService` for all credit checks/deductions/additions; do not mutate `Account.credits` directly.
- When adding new AI operations, add `operation_type` to `CreditUsageLog.OPERATION_TYPE_CHOICES` and `CreditCostConfig` seed/constants, then use `deduct_credits_for_operation`.
- Extend payment flows by implementing Stripe/PayPal handlers in `PaymentService` and wiring webhooks to update `Payment`/`Invoice`.
- Use existing serializers/viewsets when exposing billing data; keep queries scoped to `request.account`.

View File

@@ -0,0 +1,80 @@
# Credit System
## Purpose
Detail how credits are priced, checked, deducted, logged, and reported across the platform.
## Code Locations (exact paths)
- Credit logic: `backend/igny8_core/business/billing/services/credit_service.py`
- Credit costs config: `backend/igny8_core/business/billing/models.py` (`CreditCostConfig`)
- Ledger and usage logs: `backend/igny8_core/business/billing/models.py` (`CreditTransaction`, `CreditUsageLog`)
- API endpoints: `backend/igny8_core/modules/billing/views.py` (`CreditBalanceViewSet`, `CreditUsageViewSet`)
- Constants and exceptions: `backend/igny8_core/business/billing/constants.py`, `exceptions.py`
- Plan included credits: `backend/igny8_core/auth/models.py` (`Plan.included_credits`, `Account.credits`)
## High-Level Responsibilities
- Compute operation costs (configurable per operation and unit) and enforce sufficient balance before AI/content actions.
- Deduct or add credits atomically while writing both transaction and usage log records.
- Provide balance, usage history, summaries, and limits endpoints for clients.
- Allow admin-configurable cost overrides via `CreditCostConfig`.
## Detailed Behavior
- Cost resolution (`CreditService.get_credit_cost`):
- First checks `CreditCostConfig` for the operation (active records). Supports units: `per_request`, `per_100_words`, `per_200_words`, `per_item`, `per_image`. Applies amounts when provided (e.g., words, items, images).
- Falls back to hardcoded `CREDIT_COSTS` constants; raises `CreditCalculationError` for unknown operations.
- Legacy variable costs: content_generation per 100 words, optimization per 200 words, image_generation per image, idea_generation per idea.
- Balance enforcement:
- `check_credits`/`check_credits_legacy` raise `InsufficientCreditsError` when balance insufficient.
- `deduct_credits_for_operation` computes cost, checks balance, builds a default description per operation when not supplied, then calls `deduct_credits`.
- Deduction (`deduct_credits`):
- Atomic: decrements `Account.credits`, writes `CreditTransaction` with negative amount and balance_after, writes `CreditUsageLog` capturing operation_type, cost_usd/model/tokens/related object references, metadata.
- Add credits (`add_credits`):
- Atomic: increments `Account.credits`, writes `CreditTransaction` with positive amount and balance_after.
- Logging:
- `CreditTransaction` is the authoritative ledger; `CreditUsageLog` tracks per-operation usage for analytics and summaries.
- `CreditCostConfig` tracks `previous_cost` on save when cost changes.
- Reporting endpoints (modules/billing):
- `CreditBalanceViewSet.list`: returns current credits, plan monthly credits, credits used this month (from `CreditUsageLog`), and remaining credits.
- `CreditUsageViewSet.list`: paginated usage logs filtered by operation_type and date range, account-scoped.
- `CreditUsageViewSet.summary`: aggregates credits and USD cost by operation and model over a date range (defaults to current month).
- `CreditUsageViewSet.limits`: returns plan limits (users/sites/industries/author profiles) and current usage counts, plus credits info; returns empty limits if account/plan missing.
## Data Structures / Models Involved (no code)
- `CreditCostConfig`: operation_type, credits_cost, unit, display_name, description, is_active, previous_cost, updated_by, timestamps.
- `CreditTransaction`: transaction_type (purchase/subscription/refund/deduction/adjustment), amount (+/-), balance_after, description, metadata, reference_id, created_at.
- `CreditUsageLog`: operation_type (clustering/idea_generation/content_generation/image_generation/reparse/legacy names), credits_used, cost_usd, model_used, tokens_in/out, related object type/id, metadata, created_at.
- `Account.credits`: current balance; `Plan.included_credits`: monthly included credits.
## Execution Flow
- Caller requests an operation → `get_credit_cost` computes cost → `check_credits` ensures balance → `deduct_credits` mutates balance and writes ledger + usage → upstream operation proceeds (AI/content).
- Balance/usage endpoints read from `Account`, `CreditUsageLog`, `Plan` to present current balances, month-to-date usage, summaries, and limits.
## Cross-Module Interactions
- AI/automation/planner/writer services call `CreditService` before expensive operations; automation aggregates credits used per stage from AI task logs, while billing logs capture actual deductions at AI call sites.
- Plan limits (users/sites/industries/authors) referenced in billing limits endpoint inform account management elsewhere.
## State Transitions
- Balance changes recorded per transaction; usage accumulates per operation. Cost configs can be toggled active/inactive and updated with audit of previous cost.
## Error Handling
- Unknown operation types raise `CreditCalculationError`; insufficient balance raises `InsufficientCreditsError` (mapped to HTTP 402 in callers).
- Balance/usage endpoints fall back to zeros/empty when account/plan missing rather than erroring.
## Tenancy Rules
- All credit operations and queries are account-scoped; viewsets filter by `request.account`/`request.user.account`. No cross-tenant access.
## Billing Rules
- Costs derived from `CreditCostConfig` > constants; units must match supplied amount. Ledger and usage logs are mandatory for every deduction/addition.
## Background Tasks / Schedulers
- None dedicated; credit usage often originates from AI Celery tasks but logging happens at the service call site.
## Key Design Considerations
- Centralized credit math and atomic DB updates prevent drift between balance, ledger, and usage logs.
- Configurable costs allow runtime tuning without code changes.
- Reporting endpoints are read-only and tolerant of missing plan data to keep dashboards resilient.
## How Developers Should Work With This Module
- Always route credit checks/deductions/additions through `CreditService`.
- When adding new AI operations, register operation_type in `CreditUsageLog`/constants and optionally seed `CreditCostConfig`.
- Include amount (words/items/images) when calling `deduct_credits_for_operation` so unit-based pricing applies.
- Use balance/usage endpoints for UI/analytics; avoid custom queries that bypass account scoping.