# Backend Documentation Index ## Overview This directory contains comprehensive documentation of the Biblical Guide backend architecture. The analysis covers the complete backend system including database design, authentication, APIs, payment processing, and admin functionality. ## Documentation Files ### 1. BACKEND_ARCHITECTURE_ANALYSIS.md (Primary Document) **Size**: 29 KB | **Lines**: 890 | **Sections**: 13 Complete architectural documentation covering: - **Section 1**: Database Schema (32 models) - User Management - Bible Data Models - User Content Models - Communication Models - Prayer System Models - Reading Plans Models - Payment & Subscription Models - Content Management Models - User Preferences - **Section 2**: Authentication System - JWT Token Architecture - User Registration/Login Flow - Admin Authentication - Permission System - Client-Side Auth Management - **Section 3**: Payment & Subscription System - Stripe Configuration - Donation Flow - Subscription Flow - Webhook Handling - Conversation Limit Management - **Section 4**: API Structure & Endpoints - Framework & Runtime - 12 API Categories - 70+ Documented Endpoints - Request/Response Patterns - **Section 5**: Key Business Logic - Conversation Limit System - Prayer System Features - Reading Plans - Chat System - Vector Search - Admin Features - **Section 6-13**: Additional Topics - External Integrations - File Storage - Technology Stack - Environment Variables - Current Status & Notes - Data Relationships - API Response Patterns - Deployment Considerations **Best For**: Comprehensive understanding, onboarding new developers, system design decisions --- ### 2. BACKEND_QUICK_REFERENCE.md (Quick Lookup) **Size**: 9.2 KB | **Lines**: 353 | **Sections**: 14 Quick reference guide for common tasks: - **Model Index**: 32 models organized by category - **Authentication Table**: Endpoints, methods, auth requirements - **API Endpoints**: Organized by category with example URLs - **Subscription Tiers**: Feature comparison table - **Data Constraints**: Unique constraints and cascades - **Webhook Events**: Stripe events and their effects - **Admin Permissions**: Role-based access matrix - **Limits & Defaults**: Important configuration values - **Query Patterns**: Common Prisma queries - **Environment Checklist**: Required variables - **Development Tasks**: Common npm scripts - **Performance Tips**: Optimization guidelines - **Troubleshooting**: Common issues and solutions - **Resource Links**: External documentation **Best For**: Day-to-day reference, quick lookups, during development --- ## Key Information at a Glance ### Technology Stack | Component | Technology | Version | |-----------|-----------|---------| | Framework | Next.js | 15.5.3 | | Database | PostgreSQL | Latest | | ORM | Prisma | 6.16.2 | | Auth | JWT | via jsonwebtoken 9.0.2 | | Payments | Stripe | 19.1.0 | | Email | Mailgun | 12.0.3 | | AI | Azure OpenAI | Custom | | Validation | Zod | 3.25.76 | ### Database Statistics - **Total Models**: 32 - **Total Indexes**: 25+ - **Unique Constraints**: 20+ - **Foreign Key Cascades**: 8 - **Text Fields**: 15+ (for long content) - **JSON Fields**: 5 (for flexible data) ### API Statistics - **Total Endpoints**: 70+ - **Public Endpoints**: 15 - **Protected Endpoints**: 40 - **Admin Endpoints**: 25+ - **Webhook Endpoints**: 2 - **Categories**: 12 ### Authentication - **User Token Expiry**: 7 days - **Admin Token Expiry**: 24 hours (8 hours for cookie) - **Password Hash Rounds**: 10 (bcryptjs) - **Session Expiry**: 7 days - **Admin Roles**: Admin, Moderator - **Permission Types**: 13 ### Subscription System - **Free Tier Limit**: 10 conversations/month - **Premium Tier Limit**: Unlimited - **Webhook Events Handled**: 9+ - **Payment Methods**: Stripe (card) - **Donation Presets**: $5, $10, $25, $50, $100, $250 ## Quick Start References ### Common Tasks **Find Information About**: - Specific API endpoint → Search "API STRUCTURE" in ARCHITECTURE_ANALYSIS.md or check QUICK_REFERENCE.md - Database model → "DATABASE SCHEMA" in ARCHITECTURE_ANALYSIS.md or MODEL quick index - Authentication → "AUTHENTICATION SYSTEM" section - Payment flow → "PAYMENT & SUBSCRIPTION SYSTEM" section - Admin panel → "ADMIN ENDPOINTS" in QUICK_REFERENCE.md **For Development**: - Set up environment → QUICK_REFERENCE.md "Environment Setup Checklist" - Common database queries → QUICK_REFERENCE.md "Common Query Patterns" - API testing → Check each endpoint in ARCHITECTURE_ANALYSIS.md Section 4 - Troubleshooting → QUICK_REFERENCE.md "Troubleshooting" section **For Deployment**: - Production checklist → ARCHITECTURE_ANALYSIS.md Section 13 - Environment variables → ARCHITECTURE_ANALYSIS.md Section 9 - Migrations → QUICK_REFERENCE.md "Common Development Tasks" - Monitoring → ARCHITECTURE_ANALYSIS.md "Monitoring & Logging" ## Data Models by Feature ### Bible Reading - BibleVersion, BibleBook, BibleChapter, BibleVerse - BiblePassage (with embeddings) - ReadingHistory ### User Content - Bookmark, ChapterBookmark - Highlight, Note - ReadingHistory ### User Engagement - PrayerRequest, Prayer, UserPrayer - ReadingPlan, UserReadingPlan, UserReadingProgress - ChatConversation, ChatMessage ### Monetization - Subscription, Donation - User (subscription fields) ### Administration - Page, MediaFile - SocialMediaLink, MailgunSettings ## Security Features ### Authentication - JWT-based token authentication - bcryptjs password hashing (10 rounds) - Session tracking in database - HttpOnly cookies for admin tokens - CSRF protection via SameSite ### Authorization - Role-based access control (User/Admin/Moderator) - Fine-grained permissions (13 types) - Per-endpoint permission checks - Cascade deletion on user removal ### Data Protection - Encrypted Mailgun API keys in database - Stripe webhook signature verification - Secure token generation (UUID) - Proper SQL parameter binding via Prisma ## Performance Optimizations ### Database - Strategic indexing on frequently queried fields - Composite indexes for complex queries - Unique constraints prevent duplicates - Select-only queries reduce data transfer - Proper relationship handling with include ### API - Bible version caching (1 hour + 2hr stale-while-revalidate) - Pagination for list endpoints - Selective field selection - Connection pooling via Prisma ### Frontend - JWT stored in localStorage - Client-side token expiration check - Lazy loading of relationships ## Disabled Features ### Chat Feature (Currently Disabled) - **Endpoint**: `POST /api/chat` - **Status**: Returns 503 Service Unavailable - **Reason**: Azure OpenAI configuration needed - **Features Blocked**: - AI responses - Vector search for Bible verses - Conversation persistence - Limit enforcement ### Password Reset - Structure in place but incomplete - Mailgun integration available - Email template defined ## Integration Points ### External Services 1. **Stripe** - Payments, subscriptions, webhooks 2. **Azure OpenAI** - AI chat responses 3. **Mailgun** - Email delivery 4. **PostgreSQL** - Data persistence 5. **pgvector** - Vector embeddings (optional) ### Internal Services 1. **JWT** - Token generation/verification 2. **bcryptjs** - Password hashing 3. **Zod** - Input validation 4. **Prisma** - Database ORM ## Contribution Guidelines When modifying the backend: 1. **Database Changes** - Update schema.prisma - Create migration: `npx prisma migrate dev` - Update BACKEND_ARCHITECTURE_ANALYSIS.md 2. **API Changes** - Follow existing patterns in /app/api - Use Zod schemas for validation - Add error handling with NextResponse - Update BACKEND_QUICK_REFERENCE.md endpoint list 3. **Authentication Changes** - Update lib/auth/* files - Verify JWT payload structure - Test with client-side auth management - Update ARCHITECTURE_ANALYSIS.md Section 2 4. **Payment Changes** - Update lib/stripe-server.ts or lib/subscription-utils.ts - Add/update webhook handlers - Update ARCHITECTURE_ANALYSIS.md Section 3 - Test with Stripe test keys ## Related Documents ### In This Directory - BACKEND_ARCHITECTURE_ANALYSIS.md (this document) - BACKEND_QUICK_REFERENCE.md - BACKEND_DOCUMENTATION_INDEX.md (this file) ### In Repository Root - README.md (project overview) - package.json (dependencies) - .env.example (environment template) ### Prisma Files - prisma/schema.prisma (database schema) - prisma/migrations/* (migration history) ## Useful Commands ```bash # Database npx prisma migrate deploy # Apply migrations npx prisma generate # Generate Prisma client npx prisma studio # Open database UI # Development npm run dev # Start dev server npm run build # Build for production npm run import-bible # Import Bible data # Analysis grep -r "export async function" app/api/ # Find all endpoints grep -r "model " prisma/schema.prisma # List all models ``` ## Support & Questions ### For Understanding 1. Read BACKEND_QUICK_REFERENCE.md first (faster) 2. Dive into BACKEND_ARCHITECTURE_ANALYSIS.md for details 3. Check specific endpoint files in app/api/ ### For Debugging 1. Check QUICK_REFERENCE.md "Troubleshooting" 2. Enable logging: `log: ['query', 'error']` in Prisma client 3. Use `npx prisma studio` to inspect data 4. Check API route logs and error messages ### For Adding Features 1. Plan database changes in schema.prisma 2. Create API route in app/api/ 3. Update documentation 4. Test with auth headers if needed 5. Configure webhooks if needed ## Version History | Date | Changes | Version | |------|---------|---------| | 2025-11-05 | Initial comprehensive analysis | 1.0 | --- **Last Updated**: November 5, 2025 **Document Version**: 1.0 **Backend Status**: Production-ready (chat feature disabled) For the latest information, always refer to the source files in `/root/biblical-guide/`.