7.2 KiB
7.2 KiB
Billing Module
Last Verified: December 25, 2025
Status: ✅ Active
Backend Path: backend/igny8_core/modules/billing/ + backend/igny8_core/business/billing/
Frontend Path: frontend/src/pages/Billing/ + frontend/src/pages/Account/
Quick Reference
| What | File | Key Items |
|---|---|---|
| Models | business/billing/models.py |
CreditTransaction, CreditUsageLog, CreditCostConfig |
| Service | business/billing/services/credit_service.py |
CreditService |
| Views | modules/billing/views.py |
CreditBalanceViewSet, CreditUsageViewSet |
| Frontend | pages/Account/PlansAndBillingPage.tsx |
Plans, credits, billing history |
| Store | store/billingStore.ts |
useBillingStore |
Purpose
The Billing module manages:
- Credit balance and transactions
- Usage tracking and limits
- Plan enforcement
- Payment processing
Data Models
CreditTransaction (Ledger)
| Field | Type | Purpose |
|---|---|---|
| account | FK | Owner account |
| transaction_type | CharField | purchase/subscription/refund/deduction/adjustment |
| amount | Decimal | Positive (add) or negative (deduct) |
| balance_after | Decimal | Balance after transaction |
| description | CharField | Transaction description |
| metadata | JSON | Additional data |
| reference_id | CharField | External reference |
| created_at | DateTime | Transaction time |
CreditUsageLog (Analytics)
| Field | Type | Purpose |
|---|---|---|
| account | FK | Owner account |
| operation_type | CharField | clustering/idea_generation/content_generation/image_generation |
| credits_used | Decimal | Credits consumed |
| cost_usd | Decimal | USD cost |
| model_used | CharField | AI model used |
| tokens_in | Integer | Input tokens |
| tokens_out | Integer | Output tokens |
| content_type | FK | Related content type |
| object_id | Integer | Related object ID |
| metadata | JSON | Additional data |
| created_at | DateTime | Usage time |
CreditCostConfig
| Field | Type | Purpose |
|---|---|---|
| operation_type | CharField | Operation name |
| credits_cost | Decimal | Credits per unit |
| unit | CharField | per_request/per_100_words/per_200_words/per_item/per_image |
| display_name | CharField | UI display name |
| description | TextField | Description |
| is_active | Boolean | Enable/disable |
| previous_cost | Decimal | Previous cost (audit) |
| updated_by | FK | Last updater |
Credit Calculation Methods
Method 1: Token-Based (Text Models)
Used for: Clustering, Ideas, Content Generation, Optimization
Flow:
- AI call completes
- OpenAI returns actual token usage
- Calculate:
total_tokens = input_tokens + output_tokens - Look up
CreditCostConfigfor operation - Apply formula based on unit:
per_100_words:credits = ceil(words / 100) * costper_item:credits = items * cost
- Apply minimum credits
- Deduct from balance
Method 2: Fixed Cost (Image Models)
Used for: Image Generation
Flow:
- Before AI call
- Calculate:
credits = num_images * cost_per_image - Check balance sufficient
- Deduct credits
- Then make AI call
API Endpoints
| Method | Path | Handler | Purpose |
|---|---|---|---|
| GET | /api/v1/billing/balance/ |
CreditBalanceViewSet.list |
Current balance + monthly usage |
| GET | /api/v1/billing/usage/ |
CreditUsageViewSet.list |
Usage log (paginated) |
| GET | /api/v1/billing/usage/summary/ |
CreditUsageViewSet.summary |
Aggregated by operation |
| GET | /api/v1/billing/usage/limits/ |
CreditUsageViewSet.limits |
Plan limits + current usage |
| GET | /api/v1/billing/transactions/ |
TransactionViewSet.list |
Transaction history |
Credit Service API
Check Credits
CreditService.check_credits(account, required_credits)
# Raises InsufficientCreditsError if balance < required
Deduct Credits
CreditService.deduct_credits_for_operation(
account=account,
operation_type='content_generation',
amount=word_count, # For per_word operations
model='gpt-4o-mini',
tokens_in=2500,
tokens_out=1500,
metadata={'content_id': 123}
)
Add Credits
CreditService.add_credits(
account=account,
amount=1000,
transaction_type='purchase',
description='Credit package purchase'
)
Plan Limits
Hard Limits (Never Reset)
| Limit | Field | Description |
|---|---|---|
| Sites | max_sites |
Maximum sites per account |
| Users | max_users |
Maximum team members |
| Keywords | max_keywords |
Total keywords allowed |
| Clusters | max_clusters |
Total clusters allowed |
Monthly Limits (Reset on Billing Cycle)
| Limit | Field | Description |
|---|---|---|
| Content Ideas | max_content_ideas |
Ideas per month |
| Content Words | max_content_words |
Words generated per month |
| Basic Images | max_images_basic |
Basic AI images per month |
| Premium Images | max_images_premium |
Premium AI images per month |
| Image Prompts | max_image_prompts |
Prompts per month |
Usage Limits Panel
Component: UsageLimitsPanel.tsx
Displays:
- Progress bars for each limit
- Color coding: blue (safe), yellow (warning), red (critical)
- Days until reset for monthly limits
- Upgrade CTA when approaching limits
Credit Costs Reference
Current costs (from CreditCostConfig):
| Operation | Unit | Default Cost |
|---|---|---|
| Clustering | per_request | 10 credits |
| Idea Generation | per_item | 2 credits |
| Content Generation | per_100_words | 5 credits |
| Image Generation (Basic) | per_image | 3 credits |
| Image Generation (Premium) | per_image | 5 credits |
| Content Optimization | per_200_words | 3 credits |
Frontend Pages
Plans & Billing (/account/plans)
Tabs:
- Current Plan - Active plan, upgrade options
- Credits Overview - Balance, usage chart, cost breakdown
- Purchase Credits - Credit packages
- Billing History - Invoices and transactions
Usage Analytics (/account/usage)
Tabs:
- Limits & Usage - Plan limits with progress bars
- Activity - Credit transaction history
- API Usage - API call statistics
Integration Points
| From | To | Trigger |
|---|---|---|
| AIEngine | CreditService | Pre-check and post-deduct |
| Automation | CreditService | Per-stage credit tracking |
| Subscription | Account | Credit allocation |
| Admin | CreditCostConfig | Price adjustments |
Common Issues
| Issue | Cause | Fix |
|---|---|---|
| 402 error | Insufficient credits | Add credits or reduce operation |
| Usage not showing | Log not created | Check CreditService called |
| Limits wrong | Cache stale | Clear cache, reload |
| Monthly usage high | Automation running | Pause automation |
Planned Changes
| Feature | Status | Description |
|---|---|---|
| AI Model Config database | 🔜 Planned | Move model pricing to database |
| Budget alerts | 🔜 Planned | Email when approaching limits |
| Usage forecasting | 🔜 Planned | Predict credit usage |
| Overage billing | 🔜 Planned | Charge for overages instead of blocking |