diff --git a/POST_DEPLOYMENT_CHECKLIST.md b/POST_DEPLOYMENT_CHECKLIST.md new file mode 100644 index 0000000..57ecf75 --- /dev/null +++ b/POST_DEPLOYMENT_CHECKLIST.md @@ -0,0 +1,281 @@ +# ✅ Post-Deployment Verification Checklist + +## Overview +Use this comprehensive checklist to verify your Quantum Tasks AI application is working correctly after Railway deployment. + +--- + +## 🔍 **PHASE 1: Basic System Health** + +### Application Accessibility +- [ ] **Homepage loads**: Visit `https://your-domain.railway.app/` +- [ ] **Health check responds**: Visit `https://your-domain.railway.app/health/` + ```json + Expected: {"status": "healthy", "checks": {"database": "healthy", "agents": "healthy"}} + ``` +- [ ] **Admin panel accessible**: Visit `https://your-domain.railway.app/admin/` +- [ ] **No 500 errors**: Check Railway logs for any server errors +- [ ] **Static files loading**: CSS, JavaScript, and images display correctly + +### Database Connectivity +- [ ] **Database connection**: Health check shows database as "healthy" +- [ ] **Admin login works**: Test Django admin authentication +- [ ] **User registration**: Create a test user account +- [ ] **Agent data loaded**: Marketplace shows all 7+ AI agents + +--- + +## 🔐 **PHASE 2: Authentication System** + +### User Registration & Login +- [ ] **Registration form**: `/auth/register/` loads and accepts new users +- [ ] **Email verification**: Check if verification emails are sent (if enabled) +- [ ] **Login functionality**: `/auth/login/` authenticates users successfully +- [ ] **Password reset**: Test forgot password flow +- [ ] **Rate limiting**: Verify login attempts are rate-limited (test 6+ failed attempts) +- [ ] **User dashboard**: Authenticated users can access their profile + +### Security Features +- [ ] **HTTPS enforced**: All pages redirect to HTTPS +- [ ] **CSRF protection**: Forms include CSRF tokens +- [ ] **Session management**: Users stay logged in appropriately +- [ ] **Secure headers**: Check response headers include security settings + +--- + +## 💳 **PHASE 3: Payment System** + +### Stripe Integration +- [ ] **Wallet page loads**: `/wallet/` displays user balance +- [ ] **Top-up form**: Payment form loads with Stripe elements +- [ ] **Test payment**: Use Stripe test card `4242 4242 4242 4242` +- [ ] **Webhook processing**: Check Railway logs for Stripe webhook events +- [ ] **Balance updates**: User balance increases after successful payment +- [ ] **Transaction history**: Payment records appear in wallet history + +### Payment Security +- [ ] **Rate limiting**: Payment attempts are rate-limited +- [ ] **Error handling**: Invalid cards show appropriate errors +- [ ] **Webhook validation**: Stripe webhooks are properly verified + +--- + +## 🤖 **PHASE 4: AI Agent System** + +### Marketplace Functionality +- [ ] **Marketplace loads**: `/marketplace/` displays all agents +- [ ] **Category filtering**: Filter agents by category works +- [ ] **Search functionality**: Search for agents by name/description +- [ ] **Agent details**: Click on agents loads detail pages +- [ ] **Rate limiting**: Marketplace requests are rate-limited + +### Individual Agent Testing +Test each AI agent with sample data: + +#### Data Analyzer Agent +- [ ] **Agent loads**: `/agents/data-analyzer/` accessible +- [ ] **File upload**: Can upload CSV/Excel files +- [ ] **Processing**: Agent processes data and returns results +- [ ] **N8N webhook**: Check Railway logs for webhook calls + +#### Weather Reporter Agent +- [ ] **Agent loads**: `/agents/weather-reporter/` accessible +- [ ] **Location search**: Can search for cities +- [ ] **Weather data**: Returns current weather information +- [ ] **API integration**: OpenWeather API calls work + +#### Job Posting Generator +- [ ] **Agent loads**: `/agents/job-posting-generator/` accessible +- [ ] **Form submission**: Can submit job requirements +- [ ] **Content generation**: Generates job posting content +- [ ] **N8N integration**: Webhook processes request + +#### Social Ads Generator +- [ ] **Agent loads**: `/agents/social-ads-generator/` accessible +- [ ] **Ad creation**: Generates social media ad content +- [ ] **Platform options**: Multiple platform options work +- [ ] **Output quality**: Generated content is coherent + +#### Five Whys Analyzer +- [ ] **Agent loads**: `/agents/five-whys-analyzer/` accessible +- [ ] **Problem analysis**: Analyzes root causes effectively +- [ ] **Question generation**: Generates meaningful follow-up questions + +#### Email Writer +- [ ] **Agent loads**: `/agents/email-writer/` accessible +- [ ] **Email composition**: Generates professional emails +- [ ] **Tone options**: Different tone settings work + +--- + +## 📧 **PHASE 5: Communication Systems** + +### Email Functionality +- [ ] **SMTP configuration**: Email backend connects successfully +- [ ] **Contact form**: `/contact/` form submits emails +- [ ] **Password reset emails**: Users receive reset emails +- [ ] **Admin notifications**: Contact form notifications reach admin +- [ ] **Email deliverability**: Test emails not in spam folder + +### Contact System +- [ ] **Contact form loads**: Form displays correctly +- [ ] **Form validation**: Client and server-side validation works +- [ ] **Rate limiting**: Contact submissions are rate-limited +- [ ] **Admin integration**: Submissions appear in Django admin +- [ ] **Spam protection**: Form blocks suspicious submissions + +--- + +## 🚀 **PHASE 6: Performance & Monitoring** + +### Performance Metrics +- [ ] **Page load times**: Pages load within 2-3 seconds +- [ ] **Database queries**: No N+1 query issues (check Django debug toolbar locally) +- [ ] **Static file delivery**: CSS/JS/images load quickly +- [ ] **Memory usage**: Railway metrics show reasonable memory consumption +- [ ] **CPU usage**: Application runs efficiently + +### Caching System +- [ ] **Redis connection**: Health check shows Redis connectivity (if configured) +- [ ] **Session caching**: User sessions stored in cache +- [ ] **Database caching**: Repeated queries use cache +- [ ] **Performance improvement**: Pages load faster on subsequent visits + +### Monitoring Setup +- [ ] **Health endpoint**: Set up external monitoring for `/health/` +- [ ] **Error tracking**: Monitor Railway application logs +- [ ] **Uptime monitoring**: Configure service like UptimeRobot +- [ ] **Alert configuration**: Set up alerts for downtime/errors + +--- + +## 🔧 **PHASE 7: Production Configuration** + +### Environment Verification +- [ ] **DEBUG=False**: Application runs in production mode +- [ ] **Secret key**: Unique 50+ character secret key set +- [ ] **ALLOWED_HOSTS**: Includes your domain and Railway URL +- [ ] **SSL configuration**: HTTPS working with proper certificates +- [ ] **CORS settings**: API endpoints have appropriate CORS headers + +### External Services +- [ ] **N8N webhooks**: All webhook URLs are accessible and active +- [ ] **Stripe webhooks**: Webhook endpoint configured in Stripe dashboard +- [ ] **Email service**: SMTP service quota and limits appropriate +- [ ] **API rate limits**: External APIs (OpenWeather) have sufficient quotas + +--- + +## 🛡️ **PHASE 8: Security Verification** + +### Security Audit +- [ ] **SSL/TLS**: A+ rating on SSL Labs test +- [ ] **Security headers**: Check securityheaders.com score +- [ ] **OWASP compliance**: No obvious security vulnerabilities +- [ ] **Input sanitization**: Forms properly sanitize user input +- [ ] **SQL injection**: Database queries use parameterized statements + +### Access Control +- [ ] **Admin protection**: Admin panel requires authentication +- [ ] **User isolation**: Users can only access their own data +- [ ] **API security**: API endpoints have proper authentication +- [ ] **File upload security**: Uploaded files are validated and secured + +--- + +## 📊 **PHASE 9: Analytics & Logging** + +### Application Logging +- [ ] **Error logging**: Errors properly logged to Railway console +- [ ] **Security logging**: Failed login attempts logged +- [ ] **Access logging**: User activities tracked appropriately +- [ ] **Performance logging**: Slow queries and requests identified + +### Business Metrics +- [ ] **User registrations**: Track new user signups +- [ ] **Agent usage**: Monitor which agents are most popular +- [ ] **Payment conversions**: Track payment success rates +- [ ] **Error rates**: Monitor application error frequency + +--- + +## 🎯 **PHASE 10: User Experience** + +### Frontend Functionality +- [ ] **Responsive design**: Application works on mobile devices +- [ ] **Navigation**: All navigation links work correctly +- [ ] **Forms**: All forms submit and validate properly +- [ ] **Error messages**: User-friendly error messages display +- [ ] **Loading states**: Users see appropriate loading indicators + +### Content Verification +- [ ] **Agent descriptions**: All agent descriptions are accurate +- [ ] **Pricing information**: Payment amounts and descriptions correct +- [ ] **Help documentation**: Links to documentation work +- [ ] **Legal pages**: Privacy policy and terms of service accessible + +--- + +## 🚨 **Common Issues & Solutions** + +### Application Not Loading +1. Check Railway build logs for deployment errors +2. Verify all environment variables are set +3. Check health endpoint for specific error details +4. Review Django application logs in Railway console + +### Database Connection Issues +1. Ensure PostgreSQL service is running in Railway +2. Verify DATABASE_URL is automatically set +3. Check database connection limits and usage +4. Test database connectivity via health endpoint + +### Payment System Issues +1. Verify Stripe webhook endpoint is accessible +2. Check Stripe dashboard for webhook delivery status +3. Ensure webhook secret matches environment variable +4. Test with Stripe test cards first + +### Email Delivery Problems +1. Verify SMTP credentials and settings +2. Check email service quotas and limits +3. Test email deliverability with multiple providers +4. Monitor email service logs for delivery issues + +--- + +## ✅ **Final Deployment Sign-off** + +Once all checklist items are verified: + +- [ ] **All critical functionality working**: Core features operational +- [ ] **Performance acceptable**: Application responds quickly +- [ ] **Security verified**: No obvious vulnerabilities +- [ ] **Monitoring configured**: Health checks and alerts set up +- [ ] **Documentation updated**: Deployment details documented +- [ ] **Team notified**: Stakeholders informed of successful deployment + +**Deployment Status**: ✅ **PRODUCTION READY** + +**Deployed URL**: `https://your-domain.railway.app` +**Admin Panel**: `https://your-domain.railway.app/admin/` +**Health Check**: `https://your-domain.railway.app/health/` + +--- + +## 📞 **Support & Maintenance** + +### Regular Maintenance Tasks +- Monitor Railway application metrics weekly +- Review error logs and address issues promptly +- Update dependencies and security patches monthly +- Backup database and test restore procedures +- Monitor external service quotas and usage + +### Emergency Contacts +- Railway Support: support@railway.app +- Stripe Support: support@stripe.com +- Domain/DNS Provider: [Your DNS provider] +- Email Service Provider: [Your SMTP provider] + +**Congratulations! Your Quantum Tasks AI application is successfully deployed and verified! 🎉** \ No newline at end of file diff --git a/RAILWAY_DEPLOYMENT_GUIDE.md b/RAILWAY_DEPLOYMENT_GUIDE.md new file mode 100644 index 0000000..e5a4238 --- /dev/null +++ b/RAILWAY_DEPLOYMENT_GUIDE.md @@ -0,0 +1,220 @@ +# 🚀 Railway.app Deployment Guide for Quantum Tasks AI + +## Overview +This guide will help you deploy your Quantum Tasks AI Django application to Railway.app. Your application is already optimized for Railway deployment with the existing `railway.json` configuration. + +## 📋 Pre-Deployment Checklist + +### Required Accounts & Services +- [ ] GitHub account with your repository +- [ ] Railway.app account (free signup) +- [ ] Stripe account for payments (test/live keys) +- [ ] Gmail or SMTP service for emails +- [ ] N8N instance for AI agent webhooks + +### Code Verification +- [ ] Latest code pushed to GitHub +- [ ] All migrations created and committed +- [ ] `railway.json` file present in root directory +- [ ] Environment variables documented in `.env.example` + +## 🔧 Step-by-Step Deployment + +### Step 1: Connect to Railway +1. Visit [railway.app](https://railway.app) and sign up/login +2. Click "New Project" → "Deploy from GitHub repo" +3. Select your `quantum_ai` repository +4. Railway will automatically detect Django and start building + +### Step 2: Configure Environment Variables +Navigate to your project settings and add these environment variables: + +#### 🔐 Security Settings +```bash +SECRET_KEY=your-50-character-secret-key-here +DEBUG=False +ALLOWED_HOSTS=your-domain.railway.app,quantumtaskai.com +CSRF_TRUSTED_ORIGINS=https://your-domain.railway.app,https://quantumtaskai.com +``` + +#### 📧 Email Configuration +```bash +EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend +EMAIL_HOST=smtp.gmail.com +EMAIL_PORT=587 +EMAIL_USE_TLS=True +EMAIL_HOST_USER=your-email@gmail.com +EMAIL_HOST_PASSWORD=your-app-password +DEFAULT_FROM_EMAIL=Quantum Tasks AI +``` + +#### 💳 Stripe Configuration +```bash +STRIPE_SECRET_KEY=sk_live_your_stripe_secret_key +STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret +``` + +#### 🤖 N8N Webhook URLs +```bash +N8N_WEBHOOK_DATA_ANALYZER=https://your-n8n.com/webhook/data-analyzer +N8N_WEBHOOK_FIVE_WHYS=https://your-n8n.com/webhook/five-whys +N8N_WEBHOOK_JOB_POSTING=https://your-n8n.com/webhook/job-posting +N8N_WEBHOOK_SOCIAL_ADS=https://your-n8n.com/webhook/social-ads +N8N_WEBHOOK_FAQ_GENERATOR=https://your-n8n.com/webhook/faq-generator +``` + +#### 🗄️ Database Configuration +Railway automatically provides `DATABASE_URL` - no manual configuration needed! + +#### ⚡ Redis Configuration (Optional but Recommended) +```bash +REDIS_URL=redis://your-redis-url:6379 +``` + +### Step 3: Add PostgreSQL Database +1. In your Railway project dashboard +2. Click "New" → "Database" → "Add PostgreSQL" +3. Railway automatically sets the `DATABASE_URL` environment variable + +### Step 4: Add Redis (Recommended) +1. Click "New" → "Database" → "Add Redis" +2. Railway automatically sets the `REDIS_URL` environment variable + +### Step 5: Custom Domain (Optional) +1. Go to project Settings → Domains +2. Add your custom domain (e.g., `quantumtaskai.com`) +3. Update DNS records as instructed by Railway +4. Update `ALLOWED_HOSTS` and `CSRF_TRUSTED_ORIGINS` environment variables + +## 🔍 Post-Deployment Verification + +### Health Check +Visit your deployed application health endpoint: +``` +https://your-domain.railway.app/health/ +``` + +Expected response: +```json +{ + "status": "healthy", + "timestamp": 1234567890, + "version": "1.0", + "checks": { + "database": {"status": "healthy", "response_time_ms": 2.5}, + "agents": {"status": "healthy", "active_count": 7} + }, + "response_time_ms": 5.2 +} +``` + +### Application Testing +- [ ] Homepage loads correctly (`/`) +- [ ] User registration works (`/auth/register/`) +- [ ] Login functionality (`/auth/login/`) +- [ ] Marketplace displays agents (`/marketplace/`) +- [ ] Payment system functional (Stripe webhooks) +- [ ] Contact form submits successfully (`/contact/`) +- [ ] Admin panel accessible (`/admin/`) + +### Monitoring Setup +1. **Application Logs**: Available in Railway dashboard +2. **Health Monitoring**: Set up external monitoring to ping `/health/` +3. **Error Tracking**: Monitor Railway application logs +4. **Database Performance**: Use Railway's built-in database metrics + +## 🚨 Troubleshooting + +### Common Issues & Solutions + +#### Migration Errors +```bash +# If you see migration conflicts, check Railway logs +# Your railway.json already handles complex migrations +``` + +#### Static Files Not Loading +```bash +# Already handled by WhiteNoise configuration +# Verify STATIC_URL and STATIC_ROOT in settings +``` + +#### Environment Variable Issues +```bash +# Check Railway project settings +# Ensure all required variables are set +# Restart deployment after adding variables +``` + +#### Database Connection Issues +```bash +# Verify PostgreSQL service is running in Railway +# Check DATABASE_URL is automatically set +# Review connection logs in Railway dashboard +``` + +## 📊 Cost Estimation + +### Railway.app Pricing (Monthly) +- **Web Service**: $5/month (scales with usage) +- **PostgreSQL**: $5/month (1GB storage, scales up) +- **Redis**: $5/month (256MB, scales up) +- **Bandwidth**: $0.10/GB (generous free tier) + +**Total Estimated Cost**: $15-25/month for production usage + +### Scaling Thresholds +- **Free Tier**: Good for development and testing +- **Scale Up**: When you hit 1000+ daily active users +- **Database**: Scales automatically with your data growth + +## 🔒 Security Best Practices + +### Environment Variables +- Never commit real environment variables to Git +- Use Railway's environment variable encryption +- Rotate API keys regularly (Stripe, email, N8N) + +### Domain Security +- Always use HTTPS (Railway provides SSL automatically) +- Configure proper CORS settings +- Monitor your `/health/` endpoint for unauthorized access + +### Database Security +- Railway PostgreSQL is automatically encrypted +- Enable database backups (Railway provides automatic backups) +- Monitor database performance and queries + +## 📈 Performance Optimization + +### Railway-Specific Optimizations +1. **Region Selection**: Choose region closest to your users +2. **Resource Allocation**: Monitor CPU/memory usage in dashboard +3. **Caching**: Redis is automatically configured for session caching +4. **Static Files**: WhiteNoise serves static files efficiently + +### Monitoring & Alerts +1. Set up monitoring for your `/health/` endpoint +2. Configure alerts for high error rates +3. Monitor database performance metrics +4. Track user registration and payment success rates + +## 🎉 Success! + +Once deployed successfully, your Quantum Tasks AI application will be live at: +- **Production URL**: `https://your-domain.railway.app` +- **Custom Domain**: `https://quantumtaskai.com` (if configured) +- **Health Check**: `https://your-domain.railway.app/health/` +- **Admin Panel**: `https://your-domain.railway.app/admin/` + +Your AI agent marketplace is now ready to serve users worldwide! 🌍 + +## 📞 Support + +If you encounter issues: +1. Check Railway application logs first +2. Verify all environment variables are set correctly +3. Test the `/health/` endpoint for system status +4. Review this deployment guide for common solutions + +Railway.app provides excellent documentation and support for Django applications. \ No newline at end of file diff --git a/RAILWAY_ENV_TEMPLATE.md b/RAILWAY_ENV_TEMPLATE.md new file mode 100644 index 0000000..fb98b62 --- /dev/null +++ b/RAILWAY_ENV_TEMPLATE.md @@ -0,0 +1,205 @@ +# 🔐 Railway Environment Variables Template + +## Required Environment Variables for Production Deployment + +Copy these environment variables to your Railway project settings. Replace placeholder values with your actual production values. + +### 🔒 Core Security Settings +```bash +# Django Security +SECRET_KEY=django-insecure-REPLACE-WITH-50-RANDOM-CHARACTERS-FOR-PRODUCTION +DEBUG=False +ALLOWED_HOSTS=your-project-name.railway.app,quantumtaskai.com,www.quantumtaskai.com +CSRF_TRUSTED_ORIGINS=https://your-project-name.railway.app,https://quantumtaskai.com,https://www.quantumtaskai.com +``` + +### 📧 Email Configuration (Gmail Example) +```bash +# Email Settings - Use Gmail App Password or SMTP service +EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend +EMAIL_HOST=smtp.gmail.com +EMAIL_PORT=587 +EMAIL_USE_TLS=True +EMAIL_HOST_USER=your-email@gmail.com +EMAIL_HOST_PASSWORD=your-16-character-app-password +DEFAULT_FROM_EMAIL=Quantum Tasks AI +``` + +### 💳 Stripe Payment Configuration +```bash +# Stripe - Use LIVE keys for production +STRIPE_SECRET_KEY=sk_live_your_stripe_secret_key_here +STRIPE_WEBHOOK_SECRET=whsec_your_webhook_endpoint_secret +``` + +### 🤖 N8N AI Agent Webhooks +```bash +# N8N Webhook URLs - Replace with your N8N instance +N8N_WEBHOOK_DATA_ANALYZER=https://your-n8n-instance.com/webhook/data-analyzer +N8N_WEBHOOK_FIVE_WHYS=https://your-n8n-instance.com/webhook/five-whys +N8N_WEBHOOK_JOB_POSTING=https://your-n8n-instance.com/webhook/job-posting +N8N_WEBHOOK_SOCIAL_ADS=https://your-n8n-instance.com/webhook/social-ads +N8N_WEBHOOK_FAQ_GENERATOR=https://your-n8n-instance.com/webhook/faq-generator +``` + +### 🌤️ External API Keys +```bash +# OpenWeather API for Weather Agent +OPENWEATHER_API_KEY=your_openweather_api_key_here +``` + +### ⚡ Performance & Caching (Optional) +```bash +# Redis URL - Automatically set by Railway Redis service +# REDIS_URL=redis://default:password@host:port +``` + +--- + +## 🔍 Environment Variable Setup Instructions + +### Step 1: Generate SECRET_KEY +Use Django to generate a secure secret key: +```python +from django.core.management.utils import get_random_secret_key +print(get_random_secret_key()) +``` + +### Step 2: Gmail App Password Setup +1. Enable 2-Factor Authentication on your Gmail account +2. Go to Google Account Settings → Security → App passwords +3. Generate an app password for "Django Email" +4. Use the 16-character app password (not your regular password) + +### Step 3: Stripe Configuration +1. Login to your Stripe Dashboard +2. Go to Developers → API Keys +3. Copy your "Secret key" (starts with `sk_live_` for production) +4. Go to Developers → Webhooks +5. Create webhook endpoint: `https://your-domain.railway.app/wallet/stripe/webhook/` +6. Copy the webhook signing secret (starts with `whsec_`) + +### Step 4: N8N Webhook URLs +1. Deploy your N8N instance (can use Railway, Heroku, or self-hosted) +2. Create workflows for each AI agent +3. Copy the webhook URLs from each workflow +4. Ensure N8N workflows are active and accessible + +### Step 5: OpenWeather API +1. Sign up at [OpenWeatherMap](https://openweathermap.org/api) +2. Get your free API key +3. Add it to the environment variables + +--- + +## 🚫 Important Security Notes + +### Never Include in Git: +- ❌ Real SECRET_KEY values +- ❌ Production API keys +- ❌ Email passwords +- ❌ Stripe live keys +- ❌ Database credentials + +### Railway Automatic Variables: +Railway automatically provides these - **DO NOT SET MANUALLY**: +- `DATABASE_URL` (PostgreSQL connection string) +- `PORT` (Application port) +- `RAILWAY_*` (Railway-specific variables) + +### Testing Configuration: +Use Railway's "Preview" deployments to test environment variables before going live. + +--- + +## 📋 Environment Variable Checklist + +Before deploying, verify you have set: + +### Core Settings ✓ +- [ ] `SECRET_KEY` (50+ random characters) +- [ ] `DEBUG=False` +- [ ] `ALLOWED_HOSTS` (includes your Railway domain) +- [ ] `CSRF_TRUSTED_ORIGINS` (HTTPS URLs only) + +### Email Configuration ✓ +- [ ] `EMAIL_HOST_USER` (your Gmail address) +- [ ] `EMAIL_HOST_PASSWORD` (Gmail app password) +- [ ] `DEFAULT_FROM_EMAIL` (your sender email) + +### Payment System ✓ +- [ ] `STRIPE_SECRET_KEY` (live key for production) +- [ ] `STRIPE_WEBHOOK_SECRET` (webhook endpoint secret) + +### AI Agents ✓ +- [ ] All `N8N_WEBHOOK_*` URLs are accessible +- [ ] `OPENWEATHER_API_KEY` (for weather agent) + +### External Services ✓ +- [ ] PostgreSQL database added to Railway project +- [ ] Redis service added (optional but recommended) +- [ ] Custom domain configured (if applicable) + +--- + +## 🔧 Advanced Configuration + +### Production-Ready Gunicorn Settings +The `railway.json` includes optimized Gunicorn configuration: +- 2 workers (scales with CPU cores) +- 120-second timeout for AI processing +- Request recycling for memory management +- Health check integration + +### Database Connection Pooling +Railway's PostgreSQL automatically handles connection pooling for optimal performance. + +### Static Files & CDN +WhiteNoise configuration in your Django settings handles static file serving efficiently. + +--- + +## 🎯 Environment Variable Testing + +After setting variables in Railway: + +1. **Deploy Application**: Railway will automatically deploy with new variables +2. **Check Health Endpoint**: `https://your-domain.railway.app/health/` +3. **Test Authentication**: Try user registration and login +4. **Verify Payments**: Test Stripe integration (use test cards) +5. **Check AI Agents**: Test each agent workflow +6. **Monitor Logs**: Watch Railway application logs for errors + +--- + +## 🆘 Troubleshooting + +### Common Issues: + +**Secret Key Error:** +``` +django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty +``` +→ Ensure SECRET_KEY is set and not empty + +**Email Authentication Failed:** +``` +SMTPAuthenticationError: Username and Password not accepted +``` +→ Use Gmail App Password, not regular password + +**Stripe Webhook Verification Failed:** +``` +stripe.error.SignatureVerificationError +``` +→ Verify webhook secret matches Stripe dashboard + +**N8N Webhook Not Responding:** +``` +requests.exceptions.ConnectionError +``` +→ Ensure N8N instance is running and accessible + +--- + +This template ensures your Quantum Tasks AI application runs securely and efficiently on Railway.app! 🚀 \ No newline at end of file diff --git a/core/urls.py b/core/urls.py index 3019d92..e4eb6ee 100644 --- a/core/urls.py +++ b/core/urls.py @@ -7,4 +7,5 @@ urlpatterns = [ path('', views.homepage_view, name='homepage'), path('pricing/', views.pricing_view, name='pricing'), path('contact/', views.contact_form_view, name='contact_form'), + path('health/', views.health_check_view, name='health_check'), ] \ No newline at end of file diff --git a/core/views.py b/core/views.py index 8ed25d2..b52adc8 100644 --- a/core/views.py +++ b/core/views.py @@ -8,8 +8,10 @@ from django_ratelimit.decorators import ratelimit from django_ratelimit import UNSAFE from agent_base.models import BaseAgent from .models import ContactSubmission +from django.db import connection import logging import re +import time logger = logging.getLogger(__name__) @ratelimit(key='ip', rate='60/m', method='GET', block=False) @@ -210,3 +212,52 @@ def contact_form_view(request): 'success': False, 'error': 'Unable to process your message at this time. Please try again later.' }, status=500) + + +@ratelimit(key='ip', rate='60/m', method='GET', block=False) +def health_check_view(request): + """Health check endpoint for monitoring and load balancers""" + start_time = time.time() + health_data = { + 'status': 'healthy', + 'timestamp': int(time.time()), + 'version': '1.0', + 'checks': {} + } + + try: + # Database connectivity check + with connection.cursor() as cursor: + cursor.execute("SELECT 1") + health_data['checks']['database'] = { + 'status': 'healthy', + 'response_time_ms': round((time.time() - start_time) * 1000, 2) + } + except Exception as e: + health_data['status'] = 'unhealthy' + health_data['checks']['database'] = { + 'status': 'unhealthy', + 'error': str(e) + } + + # Check if agents can be queried + try: + agent_count = BaseAgent.objects.filter(is_active=True).count() + health_data['checks']['agents'] = { + 'status': 'healthy', + 'active_count': agent_count + } + except Exception as e: + health_data['status'] = 'unhealthy' + health_data['checks']['agents'] = { + 'status': 'unhealthy', + 'error': str(e) + } + + # Overall response time + health_data['response_time_ms'] = round((time.time() - start_time) * 1000, 2) + + # Return appropriate status code + status_code = 200 if health_data['status'] == 'healthy' else 503 + + return JsonResponse(health_data, status=status_code) diff --git a/netcop_hub/settings.py b/netcop_hub/settings.py index a3c2ccb..c1e737b 100644 --- a/netcop_hub/settings.py +++ b/netcop_hub/settings.py @@ -29,12 +29,24 @@ SECRET_KEY = config('SECRET_KEY') # Validate required environment variables required_env_vars = ['SECRET_KEY'] + +# Add production-specific required variables when DEBUG=False +debug_mode = config('DEBUG', default=True, cast=bool) +if not debug_mode: + required_env_vars.extend([ + 'ALLOWED_HOSTS', + 'EMAIL_HOST_USER', + 'EMAIL_HOST_PASSWORD', + 'STRIPE_SECRET_KEY', + ]) + missing_vars = [var for var in required_env_vars if not config(var, default='')] if missing_vars: import sys print(f"❌ Missing required environment variables: {', '.join(missing_vars)}") print("💡 Please create a .env file based on .env.example") print("💡 For local development, copy .env.example to .env and fill in the values") + print("💡 For production, ensure all required environment variables are set") sys.exit(1) # SECURITY WARNING: don't run with debug turned on in production! @@ -264,7 +276,12 @@ N8N_WEBHOOK_SOCIAL_ADS = config('N8N_WEBHOOK_SOCIAL_ADS', default='') OPENWEATHER_API_KEY = config('OPENWEATHER_API_KEY', default='') # Email Configuration -EMAIL_BACKEND = config('EMAIL_BACKEND', default='django.core.mail.backends.console.EmailBackend') +# Use SMTP backend in production, console in development +if DEBUG: + EMAIL_BACKEND = config('EMAIL_BACKEND', default='django.core.mail.backends.console.EmailBackend') +else: + EMAIL_BACKEND = config('EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend') + EMAIL_HOST = config('EMAIL_HOST', default='smtp.gmail.com') EMAIL_PORT = config('EMAIL_PORT', default=587, cast=int) EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=True, cast=bool) @@ -273,6 +290,9 @@ EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default='') EMAIL_FILE_PATH = config('EMAIL_FILE_PATH', default='/tmp/app-messages') DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL', default='Quantum Tasks AI ') +# Email timeout settings for production stability +EMAIL_TIMEOUT = 30 + # Security settings CSRF_TRUSTED_ORIGINS = [origin.strip() for origin in config('CSRF_TRUSTED_ORIGINS', default='').split(',') if origin.strip()] @@ -283,6 +303,18 @@ if config('RAILWAY_ENVIRONMENT', default=''): CSRF_TRUSTED_ORIGINS.append(f'https://{railway_url}') # Also add production domain CSRF_TRUSTED_ORIGINS.append('https://quantumtaskai.com') + + # Railway-specific optimizations + USE_X_FORWARDED_HOST = True + USE_X_FORWARDED_PORT = True + + # Database connection optimization for Railway PostgreSQL + if 'default' in DATABASES: + DATABASES['default']['CONN_MAX_AGE'] = 600 # 10 minutes connection pooling + if 'OPTIONS' not in DATABASES['default']: + DATABASES['default']['OPTIONS'] = {} + DATABASES['default']['OPTIONS']['MAX_CONNS'] = 20 + SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Default primary key field type diff --git a/railway.json b/railway.json index d8a7c84..78714c7 100644 --- a/railway.json +++ b/railway.json @@ -4,8 +4,10 @@ "builder": "NIXPACKS" }, "deploy": { - "startCommand": "python manage.py migrate --fake-initial || python manage.py migrate --fake data_analyzer 0002 || python manage.py migrate && python manage.py backup_users --action info && python manage.py populate_agents && python manage.py collectstatic --noinput && gunicorn netcop_hub.wsgi:application", + "startCommand": "python manage.py migrate --fake-initial || python manage.py migrate --fake data_analyzer 0002 || python manage.py migrate && python manage.py backup_users --action info && python manage.py populate_agents && python manage.py collectstatic --noinput && gunicorn netcop_hub.wsgi:application --bind 0.0.0.0:$PORT --workers 2 --timeout 120 --keep-alive 2 --max-requests 1000 --max-requests-jitter 100", "restartPolicyType": "ON_FAILURE", - "restartPolicyMaxRetries": 10 + "restartPolicyMaxRetries": 10, + "healthcheckPath": "/health/", + "healthcheckTimeout": 30 } } \ No newline at end of file diff --git a/templates/404.html b/templates/404.html new file mode 100644 index 0000000..2c5e417 --- /dev/null +++ b/templates/404.html @@ -0,0 +1,93 @@ +{% extends 'base.html' %} +{% load static %} + +{% block title %}Page Not Found - Quantum Tasks AI{% endblock %} + +{% block extra_css %} + +{% endblock %} + +{% block content %} +
+
🔍
+

Page Not Found

+

+ The page you're looking for doesn't exist or has been moved. + Don't worry, let's get you back on track to explore our AI assistants. +

+ +
+{% endblock %} \ No newline at end of file diff --git a/templates/500.html b/templates/500.html new file mode 100644 index 0000000..ad906ab --- /dev/null +++ b/templates/500.html @@ -0,0 +1,108 @@ +{% load static %} + + + + + + Server Error - Quantum Tasks AI + + + + +
+
⚠️
+

Server Error

+

+ We're experiencing technical difficulties. Our team has been notified + and is working to resolve the issue. Please try again in a few minutes. +

+ +
+

Error ID: {{ request.META.HTTP_X_REQUEST_ID|default:"N/A" }}

+

Time:

+
+
+ + + + \ No newline at end of file