Files
igny8/docs/working-docs/IMPLEMENTATION-GUIDE-DEC-4-2025.md
2025-12-04 23:56:38 +00:00

753 lines
21 KiB
Markdown

# SaaS Platform Implementation Guide
**Date:** December 4, 2025
**Status:** 🚀 READY TO IMPLEMENT
**Scope:** Complete billing, payment, and account management system
---
## ✅ COMPLETED (Ready for Migration)
### Backend Models Created
1. **Invoice Model** - `backend/igny8_core/business/billing/models.py`
- Tracks billing invoices with line items
- Supports Stripe integration
- Status tracking (draft, pending, paid, void)
2. **Payment Model** - `backend/igny8_core/business/billing/models.py`
- Multi-payment gateway support (Stripe, PayPal, Manual)
- Manual payment approval workflow
- Comprehensive tracking fields
3. **CreditPackage Model** - `backend/igny8_core/business/billing/models.py`
- Defines purchasable credit bundles
- Stripe and PayPal product integration
- Featured packages support
4. **PaymentMethodConfig Model** - `backend/igny8_core/business/billing/models.py`
- Per-country payment method configuration
- Enable/disable manual payments by region
- Bank details and wallet information
5. **Account Model Updates** - `backend/igny8_core/auth/models.py`
- Added billing address fields
- Tax ID support
- Billing email
---
## 🔄 NEXT STEP: Create Migrations
```bash
cd /data/app/igny8/backend
# Create migrations
python manage.py makemigrations billing --name add_invoice_payment_models
python manage.py makemigrations auth --name add_billing_address_fields
# Review migrations
python manage.py sqlmigrate billing <number>
python manage.py sqlmigrate auth <number>
# Apply migrations
python manage.py migrate billing
python manage.py migrate auth
```
---
## 📋 IMPLEMENTATION ROADMAP (32 Tasks)
This is a LARGE implementation. Recommended approach: **Implement in phases over 8-12 weeks**.
### PHASE 1: Backend Foundation (Week 1-2) - CRITICAL
#### Tasks 5-10: Core Services & Webhooks
**Task 5:** Database Migrations ✅ Ready to run (see above)
**Task 6:** SubscriptionService
- File: `backend/igny8_core/business/billing/services/subscription_service.py`
- Methods needed:
```python
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)
```
**Task 7:** InvoiceService
- File: `backend/igny8_core/business/billing/services/invoice_service.py`
- Methods needed:
```python
create_invoice(account, line_items, subscription=None)
generate_invoice_number() # Format: INV-YYYY-MM-XXXXX
mark_paid(invoice, payment)
mark_void(invoice, reason)
generate_pdf(invoice) # Returns PDF bytes
send_invoice_email(invoice)
```
**Task 8:** PaymentService
- File: `backend/igny8_core/business/billing/services/payment_service.py`
- Methods needed:
```python
# Stripe
create_stripe_payment(invoice, payment_method_id)
handle_stripe_success(payment_intent)
handle_stripe_failure(payment_intent)
# PayPal
create_paypal_payment(invoice)
handle_paypal_success(order_id, capture_id)
handle_paypal_failure(order_id)
# Manual
create_manual_payment(invoice, payment_method, reference)
approve_manual_payment(payment, approved_by)
reject_manual_payment(payment, reason)
# Common
process_refund(payment, amount)
get_available_payment_methods(country_code)
```
**Task 9:** Stripe Webhook Handler
- File: `backend/igny8_core/business/billing/webhooks/stripe_webhooks.py`
- Endpoint: `POST /v1/billing/webhooks/stripe/`
- Events to handle:
- `invoice.paid` → Create payment, update invoice
- `invoice.payment_failed` → Mark invoice failed
- `customer.subscription.created` → Create subscription
- `customer.subscription.updated` → Update subscription
- `customer.subscription.deleted` → Cancel subscription
- `payment_intent.succeeded` → Update payment status
- `payment_intent.payment_failed` → Mark payment failed
**Task 10:** PayPal Webhook Handler
- File: `backend/igny8_core/business/billing/webhooks/paypal_webhooks.py`
- Endpoint: `POST /v1/billing/webhooks/paypal/`
- Events to handle:
- `PAYMENT.CAPTURE.COMPLETED` → Create payment
- `PAYMENT.CAPTURE.DENIED` → Mark payment failed
- `PAYMENT.CAPTURE.REFUNDED` → Process refund
---
### PHASE 2: Backend APIs (Week 3-4) - HIGH PRIORITY
#### Tasks 11-13: REST API Endpoints
**Task 11:** Billing API Endpoints
- File: `backend/igny8_core/business/billing/views.py`
- Endpoints needed:
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/v1/billing/invoices/` | GET | List user's invoices |
| `/v1/billing/invoices/:id/` | GET | Get invoice details |
| `/v1/billing/invoices/:id/pdf/` | GET | Download PDF |
| `/v1/billing/subscriptions/` | GET | Get current subscription |
| `/v1/billing/subscriptions/create/` | POST | Create subscription |
| `/v1/billing/subscriptions/cancel/` | POST | Cancel subscription |
| `/v1/billing/subscriptions/upgrade/` | POST | Upgrade plan |
| `/v1/billing/credits/packages/` | GET | List credit packages |
| `/v1/billing/credits/purchase/` | POST | Purchase credits |
| `/v1/billing/payment-methods/` | GET | List payment methods for country |
| `/v1/billing/payment-methods/add/` | POST | Add payment method |
**Task 12:** Account Management API
- File: `backend/igny8_core/api/account_views.py` (new file)
- Endpoints needed:
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/v1/account/settings/` | GET | Get account info |
| `/v1/account/settings/` | PATCH | Update account |
| `/v1/account/limits/` | GET | Get account limits |
| `/v1/account/team/` | GET | List team members |
| `/v1/account/team/invite/` | POST | Invite user |
| `/v1/account/team/:id/` | DELETE | Remove user |
| `/v1/account/team/:id/role/` | PATCH | Update user role |
| `/v1/account/usage/analytics/` | GET | Usage analytics |
**Task 13:** Admin Billing API
- File: `backend/igny8_core/admin/billing_admin_views.py` (new file)
- Endpoints needed:
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/v1/admin/accounts/` | GET | List all accounts |
| `/v1/admin/accounts/:id/suspend/` | POST | Suspend account |
| `/v1/admin/accounts/:id/activate/` | POST | Activate account |
| `/v1/admin/invoices/` | GET | All invoices |
| `/v1/admin/invoices/create/` | POST | Manual invoice |
| `/v1/admin/payments/` | GET | All payments |
| `/v1/admin/payments/:id/approve/` | POST | Approve manual payment |
| `/v1/admin/payment-methods/` | GET | Payment method configs |
| `/v1/admin/payment-methods/` | POST | Create payment config |
| `/v1/admin/dashboard/stats/` | GET | System statistics |
---
### PHASE 3: Frontend Pages (Week 5-8) - HIGH PRIORITY
#### Tasks 14-19: User-Facing Pages
**Task 14:** Account Settings Page
- Path: `/account/settings`
- File: `frontend/src/pages/Account/AccountSettings.tsx`
- Components needed:
- **Account Information Tab**
- Account name (editable)
- Account slug (read-only)
- Status badge
- Owner info
- **Billing Address Tab**
- Address form (line1, line2, city, state, postal, country)
- Tax ID field
- Save button
- **Account Limits Tab**
- Sites (current/max)
- Users (current/max)
- Credits (current balance + monthly included)
- Progress bars
- **Danger Zone Tab**
- Delete account (confirmation modal)
- Transfer ownership
**Task 15:** Consolidated Plans & Billing Page
- Path: `/account/billing`
- File: `frontend/src/pages/Account/PlansAndBilling.tsx`
- Tabs needed:
1. **Current Plan Tab**
- Plan name, price, billing cycle
- Included credits display
- Upgrade/Downgrade buttons
- Subscription status badge
- Next billing date
2. **Credits Tab**
- Current balance (large number)
- Monthly included
- Bonus credits
- Usage this month (progress bar)
- "Purchase Credits" button
3. **Billing History Tab**
- Invoices table (number, date, amount, status, actions)
- Filter by status
- Download PDF button per invoice
4. **Payment Methods Tab**
- Saved cards list (Stripe)
- PayPal account (if linked)
- Add payment method button
- Set default option
**Task 16:** Team Management Page
- Path: `/account/team`
- File: `frontend/src/pages/Account/TeamManagement.tsx`
- Features:
- **Team Members Table**
- Name, Email, Role, Status columns
- Actions: Edit role, Remove
- **Invite User Section**
- Email input
- Role selector
- Site access selector (multi-site accounts)
- Send invitation button
- **Pending Invitations**
- List of pending invites
- Resend/Cancel options
**Task 17:** Usage & Analytics Page
- Path: `/account/usage`
- File: `frontend/src/pages/Account/UsageAnalytics.tsx`
- Charts needed:
- **Credit Usage Over Time** (Line chart)
- Last 30 days
- Daily breakdown
- **Cost Breakdown** (Pie chart)
- By operation type
- Show percentages
- **Top Operations** (Bar chart)
- Most expensive operations
- Credits consumed
- **Stats Cards**
- Total credits used this month
- Average daily usage
- Most used operation
- Projected monthly cost
**Task 18:** Purchase Credits Page
- Path: `/account/credits/purchase`
- File: `frontend/src/pages/Account/PurchaseCredits.tsx`
- Layout:
- **Package Selection Grid**
- 4 packages (Starter, Pro, Business, Enterprise)
- Show credits, price, discount
- Featured badge
- "Select" button
- **Payment Method Selection**
- Stripe (card)
- PayPal
- Bank Transfer (if enabled for country)
- Local Wallet (if enabled for country)
- **Payment Forms**
- Stripe Elements integration
- PayPal Smart Buttons
- Manual payment instructions
- **Confirmation**
- Success modal
- Credits added notification
- Invoice link
**Task 19:** Invoices Page
- Path: `/account/invoices`
- File: `frontend/src/pages/Account/Invoices.tsx`
- Features:
- **Invoices Table**
- Columns: Number, Date, Amount, Status, Actions
- Sort by date
- Filter by status
- **Invoice Details Modal**
- Line items
- Subtotal, tax, total
- Payment status
- Download PDF button
- **Search & Filters**
- Search by invoice number
- Date range picker
- Status filter
---
#### Tasks 20-23: Admin Pages
**Task 20:** Admin System Dashboard
- Path: `/admin/dashboard`
- File: `frontend/src/pages/Admin/SystemDashboard.tsx`
- Metrics:
- **Overview Cards**
- Total accounts
- Active subscriptions
- Revenue this month
- Credits issued/used
- **Charts**
- Revenue trend (line)
- New accounts (bar)
- Subscription distribution (pie)
- **Recent Activity**
- Latest transactions
- New accounts
- Failed payments
**Task 21:** Admin Accounts Management
- Path: `/admin/accounts`
- File: `frontend/src/pages/Admin/AccountsManagement.tsx`
- Features:
- **Accounts Table**
- Search by name/email
- Filter by status, plan
- Columns: Name, Plan, Credits, Status, Created
- Actions: View, Adjust Credits, Suspend
- **Account Details Modal**
- Full account info
- Credit adjustment form
- Suspend/Activate buttons
- Activity log
**Task 22:** Admin Invoices Management
- Path: `/admin/invoices`
- File: `frontend/src/pages/Admin/InvoicesManagement.tsx`
- Features:
- **All Invoices Table**
- Search, filter
- Account name column
- Bulk actions
- **Create Manual Invoice**
- Account selector
- Line items builder
- Send invoice option
**Task 23:** Payment Method Config Admin
- Path: `/admin/payment-methods`
- File: `frontend/src/pages/Admin/PaymentMethodConfig.tsx`
- Features:
- **Country Configurations Table**
- Group by country
- Enable/disable toggles per method
- **Add Configuration Form**
- Country selector
- Payment method selector
- Instructions editor
- Bank details (for manual methods)
---
### PHASE 4: Navigation & UI Updates (Week 9)
#### Task 24: Update Navigation Menu
**File:** `frontend/src/layout/AppSidebar.tsx`
**Changes Needed:**
1. Add new "ACCOUNT" section between "WORKFLOW" and "SETTINGS":
```tsx
{
label: "ACCOUNT",
items: [
{
icon: <SettingsIcon />,
name: "Account Settings",
path: "/account/settings",
},
{
icon: <DollarLineIcon />,
name: "Plans & Billing",
path: "/account/billing",
},
{
icon: <UserIcon />,
name: "Team",
path: "/account/team",
},
{
icon: <PieChartIcon />,
name: "Usage & Analytics",
path: "/account/usage",
},
],
}
```
2. Update SETTINGS section (remove Plans, consolidate Billing):
```tsx
{
label: "SETTINGS",
items: [
{
icon: <PlugInIcon />,
name: "Integration",
path: "/settings/integration",
},
{
icon: <FileIcon />,
name: "Publishing",
path: "/settings/publishing",
},
// ... rest
],
}
```
3. Update ADMIN section:
```tsx
{
label: "ADMIN",
items: [
{
icon: <GridIcon />,
name: "System Dashboard",
path: "/admin/dashboard",
},
{
icon: <UserIcon />,
name: "Accounts",
path: "/admin/accounts",
},
{
icon: <DollarLineIcon />,
name: "Billing",
subItems: [
{ name: "Invoices", path: "/admin/invoices" },
{ name: "Payments", path: "/admin/payments" },
{ name: "Credit Costs", path: "/admin/credit-costs" },
{ name: "Payment Methods", path: "/admin/payment-methods" },
],
},
// ... rest
],
}
```
---
### PHASE 5: Supporting Features (Week 10-12)
#### Tasks 25-26: Email & PDF
**Task 25:** Email Templates
- File: `backend/igny8_core/business/billing/templates/emails/`
- Templates needed:
- `invoice_created.html` - New invoice notification
- `payment_success.html` - Payment confirmation
- `payment_failed.html` - Payment failure alert
- `subscription_created.html` - Welcome email
- `subscription_cancelled.html` - Cancellation confirmation
- `manual_payment_instructions.html` - Bank transfer details
- `manual_payment_approved.html` - Payment approved notification
**Task 26:** PDF Invoice Generation
- Library: `reportlab` or `weasyprint`
- File: `backend/igny8_core/business/billing/services/pdf_service.py`
- Template: `backend/igny8_core/business/billing/templates/pdf/invoice.html`
- Features:
- Company logo
- Invoice number, date
- Bill to address
- Line items table
- Subtotal, tax, total
- Payment instructions
- Footer with terms
---
### PHASE 6: Testing & Documentation (Week 13-14)
#### Tasks 27-32: Quality Assurance
**Task 27-28:** Unit & Integration Tests
- Test files to create:
- `backend/igny8_core/business/billing/tests/test_subscription_service.py`
- `backend/igny8_core/business/billing/tests/test_invoice_service.py`
- `backend/igny8_core/business/billing/tests/test_payment_service.py`
- `backend/igny8_core/business/billing/tests/test_webhooks.py`
- `backend/igny8_core/business/billing/tests/test_billing_api.py`
**Task 29-31:** Payment Gateway Testing
- Stripe test mode
- PayPal sandbox
- Manual payment workflow
**Task 32:** Documentation
- User guide: Billing features
- Admin guide: Payment configuration
- Developer guide: API reference
- Webhook setup guide
---
## 🎯 QUICK START GUIDE
### Step 1: Run Migrations (Today)
```bash
cd /data/app/igny8/backend
python manage.py makemigrations billing --name add_invoice_payment_models
python manage.py makemigrations auth --name add_billing_address_fields
python manage.py migrate
```
### Step 2: Create Sample Data (Testing)
```bash
python manage.py shell
```
```python
from igny8_core.business.billing.models import CreditPackage, PaymentMethodConfig
# Create credit packages
CreditPackage.objects.create(
name="Starter Pack",
slug="starter",
credits=500,
price=9.00,
sort_order=1,
is_active=True
)
CreditPackage.objects.create(
name="Pro Pack",
slug="pro",
credits=2000,
price=29.00,
discount_percentage=10,
sort_order=2,
is_active=True,
is_featured=True
)
# Enable payment methods for US
PaymentMethodConfig.objects.create(
country_code="US",
payment_method="stripe",
is_enabled=True,
display_name="Credit/Debit Card",
sort_order=1
)
PaymentMethodConfig.objects.create(
country_code="US",
payment_method="paypal",
is_enabled=True,
display_name="PayPal",
sort_order=2
)
```
### Step 3: Start with One Service
Pick ONE service to implement first (recommended: InvoiceService - simplest):
```python
# backend/igny8_core/business/billing/services/invoice_service.py
from django.db import transaction
from django.utils import timezone
from datetime import timedelta
from igny8_core.business.billing.models import Invoice
class InvoiceService:
@staticmethod
def generate_invoice_number():
"""Generate unique invoice number: INV-YYYY-MM-XXXXX"""
from datetime import datetime
today = datetime.now()
prefix = f"INV-{today.year}-{today.month:02d}"
# Get last invoice of the month
last_invoice = Invoice.objects.filter(
invoice_number__startswith=prefix
).order_by('-invoice_number').first()
if last_invoice:
last_num = int(last_invoice.invoice_number.split('-')[-1])
next_num = last_num + 1
else:
next_num = 1
return f"{prefix}-{next_num:05d}"
@staticmethod
@transaction.atomic
def create_invoice(account, line_items, subscription=None):
"""Create invoice for account"""
# Calculate totals
subtotal = sum(item['amount'] * item['quantity'] for item in line_items)
tax = subtotal * 0.0 # TODO: Implement tax calculation
total = subtotal + tax
# Create invoice
invoice = Invoice.objects.create(
account=account,
subscription=subscription,
invoice_number=InvoiceService.generate_invoice_number(),
subtotal=subtotal,
tax=tax,
total=total,
invoice_date=timezone.now().date(),
due_date=timezone.now().date() + timedelta(days=7),
line_items=line_items,
status='pending'
)
return invoice
```
### Step 4: Test the Service
```python
from igny8_core.business.billing.services.invoice_service import InvoiceService
from igny8_core.auth.models import Account
account = Account.objects.first()
line_items = [
{
'description': 'Professional Plan - Monthly',
'amount': 99.00,
'quantity': 1
},
{
'description': 'Additional 1000 credits',
'amount': 19.00,
'quantity': 1
}
]
invoice = InvoiceService.create_invoice(account, line_items)
print(f"Created invoice: {invoice.invoice_number}")
```
---
## 📝 RECOMMENDED IMPLEMENTATION ORDER
1. **Week 1:** Migrations + InvoiceService + Basic Invoice API
2. **Week 2:** PaymentService (manual only) + Manual payment flow
3. **Week 3:** Stripe integration (subscription + one-time)
4. **Week 4:** Account Settings page + Plans & Billing page
5. **Week 5:** Stripe webhooks + Payment confirmation
6. **Week 6:** PayPal integration + PayPal webhooks
7. **Week 7:** Team Management + Usage Analytics pages
8. **Week 8:** Purchase Credits page + Payment method selection
9. **Week 9:** Admin Dashboard + Accounts Management
10. **Week 10:** Admin Invoices + Payment Method Config
11. **Week 11:** Email templates + PDF generation
12. **Week 12:** Testing + Bug fixes + Documentation
---
## ⚠️ IMPORTANT NOTES
1. **Stripe Setup Required:**
```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. **PayPal Setup Required:**
```python
# settings.py
PAYPAL_CLIENT_ID = env('PAYPAL_CLIENT_ID')
PAYPAL_CLIENT_SECRET = env('PAYPAL_CLIENT_SECRET')
PAYPAL_MODE = env('PAYPAL_MODE', default='sandbox') # or 'live'
```
3. **Frontend Dependencies:**
```bash
cd frontend
npm install @stripe/stripe-js @stripe/react-stripe-js
npm install @paypal/react-paypal-js
npm install recharts # For charts in analytics
```
4. **Backend Dependencies:**
```bash
cd backend
pip install stripe
pip install paypalrestsdk
pip install reportlab # For PDF generation
```
---
## 🎉 SUCCESS CRITERIA
- [ ] Users can view and update account settings
- [ ] Users can purchase credit packages with Stripe
- [ ] Users can purchase credit packages with PayPal
- [ ] Users can request manual payments (bank transfer)
- [ ] Admins can approve/reject manual payments
- [ ] Invoices are generated automatically
- [ ] Invoices can be downloaded as PDF
- [ ] Subscription creation works end-to-end
- [ ] Webhooks process correctly
- [ ] Payment methods can be configured per country
- [ ] Team management is functional
- [ ] Usage analytics display correctly
- [ ] All tests pass
- [ ] Documentation is complete
---
**Status:** ✅ MODELS CREATED - READY FOR IMPLEMENTATION
**Next Step:** Run migrations, then implement services one by one following the recommended order above.