# 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:**
1. AI call completes
2. OpenAI returns actual token usage
3. Calculate: `total_tokens = input_tokens + output_tokens`
4. Look up `CreditCostConfig` for operation
5. Apply formula based on unit:
   - `per_100_words`: `credits = ceil(words / 100) * cost`
   - `per_item`: `credits = items * cost`
6. Apply minimum credits
7. Deduct from balance

### Method 2: Fixed Cost (Image Models)

Used for: Image Generation

**Flow:**
1. Before AI call
2. Calculate: `credits = num_images * cost_per_image`
3. Check balance sufficient
4. Deduct credits
5. 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

```python
CreditService.check_credits(account, required_credits)
# Raises InsufficientCreditsError if balance < required
```

### Deduct Credits

```python
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

```python
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:**
1. **Current Plan** - Active plan, upgrade options
2. **Credits Overview** - Balance, usage chart, cost breakdown
3. **Purchase Credits** - Credit packages
4. **Billing History** - Invoices and transactions

### Usage Analytics (`/account/usage`)

**Tabs:**
1. **Limits & Usage** - Plan limits with progress bars
2. **Activity** - Credit transaction history
3. **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 |
