The Algo Cloud IDE monetization system provides comprehensive billing, subscriptions, usage tracking, and payment processing capabilities. This document covers the complete implementation including database schema, backend services, API endpoints, and frontend components.
- Pricing Tiers
- Usage-Based Billing
- Database Schema
- Backend Services
- API Endpoints
- Frontend Components
- Payment Gateway Integration
- Setup and Configuration
- Testing
- Price: $0/month
- Storage: 500 MB
- Compute Hours: 500 hours/month
- Bandwidth: 10 GB/month
- Concurrent Deployments: 1
- Support: Community forum only
- AI Features: Bring-your-own API keys (unlimited usage)
- Price: $15/month or $150/year (save 17%)
- Storage: 5 GB
- Compute Hours: 2,000 hours/month
- Bandwidth: 50 GB/month
- Concurrent Deployments: 3
- Support: Priority support
- Features: Advanced analytics
- AI Features: Platform-managed keys available with cost + 20% markup
- Price: $49/month or $490/year (save 17%)
- Storage: 20 GB
- Compute Hours: 5,000 hours/month
- Bandwidth: 200 GB/month
- Concurrent Deployments: 10
- Support: Priority support
- Features: Advanced analytics, SSO, Team management
- AI Features: Platform-managed keys available with cost + 20% markup
- Price: Custom pricing
- Storage: Unlimited
- Compute Hours: Unlimited
- Bandwidth: Unlimited
- Concurrent Deployments: Unlimited
- Support: Dedicated support
- Features: All features + Custom resources, 99.9% SLA
- AI Features: Custom AI solutions available
Beyond the plan limits, users are charged for additional usage:
- Deployment Hours: $0.01/hour for active deployments
- Database Storage: $0.10/GB/month
- Bandwidth: $0.05/GB beyond quota
- AI API Usage: Cost + 20% markup (for platform-managed keys)
- Build Minutes: $0.005/minute
Defines available subscription tiers and their features.
CREATE TABLE subscription_plans (
id SERIAL PRIMARY KEY,
name VARCHAR(50) UNIQUE NOT NULL,
display_name VARCHAR(100) NOT NULL,
price_monthly NUMERIC(10, 2) NOT NULL,
price_yearly NUMERIC(10, 2),
storage_mb INTEGER NOT NULL,
compute_hours_monthly INTEGER NOT NULL,
bandwidth_gb_monthly INTEGER NOT NULL,
concurrent_deployments INTEGER DEFAULT 1,
features JSONB,
has_priority_support BOOLEAN DEFAULT false,
has_advanced_analytics BOOLEAN DEFAULT false,
has_sso BOOLEAN DEFAULT false,
has_team_management BOOLEAN DEFAULT false,
bring_own_api_keys BOOLEAN DEFAULT true,
platform_managed_ai BOOLEAN DEFAULT false
);Tracks all resource usage for billing purposes.
CREATE TABLE usage_metrics (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
project_id INTEGER REFERENCES projects(id),
metric_type VARCHAR(50) NOT NULL,
value NUMERIC(12, 4) NOT NULL,
unit VARCHAR(20) NOT NULL,
cost NUMERIC(10, 4) DEFAULT 0,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
billing_period_start DATE,
billing_period_end DATE
);Records all billing transactions.
CREATE TABLE billing_history (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
invoice_id INTEGER REFERENCES invoices(id),
transaction_type VARCHAR(50) NOT NULL,
amount NUMERIC(10, 2) NOT NULL,
status VARCHAR(20) DEFAULT 'pending',
provider VARCHAR(50),
provider_transaction_id VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);Manages prepaid credit balances.
CREATE TABLE prepaid_credits (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL UNIQUE REFERENCES users(id),
balance NUMERIC(10, 2) DEFAULT 0,
auto_reload_enabled BOOLEAN DEFAULT false,
auto_reload_threshold NUMERIC(10, 2),
auto_reload_amount NUMERIC(10, 2)
);Configuration for usage monitoring alerts.
CREATE TABLE usage_alerts (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
metric_type VARCHAR(50) NOT NULL,
threshold_percentage INTEGER NOT NULL,
notification_channels JSONB DEFAULT '["email"]',
is_active BOOLEAN DEFAULT true
);See backend/database/monetization-schema.sql for complete schema.
Handles subscription lifecycle management.
Key Methods:
getPlans()- Retrieve all available plansgetUserSubscription(userId)- Get user's current subscriptioncreateSubscription(userId, planName, billingCycle)- Create new subscriptionupgradeSubscription(userId, newPlanName)- Upgrade to higher tierdowngradeSubscription(userId, newPlanName)- Downgrade to lower tiercancelSubscription(userId, reason)- Cancel subscriptioncheckResourceLimits(userId)- Verify usage within limits
Location: backend/src/services/subscription-service.ts
Tracks and calculates resource usage.
Key Methods:
recordUsage(userId, metricType, value, unit)- Record usage eventgetCurrentUsage(userId)- Get current billing period usagegetUsageHistory(userId, startDate, endDate)- Historical usage datatrackDeploymentHours(userId, projectId, hours)- Track deployment timetrackStorageUsage(userId, projectId, megabytes)- Track storagetrackBandwidthUsage(userId, projectId, gigabytes)- Track bandwidthtrackAIUsage(userId, projectId, provider, model, tokens, cost)- Track AI API usage
Location: backend/src/services/usage-tracking-service.ts
Manages invoicing and payment processing.
Key Methods:
generateSubscriptionInvoice(userId, subscriptionId, amount, periodStart, periodEnd)- Create subscription invoicegenerateUsageInvoice(userId, periodStart, periodEnd)- Create usage-based invoiceprocessPayment(invoiceId, paymentMethodId, provider)- Process paymentgetUserInvoices(userId)- Get user's invoice historyaddPaymentMethod(userId, type, provider, providerPaymentMethodId, details)- Add payment methodhandleWebhook(provider, eventType, eventId, payload, signature)- Process payment gateway webhooks
Location: backend/src/services/billing-service.ts
Manages prepaid credit system.
Key Methods:
getBalance(userId)- Get credit balancepurchaseCredits(userId, amount)- Purchase creditsdeductCredits(userId, amount, description)- Deduct credits for usageconfigureAutoReload(userId, enabled, threshold, amount)- Configure auto-reloadgrantBonusCredits(userId, amount, reason)- Award promotional creditsrefundCredits(userId, amount, reason)- Refund credits
Location: backend/src/services/credits-service.ts
Get all available subscription plans.
Response:
{
"plans": [
{
"id": 1,
"name": "free",
"displayName": "Free Tier",
"priceMonthly": 0,
"storageMb": 500,
"computeHoursMonthly": 500,
...
}
]
}Get user's current subscription.
Response:
{
"subscription": {
"tier": "pro",
"status": "active",
"billingCycle": "monthly",
"amount": 15,
"currentPeriodStart": "2024-01-01T00:00:00Z",
"currentPeriodEnd": "2024-02-01T00:00:00Z"
}
}Subscribe to a plan.
Request:
{
"planName": "pro",
"billingCycle": "monthly",
"trialDays": 14
}Upgrade subscription.
Request:
{
"planName": "team",
"billingCycle": "yearly"
}Cancel subscription.
Request:
{
"reason": "No longer needed"
}Get current billing period usage.
Response:
{
"usage": {
"period": {
"start": "2024-01-01",
"end": "2024-02-01"
},
"metrics": {
"deployment_hours": {
"value": 120.5,
"cost": 1.21,
"unit": "hours"
},
"storage": {
"value": 1024,
"cost": 0.1,
"unit": "MB"
}
},
"totalCost": 1.31
}
}Get usage history.
Query Parameters:
startDate(required)endDate(required)metricType(optional)
Get user's invoices.
Response:
{
"invoices": [
{
"id": 1,
"invoiceNumber": "INV-2024-000001",
"amount": 15.0,
"currency": "USD",
"status": "paid",
"issuedAt": "2024-01-01T00:00:00Z",
"paidAt": "2024-01-02T00:00:00Z"
}
]
}Get invoice details with line items.
Process payment for invoice.
Request:
{
"paymentMethodId": 1,
"provider": "stripe"
}Get user's payment methods.
Add new payment method.
Request:
{
"type": "card",
"provider": "stripe",
"providerPaymentMethodId": "pm_1234567890",
"details": {
"lastFour": "4242",
"brand": "visa",
"isDefault": true
}
}Get credit balance.
Response:
{
"balance": {
"userId": 1,
"balance": 50.0,
"currency": "USD",
"autoReloadEnabled": true,
"autoReloadThreshold": 10.0,
"autoReloadAmount": 25.0
}
}Purchase credits.
Request:
{
"amount": 50.0,
"paymentMethodId": 1
}Configure auto-reload.
Request:
{
"enabled": true,
"threshold": 10.0,
"amount": 25.0
}Get configured alerts.
Configure usage alert.
Request:
{
"metricType": "storage",
"thresholdPercentage": 75,
"notificationChannels": ["email", "dashboard"],
"isActive": true
}Delete alert.
Get alert trigger history.
Component: src/components/Pricing.tsx
Displays all subscription tiers with:
- Monthly/yearly billing toggle
- Feature comparison
- Usage-based pricing details
- Subscribe buttons
Component: src/components/BillingDashboard.tsx
Shows:
- Current subscription details
- Real-time usage metrics
- Invoice history
- Payment methods management
Component: src/components/CreditsManagement.tsx
Provides:
- Current credit balance display
- Credit purchase interface
- Auto-reload configuration
- Transaction history
Component: src/components/UsageAlerts.tsx
Allows users to:
- Configure usage alerts
- Set notification thresholds
- View alert history
- Manage alert settings
The system is designed to integrate with Stripe for card payments.
Setup:
-
Install Stripe SDK:
npm install stripe -
Configure environment variables:
STRIPE_SECRET_KEY=sk_test_... STRIPE_PUBLISHABLE_KEY=pk_test_... STRIPE_WEBHOOK_SECRET=whsec_... -
Initialize Stripe in billing service:
import Stripe from 'stripe'; const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
Configure PayPal credentials:
PAYPAL_CLIENT_ID=your_client_id
PAYPAL_SECRET=your_secret
PAYPAL_MODE=sandbox
Configure Coinbase Commerce:
COINBASE_COMMERCE_API_KEY=your_api_key
COINBASE_COMMERCE_WEBHOOK_SECRET=your_webhook_secret
Add to .env:
# Payment Gateways
STRIPE_SECRET_KEY=sk_test_your_key
STRIPE_PUBLISHABLE_KEY=pk_test_your_key
STRIPE_WEBHOOK_SECRET=whsec_your_secret
PAYPAL_CLIENT_ID=your_client_id
PAYPAL_SECRET=your_secret
PAYPAL_MODE=sandbox
COINBASE_COMMERCE_API_KEY=your_api_key
# Billing Configuration
BILLING_EMAIL_FROM=billing@algo-ide.com
INVOICE_GENERATION_ENABLED=true
USAGE_TRACKING_ENABLED=true
USAGE_BILLING_DAY=1-
Run the monetization schema:
psql -U algo_user -d algo_ide -f backend/database/monetization-schema.sql
-
Verify tables are created:
\dt subscription_plans \dt usage_metrics \dt billing_history
-
Default plans are automatically inserted.
The monetization routes are automatically loaded in backend/src/index.ts:
app.use('/api/subscriptions', createSubscriptionRoutes(dashboardPool));
app.use('/api/usage', createUsageRoutes(dashboardPool));
app.use('/api/billing', createBillingRoutes(dashboardPool));
app.use('/api/credits', createCreditsRoutes(dashboardPool));
app.use('/api/alerts', createAlertsRoutes(dashboardPool));Test billing calculations:
describe('BillingService', () => {
test('calculates usage cost correctly', () => {
const cost = calculateUsageCost('deployment_hours', 100);
expect(cost).toBe(1.0);
});
});Test subscription lifecycle:
describe('Subscription Flow', () => {
test('user can subscribe to pro plan', async () => {
const subscription = await subscriptionService.createSubscription(
userId,
'pro',
'monthly'
);
expect(subscription.tier).toBe('pro');
});
});-
Start the backend server:
cd backend npm run dev -
Test API endpoints using cURL or Postman:
curl http://localhost:4000/api/subscriptions/plans
-
Test frontend components:
npm run dev # Navigate to /pricing, /billing, etc.
- Payment Data: Never store raw card numbers. Use tokenization via payment gateways.
- Webhook Verification: Always verify webhook signatures.
- Rate Limiting: Apply rate limits to payment endpoints.
- Audit Logging: Log all billing operations.
- PCI Compliance: Follow PCI DSS guidelines for payment processing.
Issue: Plans not loading
- Check database connection
- Verify schema is initialized
- Check API endpoint logs
Issue: Usage not tracked
- Verify usage tracking is enabled in environment
- Check that metrics are being recorded in the database
Issue: Payment failures
- Verify payment gateway credentials
- Check webhook configuration
- Review error logs for specific error codes
- Multi-currency support
- Tax calculation integration
- Advanced analytics dashboard
- Automated invoice PDF generation
- SMS notifications for alerts
- Referral program integration
- Volume discounts
- Custom contract management for Enterprise
For questions or issues:
- Email: support@algo-ide.com
- Documentation: https://docs.algo-ide.com
- GitHub Issues: https://github.com/Algodons/algo/issues