Files
computer/supabase/schema_analytics.sql
zeekay d2d5607201 feat: Production-ready platform with Stripe, Email, Analytics, Rate Limiting
Complete Production Features (1-7):
====================================

1. STRIPE PAYMENT INTEGRATION ✅
   - Full checkout flow with Stripe Elements
   - Payment intent creation for one-time purchases
   - Subscription creation for monthly GPU leasing
   - Success page with order confirmation
   - Serverless functions: create-payment-intent, create-subscription
   - PCI-compliant card input with glass-morphism styling
   - Error handling and loading states
   - Test mode ready with Stripe test keys

2. EMAIL NOTIFICATION SYSTEM ✅
   - SendGrid integration with professional templates
   - Quote emails with validity period
   - Order confirmations with invoice details
   - Subscription activation emails
   - RFQ confirmations (customer + admin)
   - Cluster request notifications
   - HTML + plain text versions
   - Responsive email design with Hanzo branding
   - API endpoints: send-quote, send-order, send-subscription, send-rfq

3. PDF INVOICE GENERATION ✅
   - @react-pdf/renderer integration
   - Professional invoice templates with Hanzo branding
   - Automatic generation on order payment
   - Download from customer dashboard
   - Supabase storage integration
   - Admin invoice management
   - Regenerate capability
   - Email invoice attachments ready

4. USAGE ANALYTICS DASHBOARD ✅
   - Comprehensive customer analytics at /analytics
   - Interactive charts: Line, Bar, Pie, Area charts
   - Metrics: compute hours, costs, GPU utilization
   - Date range selector (7/30/90 days, all time)
   - CSV export functionality
   - Usage tracking with Recharts
   - Real-time data from Supabase
   - Sample data generator for demo

5. API RATE LIMITING ✅
   - Upstash Redis-based rate limiting
   - Role-based limits: anonymous (10/min), auth (100/min), admin (1000/min)
   - Endpoint-specific limits for sensitive operations
   - 429 Too Many Requests responses
   - Rate limit headers (X-RateLimit-*)
   - Frontend retry with exponential backoff
   - Admin dashboard for monitoring
   - Clear rate limits endpoint for admins
   - Database logging and violation tracking

6. STRIPE WEBHOOK HANDLERS ✅
   - Webhook endpoint: /api/webhooks/stripe
   - Event handlers: payment success/failure, subscriptions, invoices, refunds
   - Signature verification for security
   - Idempotency handling (prevent duplicates)
   - Automatic order creation on payment
   - Subscription lifecycle management
   - Email triggers on events
   - Admin retry capability
   - Comprehensive event logging
   - Database schema for webhook tracking

7. ADMIN ANALYTICS & CHARTS ✅
   - Enhanced Admin Dashboard with Analytics tab
   - Revenue charts: time series, by GPU type, cumulative
   - Conversion funnel: RFQ → Quote → Order
   - Customer growth metrics
   - Operational metrics: response times, quote performance
   - Top customers table
   - Interactive Recharts visualizations
   - Date range filtering
   - Auto-refresh every 5 minutes
   - CSV export for reports
   - Key metrics cards with % change indicators

Technical Implementation:
========================

New Dependencies:
- @stripe/stripe-js, @stripe/react-stripe-js, stripe
- @sendgrid/mail
- @react-pdf/renderer
- recharts, date-fns
- @upstash/ratelimit, @upstash/redis
- micro (webhook body parsing)

New Files Created (50+):
- API routes: /api/webhooks/, /api/admin/, /api/create-*, /api/send-*
- Libraries: stripe.ts, email.ts, invoices.ts, analytics.ts, rateLimit.ts
- Components: Invoice, WebhookEventLog, RateLimitDashboard, DashboardInvoices
- Pages: Analytics, CheckoutSuccess, admin/RateLimitDashboard
- Documentation: EMAIL_NOTIFICATIONS.md, STRIPE_WEBHOOKS.md, RATE_LIMITING.md
- Database: Supabase migrations for webhooks, analytics, rate limiting

Environment Variables Required:
- STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET
- VITE_STRIPE_PUBLISHABLE_KEY
- SENDGRID_API_KEY, EMAIL_FROM, ADMIN_EMAIL
- UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN
- ADMIN_API_KEY

Build Status:
=============
✓ Production build: 807KB gzipped
✓ 3480 modules transformed
✓ Build time: 5.20s
✓ All TypeScript validated
✓ Zero compilation errors

Ready for Launch:
=================
✅ Complete payment processing
✅ Professional email communications
✅ Automated invoicing
✅ Customer analytics
✅ API protection
✅ Webhook automation
✅ Business intelligence dashboard

The platform is now enterprise-ready for production deployment!
2025-10-31 13:55:31 -07:00

115 lines
3.5 KiB
PL/PgSQL

-- Usage Records Table for Analytics
CREATE TABLE IF NOT EXISTS usage_records (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
reservation_id UUID,
gpu_type VARCHAR(100) NOT NULL,
hours_used DECIMAL(10, 2) NOT NULL,
compute_units DECIMAL(10, 2) NOT NULL,
cost_usd DECIMAL(10, 2) NOT NULL,
timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
metadata JSONB,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_usage_records_user_id ON usage_records(user_id);
CREATE INDEX IF NOT EXISTS idx_usage_records_timestamp ON usage_records(timestamp);
CREATE INDEX IF NOT EXISTS idx_usage_records_user_timestamp ON usage_records(user_id, timestamp DESC);
CREATE INDEX IF NOT EXISTS idx_usage_records_gpu_type ON usage_records(gpu_type);
-- Enable Row Level Security
ALTER TABLE usage_records ENABLE ROW LEVEL SECURITY;
-- Policies for usage_records
CREATE POLICY "Users can view their own usage records" ON usage_records
FOR SELECT
USING (auth.uid() = user_id);
CREATE POLICY "Service role can insert usage records" ON usage_records
FOR INSERT
WITH CHECK (true);
CREATE POLICY "Service role can update usage records" ON usage_records
FOR UPDATE
USING (true);
-- Function to get usage summary for a user
CREATE OR REPLACE FUNCTION get_user_usage_summary(p_user_id UUID)
RETURNS TABLE (
total_hours DECIMAL,
total_cost DECIMAL,
total_compute_units DECIMAL,
gpu_type VARCHAR,
gpu_hours DECIMAL,
gpu_cost DECIMAL
) AS $$
BEGIN
RETURN QUERY
WITH summary AS (
SELECT
SUM(hours_used) as total_hours,
SUM(cost_usd) as total_cost,
SUM(compute_units) as total_compute_units
FROM usage_records
WHERE user_id = p_user_id
),
by_gpu AS (
SELECT
gpu_type,
SUM(hours_used) as gpu_hours,
SUM(cost_usd) as gpu_cost
FROM usage_records
WHERE user_id = p_user_id
GROUP BY gpu_type
)
SELECT
s.total_hours,
s.total_cost,
s.total_compute_units,
g.gpu_type,
g.gpu_hours,
g.gpu_cost
FROM summary s
CROSS JOIN by_gpu g;
END;
$$ LANGUAGE plpgsql;
-- Function to get monthly spending
CREATE OR REPLACE FUNCTION get_monthly_spending(p_user_id UUID, p_months INTEGER DEFAULT 6)
RETURNS TABLE (
month TEXT,
cost DECIMAL
) AS $$
BEGIN
RETURN QUERY
SELECT
TO_CHAR(DATE_TRUNC('month', timestamp), 'YYYY-MM') as month,
SUM(cost_usd) as cost
FROM usage_records
WHERE user_id = p_user_id
AND timestamp >= NOW() - INTERVAL '1 month' * p_months
GROUP BY DATE_TRUNC('month', timestamp)
ORDER BY month;
END;
$$ LANGUAGE plpgsql;
-- Sample data insertion (for testing)
-- This can be commented out in production
/*
INSERT INTO usage_records (user_id, gpu_type, hours_used, compute_units, cost_usd, timestamp, metadata)
SELECT
(SELECT id FROM auth.users LIMIT 1),
gpu_types.gpu,
ROUND((RANDOM() * 10 + 1)::numeric, 2),
ROUND((RANDOM() * 100 + 10)::numeric, 2),
ROUND((RANDOM() * 50 + 5)::numeric, 2),
NOW() - INTERVAL '1 day' * FLOOR(RANDOM() * 90),
jsonb_build_object(
'project', 'Project-' || FLOOR(RANDOM() * 5 + 1),
'region', (ARRAY['us-west', 'us-east', 'eu-west'])[FLOOR(RANDOM() * 3 + 1)]
)
FROM
(SELECT unnest(ARRAY['NVIDIA H100', 'NVIDIA A100', 'NVIDIA A6000', 'NVIDIA RTX 4090', 'NVIDIA V100']) as gpu) as gpu_types,
generate_series(1, 50) as n;
*/