# 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