Files
igny8/docs/working-docs/Original-plan-may-have-wrong-logic.md
IGNY8 VPS (Salman) d92a99ecc3 some-improvement
2025-12-05 05:38:58 +00:00

1450 lines
37 KiB
Markdown

# SaaS Platform Standardization Plan
**Date:** December 4, 2025
**Status:** 🎯 PHASE 1 COMPLETE - Backend Models Ready
**Priority:** CRITICAL - Core SaaS Infrastructure
**Implementation Progress:**
- ✅ All backend models created (Invoice, Payment, CreditPackage, PaymentMethodConfig)
- ✅ Account model updated with billing address fields
- ✅ Multi-payment gateway support (Stripe, PayPal, Manual)
- ✅ Per-country payment configuration
- ⏳ Ready for database migrations
- 📋 See IMPLEMENTATION-GUIDE-DEC-4-2025.md for detailed task breakdown
- 📄 See SESSION-SUMMARY-DEC-4-2025.md for current status
---
## 📋 EXECUTIVE SUMMARY
This document provides a comprehensive, standardized plan for IGNY8's SaaS infrastructure covering:
- User Management & Access Control
- Account/Tenant Management (Multi-tenancy)
- Plans & Subscriptions
- Credits System & Usage Tracking
- Billing, Invoices & Payments
- Account Limits & Quotas
- Frontend UI Standardization
- Admin Controls & Configuration
**Current State:**
✅ Multi-tenancy implemented
✅ Credits system fully functional
✅ Basic billing UI exists
⚠️ Payment integration NOT implemented
⚠️ Invoice generation NOT implemented
⚠️ Subscription management incomplete
⚠️ UI fragmented across multiple menus
**Goal:** Create a best-practice SaaS platform with clear separation of concerns, proper admin controls, and streamlined user experience.
---
## 🏗️ ARCHITECTURE OVERVIEW
### Multi-Tenant Architecture
```
┌─────────────────────────────────────────────────────────────────┐
│ IGNY8 SAAS PLATFORM │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ACCOUNT (Tenant) │
│ ├─ Owner + Users (Role-based) │
│ ├─ Plan (Subscription Tier) │
│ ├─ Credits Balance │
│ ├─ Sites (1-N based on plan) │
│ ├─ Subscription (Stripe integration) │
│ └─ Billing Data (Transactions, Usage, Invoices) │
│ │
│ USER │
│ ├─ Role (developer, owner, admin, editor, viewer) │
│ ├─ Account (tenant_id) │
│ └─ Site Access (multi-site accounts) │
│ │
│ PLAN │
│ ├─ Price & Billing Cycle │
│ ├─ Included Credits/Month │
│ ├─ Account Limits (sites, users, etc.) │
│ └─ Stripe Product/Price IDs │
│ │
│ CREDITS SYSTEM │
│ ├─ Account Balance │
│ ├─ Transactions (purchase, grant, deduction, refund) │
│ ├─ Usage Logs (per AI operation) │
│ └─ Cost Config (admin-configurable) │
│ │
└─────────────────────────────────────────────────────────────────┘
```
---
## 🎯 CORE ENTITIES & RELATIONSHIPS
### 1. Account (Tenant)
**Current Model:** `igny8_core.auth.models.Account`
**Fields:**
```python
- id (PK)
- name
- slug (unique)
- owner (FK User)
- plan (FK Plan)
- credits (integer)
- stripe_customer_id
- status (active, suspended, trial, cancelled)
- created_at, updated_at
```
**Status:** ✅ Working - Well implemented
**Relationships:**
- 1 Account → Many Users
- 1 Account → 1 Plan (current plan)
- 1 Account → 1 Subscription (optional, Stripe)
- 1 Account → Many Sites
- 1 Account → Many CreditTransactions
- 1 Account → Many CreditUsageLogs
---
### 2. User
**Current Model:** `igny8_core.auth.models.User`
**Fields:**
```python
- id (PK)
- email (unique, username)
- account (FK Account, tenant_id)
- role (developer, owner, admin, editor, viewer, system_bot)
- is_active, is_staff, is_superuser
- created_at, updated_at
```
**Roles Hierarchy:**
- **developer**: Super admin, all access, bypasses multi-tenancy
- **owner**: Account owner, full account access
- **admin**: Account admin, full account access
- **editor**: Can edit content, limited settings
- **viewer**: Read-only access
**Status:** ✅ Working - Well implemented
**Gaps to Address:**
- [ ] Add user invitation system
- [ ] Add user activity tracking
- [ ] Add last_login tracking per site
---
### 3. Plan
**Current Model:** `igny8_core.auth.models.Plan`
**Fields:**
```python
- id (PK)
- name, slug (unique)
- price (Decimal)
- billing_cycle (monthly, annual)
- included_credits (monthly allocation)
- extra_credit_price (price per additional credit)
- allow_credit_topup (boolean)
- max_users, max_sites, max_industries, max_author_profiles
- stripe_product_id, stripe_price_id
- is_active
- features (JSON array)
```
**Status:** ✅ Working - Well designed
**Recommended Plans Structure:**
#### Free Plan
- Price: $0/month
- Credits: 100/month
- Sites: 1
- Users: 1
- Features: Basic AI tools
#### Starter Plan
- Price: $29/month
- Credits: 1,000/month
- Sites: 3
- Users: 2
- Features: Full AI suite, automation
#### Professional Plan
- Price: $99/month
- Credits: 5,000/month
- Sites: 10
- Users: 5
- Features: Priority support, advanced analytics
#### Enterprise Plan
- Price: $299/month
- Credits: 20,000/month
- Sites: Unlimited
- Users: 20
- Features: Custom integrations, dedicated support
---
### 4. Subscription
**Current Model:** `igny8_core.auth.models.Subscription`
**Fields:**
```python
- id (PK)
- account (OneToOne Account)
- stripe_subscription_id (unique)
- status (active, past_due, canceled, trialing)
- current_period_start, current_period_end
- cancel_at_period_end
- created_at, updated_at
```
**Status:** ⚠️ Model exists but Stripe integration NOT implemented
**Missing Features:**
- [ ] Stripe webhook handlers
- [ ] Subscription creation flow
- [ ] Plan upgrade/downgrade
- [ ] Cancellation flow
- [ ] Trial period management
- [ ] Past due handling
---
### 5. Credit System
#### CreditTransaction
**Current Model:** `igny8_core.business.billing.models.CreditTransaction`
**Fields:**
```python
- id (PK)
- account (FK)
- transaction_type (purchase, subscription, refund, deduction, adjustment)
- amount (integer, +/-)
- balance_after
- description
- metadata (JSON)
- created_at
```
**Status:** ✅ Working perfectly
#### CreditUsageLog
**Current Model:** `igny8_core.business.billing.models.CreditUsageLog`
**Fields:**
```python
- id (PK)
- account (FK)
- operation_type (clustering, idea_generation, content_generation, etc.)
- credits_used
- cost_usd (Decimal)
- model_used (AI model name)
- tokens_input, tokens_output
- related_object_type, related_object_id
- metadata (JSON)
- created_at
```
**Status:** ✅ Working perfectly
#### CreditCostConfig
**Current Model:** `igny8_core.business.billing.models.CreditCostConfig`
**Fields:**
```python
- id (PK)
- operation_type (unique)
- credits_cost
- unit (per_request, per_100_words, per_image, etc.)
- display_name, description
- is_active
- updated_by (FK User)
- previous_cost (audit trail)
- created_at, updated_at
```
**Status:** ✅ Implemented (Dec 4, 2025)
**Operations & Costs:**
| Operation | Cost | Unit |
|-----------|------|------|
| Auto Clustering | 10 | per_request |
| Idea Generation | 15 | per_request |
| Content Generation | 1 | per_100_words |
| Image Prompt Extraction | 2 | per_request |
| Image Generation | 5 | per_image |
| Content Linking | 8 | per_request |
| Optimization | 1 | per_200_words |
| Site Structure | 50 | per_request |
| Site Page Gen | 20 | per_item |
---
## ❌ MISSING COMPONENTS (TO IMPLEMENT)
### 1. Invoice Model
**Purpose:** Track billing invoices for payments
**Proposed Model:**
```python
class Invoice(AccountBaseModel):
"""
Invoice for subscription or credit purchases
"""
STATUS_CHOICES = [
('draft', 'Draft'),
('pending', 'Pending'),
('paid', 'Paid'),
('void', 'Void'),
('uncollectible', 'Uncollectible'),
]
invoice_number = models.CharField(max_length=50, unique=True)
subscription = models.ForeignKey(Subscription, null=True, on_delete=SET_NULL)
# Amounts
subtotal = models.DecimalField(max_digits=10, decimal_places=2)
tax = models.DecimalField(max_digits=10, decimal_places=2, default=0)
total = models.DecimalField(max_digits=10, decimal_places=2)
# Status
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
# Dates
invoice_date = models.DateField()
due_date = models.DateField()
paid_at = models.DateTimeField(null=True)
# Line items
line_items = models.JSONField(default=list) # [{description, amount, quantity}]
# Payment
stripe_invoice_id = models.CharField(max_length=255, null=True)
payment_method = models.CharField(max_length=50, null=True) # 'stripe', 'manual'
# Metadata
notes = models.TextField(blank=True)
metadata = models.JSONField(default=dict)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
```
**Priority:** HIGH - Required for payment tracking
---
### 2. Payment Model
**Purpose:** Track individual payments
**Proposed Model:**
```python
class Payment(AccountBaseModel):
"""
Payment record for invoice or credit purchase
Supports: Stripe, PayPal, Manual (Bank Transfer, Local Wallet)
"""
STATUS_CHOICES = [
('pending', 'Pending'),
('processing', 'Processing'),
('succeeded', 'Succeeded'),
('failed', 'Failed'),
('refunded', 'Refunded'),
('cancelled', 'Cancelled'),
]
PAYMENT_METHOD_CHOICES = [
('stripe', 'Stripe (Credit/Debit Card)'),
('paypal', 'PayPal'),
('bank_transfer', 'Bank Transfer (Manual)'),
('local_wallet', 'Local Wallet (Manual)'),
('manual', 'Manual Payment'),
]
invoice = models.ForeignKey(Invoice, on_delete=CASCADE, related_name='payments')
# Amount
amount = models.DecimalField(max_digits=10, decimal_places=2)
currency = models.CharField(max_length=3, default='USD')
# Status
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
# Payment method
payment_method = models.CharField(max_length=50, choices=PAYMENT_METHOD_CHOICES)
# Stripe integration
stripe_payment_intent_id = models.CharField(max_length=255, null=True, blank=True)
stripe_charge_id = models.CharField(max_length=255, null=True, blank=True)
# PayPal integration
paypal_order_id = models.CharField(max_length=255, null=True, blank=True)
paypal_capture_id = models.CharField(max_length=255, null=True, blank=True)
# Manual payment details
manual_reference = models.CharField(max_length=255, blank=True, help_text="Bank transfer reference, wallet transaction ID, etc.")
manual_notes = models.TextField(blank=True, help_text="Admin notes for manual payments")
approved_by = models.ForeignKey('auth.User', null=True, blank=True, on_delete=SET_NULL, related_name='approved_payments')
approved_at = models.DateTimeField(null=True, blank=True)
# Timestamps
processed_at = models.DateTimeField(null=True)
failed_at = models.DateTimeField(null=True)
refunded_at = models.DateTimeField(null=True)
# Error tracking
failure_reason = models.TextField(blank=True)
# Metadata
metadata = models.JSONField(default=dict)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
```
**Priority:** HIGH
---
### 3. CreditPackage Model
**Purpose:** Define purchasable credit bundles
**Proposed Model:**
```python
class CreditPackage(models.Model):
"""
One-time credit purchase packages
"""
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
# Credits
credits = models.IntegerField(validators=[MinValueValidator(1)])
# Pricing
price = models.DecimalField(max_digits=10, decimal_places=2)
discount_percentage = models.IntegerField(default=0) # Optional discount
# Stripe
stripe_product_id = models.CharField(max_length=255, null=True)
stripe_price_id = models.CharField(max_length=255, null=True)
# Status
is_active = models.BooleanField(default=True)
is_featured = models.BooleanField(default=False)
# Display
description = models.TextField(blank=True)
features = models.JSONField(default=list) # Bonus features
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
```
**Recommended Packages:**
- Starter: 500 credits - $9
- Pro: 2,000 credits - $29 (10% discount)
- Business: 5,000 credits - $69 (15% discount)
- Enterprise: 20,000 credits - $249 (20% discount)
**Priority:** MEDIUM
---
### 4. AccountLimit Model (Optional)
**Purpose:** Track dynamic account limits and usage
**Proposed Model:**
```python
class AccountLimit(AccountBaseModel):
"""
Track account limits and current usage
"""
LIMIT_TYPE_CHOICES = [
('sites', 'Sites'),
('users', 'Users'),
('keywords', 'Keywords'),
('content_items', 'Content Items'),
('api_calls_per_day', 'API Calls Per Day'),
]
limit_type = models.CharField(max_length=50, choices=LIMIT_TYPE_CHOICES)
max_allowed = models.IntegerField()
current_usage = models.IntegerField(default=0)
# Metadata
reset_period = models.CharField(max_length=20, null=True) # 'daily', 'monthly', 'never'
last_reset = models.DateTimeField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
unique_together = [['account', 'limit_type']]
```
**Priority:** LOW - Can use Plan limits directly
---
### 5. PaymentMethodConfig Model
**Purpose:** Configure which payment methods are enabled per country
**Proposed Model:**
```python
class PaymentMethodConfig(models.Model):
"""
Configure payment methods availability per country
Allows enabling/disabling manual payments by region
"""
PAYMENT_METHOD_CHOICES = [
('stripe', 'Stripe'),
('paypal', 'PayPal'),
('bank_transfer', 'Bank Transfer'),
('local_wallet', 'Local Wallet'),
]
country_code = models.CharField(max_length=2, help_text="ISO 2-letter country code (e.g., US, GB, IN)")
payment_method = models.CharField(max_length=50, choices=PAYMENT_METHOD_CHOICES)
is_enabled = models.BooleanField(default=True)
# Display info
display_name = models.CharField(max_length=100, blank=True)
instructions = models.TextField(blank=True, help_text="Payment instructions for users")
# Manual payment details (for bank_transfer/local_wallet)
bank_name = models.CharField(max_length=255, blank=True)
account_number = models.CharField(max_length=255, blank=True)
routing_number = models.CharField(max_length=255, blank=True)
swift_code = models.CharField(max_length=255, blank=True)
# Order/priority
sort_order = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
unique_together = [['country_code', 'payment_method']]
ordering = ['country_code', 'sort_order']
```
**Priority:** MEDIUM - Required for regional payment flexibility
---
## 🎨 FRONTEND UI STANDARDIZATION
### Current UI State
**User Menu Structure (Non-Admin):**
```
Settings (collapsible)
├─ General
├─ Plans
├─ Integration
├─ Publishing
└─ Import / Export
Billing (collapsible)
├─ Overview
├─ Credits
├─ Transactions
└─ Usage
Help & Documentation
```
**Admin Menu Structure (aws-admin only):**
```
ADMIN
├─ Billing & Credits (collapsible)
│ ├─ Billing Management
│ └─ Credit Costs
├─ User Management (collapsible)
│ ├─ Users
│ └─ Subscriptions
├─ Configuration (collapsible)
│ ├─ System Settings
│ ├─ Account Settings
│ └─ Module Settings
├─ AI Controls (collapsible)
│ └─ AI Settings
├─ System Health (collapsible)
│ ├─ Status
│ ├─ API Monitor
│ └─ Debug Status
└─ Testing Tools, UI Elements...
```
---
### ⚠️ PROBLEMS WITH CURRENT UI
1. **Fragmented Billing Info**
- Credits, Transactions, Usage in separate pages
- No unified billing dashboard
- Purchase flow not visible
2. **Missing Subscription Management**
- No plan upgrade/downgrade UI
- No subscription status visibility
- No payment method management
3. **Admin Controls Scattered**
- User management in settings
- Billing in separate admin section
- No unified admin dashboard
4. **No Account Settings Page**
- Account name, billing address missing
- Team management incomplete
- Account limits not visible
---
### ✅ PROPOSED UI STRUCTURE
#### User Menu (All Users)
```
Dashboard
SETUP
├─ Add Keywords
├─ Sites
└─ Thinker (if enabled)
WORKFLOW
├─ Planner (if enabled)
├─ Writer (if enabled)
├─ Automation (if enabled)
├─ Linker (if enabled)
└─ Optimizer (if enabled)
ACCOUNT (NEW SECTION)
├─ Account Settings (NEW)
│ └─ Account Info, Billing Address, Team
├─ Plans & Billing (CONSOLIDATED)
│ ├─ Current Plan
│ ├─ Upgrade/Downgrade
│ ├─ Credits Overview
│ ├─ Purchase Credits
│ ├─ Billing History (Invoices)
│ └─ Payment Methods
├─ Team Management (NEW)
│ ├─ Users
│ ├─ Invitations
│ └─ Access Control
└─ Usage & Analytics (NEW)
├─ Credit Usage
├─ API Usage
└─ Cost Breakdown
SETTINGS (Personal)
├─ Profile Settings
├─ Integration
├─ Publishing
└─ Import / Export
HELP & DOCS
```
#### Admin Menu (Superuser Only)
```
ADMIN
├─ System Dashboard (NEW)
│ └─ Overview, Stats, Alerts
├─ Account Management (NEW)
│ ├─ All Accounts
│ ├─ Subscriptions
│ └─ Account Limits
├─ Billing Administration
│ ├─ Billing Overview
│ ├─ Invoices
│ ├─ Payments
│ ├─ Credit Costs Config
│ └─ Credit Packages
├─ User Administration
│ ├─ All Users
│ ├─ Roles & Permissions
│ └─ Activity Logs
├─ System Configuration
│ ├─ System Settings
│ ├─ AI Settings
│ ├─ Module Settings
│ └─ Integration Settings
├─ Monitoring
│ ├─ System Health
│ ├─ API Monitor
│ └─ Usage Analytics
└─ Developer Tools
├─ Function Testing
├─ System Testing
└─ UI Elements
```
---
## 📄 NEW PAGES TO CREATE
### 1. Account Settings Page
**Path:** `/account/settings`
**Access:** Owner, Admin
**Sections:**
- Account Information (name, slug, status)
- Billing Address
- Tax Information
- Account Limits (sites, users, credits)
- Danger Zone (delete account, transfer ownership)
**Priority:** HIGH
---
### 2. Plans & Billing Page (Consolidated)
**Path:** `/account/billing`
**Access:** Owner, Admin
**Tabs:**
1. **Current Plan**
- Plan details, included credits
- Upgrade/downgrade buttons
- Subscription status
2. **Credits**
- Current balance
- Monthly included
- Purchase credits (packages)
- Usage this month
3. **Billing History**
- Invoices table
- Download PDF
- Payment status
4. **Payment Methods**
- Saved cards
- Add/remove methods
- Default payment method
**Priority:** HIGH
---
### 3. Team Management Page
**Path:** `/account/team`
**Access:** Owner, Admin
**Features:**
- List team members
- Invite users (email invitation)
- Manage roles
- Remove users
- Site access control (multi-site accounts)
**Priority:** MEDIUM
---
### 4. Usage & Analytics Page
**Path:** `/account/usage`
**Access:** All users (filtered by role)
**Charts:**
- Credit usage over time
- Cost breakdown by operation
- API calls per day
- Top consuming operations
**Priority:** MEDIUM
---
### 5. Purchase Credits Page
**Path:** `/account/credits/purchase`
**Access:** Owner, Admin
**Features:**
- Credit packages display
- Stripe checkout integration
- Payment confirmation
- Credits added to balance
**Priority:** HIGH
---
### 6. Invoices Page
**Path:** `/account/invoices`
**Access:** Owner, Admin
**Features:**
- Invoice list (table)
- Filter by status, date
- Download PDF
- View details
- Payment status
**Priority:** HIGH
---
### 7. Admin: All Accounts Page
**Path:** `/admin/accounts`
**Access:** Superuser only
**Features:**
- Search accounts
- Filter by status, plan
- View account details
- Adjust credits
- Suspend/activate accounts
**Priority:** MEDIUM
---
### 8. Admin: System Dashboard
**Path:** `/admin/dashboard`
**Access:** Superuser only
**Metrics:**
- Total accounts
- Active subscriptions
- Revenue this month
- Credits issued/used
- System health status
**Priority:** MEDIUM
---
## 🔌 PAYMENT INTEGRATION PLAN
### Stripe Integration
**Status:** ⚠️ NOT IMPLEMENTED (fields exist but no webhooks/flows)
**Required Components:**
#### 1. Stripe Setup
```python
# settings.py
STRIPE_PUBLIC_KEY = env('STRIPE_PUBLIC_KEY')
STRIPE_SECRET_KEY = env('STRIPE_SECRET_KEY')
STRIPE_WEBHOOK_SECRET = env('STRIPE_WEBHOOK_SECRET')
```
#### 2. Webhook Handlers
**File:** `backend/igny8_core/business/billing/webhooks.py`
```python
@csrf_exempt
def stripe_webhook(request):
"""Handle Stripe webhooks"""
payload = request.body
sig_header = request.META.get('HTTP_STRIPE_SIGNATURE')
try:
event = stripe.Webhook.construct_event(
payload, sig_header, settings.STRIPE_WEBHOOK_SECRET
)
except ValueError:
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError:
return HttpResponse(status=400)
# Handle events
if event['type'] == 'invoice.paid':
handle_invoice_paid(event['data']['object'])
elif event['type'] == 'invoice.payment_failed':
handle_payment_failed(event['data']['object'])
elif event['type'] == 'customer.subscription.deleted':
handle_subscription_deleted(event['data']['object'])
elif event['type'] == 'customer.subscription.updated':
handle_subscription_updated(event['data']['object'])
return HttpResponse(status=200)
```
**Priority:** CRITICAL
#### 3. Subscription Creation Flow
**API Endpoint:** `POST /v1/billing/subscriptions/create/`
```python
@action(detail=False, methods=['post'])
def create_subscription(self, request):
"""Create Stripe subscription"""
plan_id = request.data.get('plan_id')
payment_method_id = request.data.get('payment_method_id')
plan = Plan.objects.get(id=plan_id)
account = request.user.account
# Create or retrieve Stripe customer
if not account.stripe_customer_id:
customer = stripe.Customer.create(
email=request.user.email,
name=account.name,
payment_method=payment_method_id,
invoice_settings={'default_payment_method': payment_method_id}
)
account.stripe_customer_id = customer.id
account.save()
# Create subscription
subscription = stripe.Subscription.create(
customer=account.stripe_customer_id,
items=[{'price': plan.stripe_price_id}],
payment_behavior='default_incomplete',
expand=['latest_invoice.payment_intent']
)
# Save subscription
Subscription.objects.create(
account=account,
stripe_subscription_id=subscription.id,
status=subscription.status,
current_period_start=datetime.fromtimestamp(subscription.current_period_start),
current_period_end=datetime.fromtimestamp(subscription.current_period_end)
)
return Response({
'subscription_id': subscription.id,
'client_secret': subscription.latest_invoice.payment_intent.client_secret
})
```
**Priority:** CRITICAL
#### 4. Credit Purchase Flow
**API Endpoint:** `POST /v1/billing/credits/purchase/`
```python
@action(detail=False, methods=['post'])
def purchase_credits(self, request):
"""Purchase credit package"""
package_id = request.data.get('package_id')
package = CreditPackage.objects.get(id=package_id)
account = request.user.account
# Create payment intent
intent = stripe.PaymentIntent.create(
amount=int(package.price * 100), # Convert to cents
currency='usd',
customer=account.stripe_customer_id,
metadata={
'account_id': account.id,
'package_id': package.id,
'credits': package.credits
}
)
return Response({
'client_secret': intent.client_secret,
'package': CreditPackageSerializer(package).data
})
```
**Priority:** HIGH
---
## 🔐 ACCESS CONTROL & PERMISSIONS
### Role-Based Permissions
| Feature | Developer | Owner | Admin | Editor | Viewer |
|---------|-----------|-------|-------|--------|--------|
| View Account Settings | ✅ | ✅ | ✅ | ❌ | ❌ |
| Edit Account Settings | ✅ | ✅ | ❌ | ❌ | ❌ |
| View Billing | ✅ | ✅ | ✅ | ❌ | ❌ |
| Purchase Credits | ✅ | ✅ | ✅ | ❌ | ❌ |
| Manage Subscription | ✅ | ✅ | ❌ | ❌ | ❌ |
| Invite Users | ✅ | ✅ | ✅ | ❌ | ❌ |
| Manage User Roles | ✅ | ✅ | ❌ | ❌ | ❌ |
| View Usage Analytics | ✅ | ✅ | ✅ | ✅ | ✅ |
| Access Admin Panel | ✅ | ❌ | ❌ | ❌ | ❌ |
| Configure Credit Costs | ✅ | ❌ | ❌ | ❌ | ❌ |
| View All Accounts | ✅ | ❌ | ❌ | ❌ | ❌ |
---
## 📊 DATABASE MIGRATIONS REQUIRED
### New Models to Create
1. **Invoice** - HIGH priority
2. **Payment** - HIGH priority
3. **CreditPackage** - MEDIUM priority
4. **AccountLimit** (optional) - LOW priority
### Migrations to Add
```bash
# Create invoice and payment models
python manage.py makemigrations billing --name add_invoice_payment_models
# Create credit packages
python manage.py makemigrations billing --name add_credit_packages
# Add missing fields to existing models
python manage.py makemigrations auth --name add_billing_address_fields
```
---
## 🚀 IMPLEMENTATION ROADMAP
### Phase 1: Core Billing Infrastructure (Week 1-2)
**Priority:** CRITICAL
1. ✅ Create Invoice model
2. ✅ Create Payment model
3. ✅ Create CreditPackage model
4. ✅ Stripe webhook handlers
5. ✅ Subscription creation API
6. ✅ Credit purchase API
**Deliverables:**
- Functional payment processing
- Invoice generation
- Subscription management
---
### Phase 2: Frontend UI Overhaul (Week 3-4)
**Priority:** HIGH
1. ✅ Create Account Settings page
2. ✅ Consolidate Plans & Billing page
3. ✅ Create Team Management page
4. ✅ Create Purchase Credits page
5. ✅ Create Invoices page
6. ✅ Update navigation structure
**Deliverables:**
- Unified account management UI
- Streamlined billing experience
- Professional SaaS interface
---
### Phase 3: Admin Dashboard (Week 5-6)
**Priority:** MEDIUM
1. ✅ Create Admin System Dashboard
2. ✅ Create All Accounts management page
3. ✅ Create Billing Administration pages
4. ✅ Create User Administration pages
5. ✅ Add comprehensive filtering/search
**Deliverables:**
- Complete admin control panel
- Account management tools
- System monitoring
---
### Phase 4: Analytics & Reporting (Week 7-8)
**Priority:** MEDIUM
1. ✅ Create Usage & Analytics page
2. ✅ Implement cost breakdown charts
3. ✅ Add usage forecasting
4. ✅ Create PDF invoice generation
5. ✅ Add export capabilities
**Deliverables:**
- Usage insights
- Cost optimization tools
- Professional invoices
---
### Phase 5: Advanced Features (Week 9-12)
**Priority:** LOW
1. ✅ User invitation system
2. ✅ Email notifications
3. ✅ Auto top-up credits
4. ✅ Budget alerts
5. ✅ API rate limiting
6. ✅ Multi-currency support
**Deliverables:**
- Enhanced user experience
- Proactive notifications
- International expansion ready
---
## 📋 API ENDPOINTS TO IMPLEMENT
### Billing APIs
| Endpoint | Method | Purpose | Priority |
|----------|--------|---------|----------|
| `/v1/billing/account_balance/` | GET | Get credit balance | ✅ EXISTS |
| `/v1/billing/transactions/` | GET | List transactions | ✅ EXISTS |
| `/v1/billing/usage/` | GET | List usage logs | ✅ EXISTS |
| `/v1/billing/invoices/` | GET | List invoices | ❌ MISSING |
| `/v1/billing/invoices/:id/` | GET | Get invoice details | ❌ MISSING |
| `/v1/billing/invoices/:id/pdf/` | GET | Download PDF | ❌ MISSING |
| `/v1/billing/subscriptions/` | GET | Get subscription | ❌ MISSING |
| `/v1/billing/subscriptions/create/` | POST | Create subscription | ❌ MISSING |
| `/v1/billing/subscriptions/cancel/` | POST | Cancel subscription | ❌ MISSING |
| `/v1/billing/subscriptions/upgrade/` | POST | Upgrade plan | ❌ MISSING |
| `/v1/billing/credits/packages/` | GET | List credit packages | ❌ MISSING |
| `/v1/billing/credits/purchase/` | POST | Purchase credits | ❌ MISSING |
| `/v1/billing/payment-methods/` | GET | List payment methods | ❌ MISSING |
| `/v1/billing/payment-methods/` | POST | Add payment method | ❌ MISSING |
| `/v1/billing/webhooks/stripe/` | POST | Stripe webhooks | ❌ MISSING |
### Account Management APIs
| Endpoint | Method | Purpose | Priority |
|----------|--------|---------|----------|
| `/v1/account/settings/` | GET | Get account info | ❌ MISSING |
| `/v1/account/settings/` | PATCH | Update account | ❌ MISSING |
| `/v1/account/limits/` | GET | Get account limits | ❌ MISSING |
| `/v1/account/team/` | GET | List team members | ❌ MISSING |
| `/v1/account/team/invite/` | POST | Invite user | ❌ MISSING |
| `/v1/account/team/:id/` | DELETE | Remove user | ❌ MISSING |
| `/v1/account/usage/analytics/` | GET | Usage analytics | ❌ MISSING |
### Admin APIs
| Endpoint | Method | Purpose | Priority |
|----------|--------|---------|----------|
| `/v1/admin/accounts/` | GET | List all accounts | ❌ MISSING |
| `/v1/admin/accounts/:id/adjust-credits/` | POST | Adjust credits | ✅ EXISTS |
| `/v1/admin/accounts/:id/suspend/` | POST | Suspend account | ❌ MISSING |
| `/v1/admin/billing/stats/` | GET | Billing statistics | ✅ EXISTS |
| `/v1/admin/invoices/` | GET | All invoices | ❌ MISSING |
| `/v1/admin/payments/` | GET | All payments | ❌ MISSING |
| `/v1/admin/credit-costs/` | GET | Credit costs config | ✅ EXISTS |
| `/v1/admin/users/` | GET | All users | ✅ EXISTS |
---
## 🔧 BACKEND SERVICES TO CREATE
### 1. SubscriptionService
**File:** `backend/igny8_core/business/billing/services/subscription_service.py`
**Methods:**
- `create_subscription(account, plan, payment_method)`
- `cancel_subscription(subscription, cancel_at_period_end=True)`
- `upgrade_subscription(subscription, new_plan)`
- `downgrade_subscription(subscription, new_plan)`
- `reactivate_subscription(subscription)`
- `sync_from_stripe(stripe_subscription_id)`
**Priority:** CRITICAL
---
### 2. InvoiceService
**File:** `backend/igny8_core/business/billing/services/invoice_service.py`
**Methods:**
- `create_invoice(account, line_items)`
- `generate_invoice_number()`
- `mark_paid(invoice, payment)`
- `mark_void(invoice)`
- `generate_pdf(invoice)`
- `send_invoice_email(invoice)`
**Priority:** HIGH
---
### 3. PaymentService
**File:** `backend/igny8_core/business/billing/services/payment_service.py`
**Methods:**
- `process_payment(invoice, payment_method)`
- `process_refund(payment, amount)`
- `handle_payment_success(stripe_payment_intent)`
- `handle_payment_failure(stripe_payment_intent)`
- `sync_from_stripe(stripe_payment_id)`
**Priority:** HIGH
---
### 4. CreditPackageService
**File:** `backend/igny8_core/business/billing/services/credit_package_service.py`
**Methods:**
- `purchase_package(account, package, payment_method)`
- `apply_credits_to_account(account, credits, package)`
- `get_available_packages()`
**Priority:** MEDIUM
---
## 🧪 TESTING REQUIREMENTS
### Unit Tests
- [ ] CreditService operations
- [ ] SubscriptionService flows
- [ ] InvoiceService generation
- [ ] PaymentService processing
- [ ] Webhook handlers
### Integration Tests
- [ ] Full subscription creation flow
- [ ] Credit purchase end-to-end
- [ ] Stripe webhook processing
- [ ] Invoice PDF generation
- [ ] Email notifications
### E2E Tests
- [ ] User signup → plan selection → payment
- [ ] Credit purchase flow
- [ ] Plan upgrade/downgrade
- [ ] Subscription cancellation
- [ ] Team member invitation
---
## 📈 SUCCESS METRICS
### Business Metrics
- Subscription conversion rate
- Average revenue per user (ARPU)
- Customer lifetime value (LTV)
- Churn rate
- Credit consumption per account
### Technical Metrics
- Payment success rate (target: >98%)
- Webhook processing latency (target: <2s)
- Invoice generation time (target: <1s)
- API response time (target: <200ms)
- Zero credit deduction race conditions
### User Experience Metrics
- Time to first purchase
- Billing page load time
- Support tickets related to billing
- User satisfaction score
---
## 🔒 SECURITY CONSIDERATIONS
### Payment Security
- ✅ Use Stripe Elements (PCI compliant)
- ✅ Never store card details
- ✅ Use HTTPS only
- ✅ Validate webhook signatures
- ✅ Implement CSRF protection
### Access Control
- ✅ Role-based permissions enforced
- ✅ Multi-tenancy isolation verified
- ✅ Admin actions logged
- ✅ Sensitive data encrypted
- ✅ Rate limiting on payment endpoints
### Data Protection
- ✅ GDPR compliance for EU users
- ✅ PII encryption at rest
- ✅ Audit trail for all billing actions
- ✅ Regular security audits
- ✅ Data retention policies
---
## 📝 DOCUMENTATION REQUIREMENTS
### User Documentation
- [ ] How to upgrade/downgrade plans
- [ ] How to purchase credits
- [ ] How to manage team members
- [ ] How to view usage analytics
- [ ] How to download invoices
### Admin Documentation
- [ ] How to configure credit costs
- [ ] How to manage accounts
- [ ] How to process refunds
- [ ] How to monitor system health
- [ ] How to handle webhook failures
### Developer Documentation
- [ ] API reference
- [ ] Stripe integration guide
- [ ] Webhook handling
- [ ] Testing procedures
- [ ] Deployment checklist
---
## 🎯 IMMEDIATE NEXT STEPS
### This Week (High Priority)
1. **Create Invoice & Payment Models**
- Write migration
- Create serializers
- Add to admin
2. **Implement Stripe Webhooks**
- Set up endpoint
- Handle subscription events
- Test webhook processing
3. **Create Plans & Billing Page**
- Consolidate existing billing pages
- Add subscription management UI
- Integrate Stripe Elements
### Next Week (High Priority)
4. **Implement Subscription Flow**
- Create subscription API
- Add plan upgrade/downgrade
- Test end-to-end
5. **Implement Credit Purchase**
- Create credit packages
- Add purchase API
- Build purchase UI
6. **Create Account Settings Page**
- Account information
- Billing address
- Team management
---
## 💡 RECOMMENDATIONS
### Must Haves (Critical)
1. ✅ Stripe webhook integration
2. ✅ Invoice & payment tracking
3. ✅ Subscription management
4. ✅ Credit purchase flow
5. ✅ Consolidated billing UI
### Should Haves (Important)
6. ✅ Team management
7. ✅ Usage analytics
8. ✅ PDF invoice generation
9. ✅ Email notifications
10. ✅ Admin dashboard
### Nice to Haves (Enhancement)
11. ✅ Budget alerts
12. ✅ Auto top-up
13. ✅ Multi-currency
14. ✅ Volume discounts
15. ✅ Referral program
---
## 🏁 CONCLUSION
This comprehensive plan addresses all aspects of a standardized SaaS platform:
**✅ Already Working:**
- Multi-tenant architecture
- Credits system
- Basic billing UI
- Admin controls for credit costs
**🚧 Need to Implement:**
- Payment processing (Stripe)
- Invoice & payment tracking
- Subscription management
- Consolidated billing UI
- Team management
- Analytics & reporting
**Priority Order:**
1. Payment integration (CRITICAL)
2. Billing UI consolidation (HIGH)
3. Subscription management (HIGH)
4. Admin dashboard (MEDIUM)
5. Analytics & advanced features (LOW)
**Timeline:** 8-12 weeks for full implementation
**Effort:** 2-3 developers full-time
This plan ensures IGNY8 becomes a professional, scalable SaaS platform with best-practice billing, user management, and admin controls.
---
**Status:** ✅ PLAN COMPLETE - READY FOR REVIEW & IMPLEMENTATION